Tuesday 8 May 2018

Volley API implementation

dependencies{
//Volley libs
implementation 'com.android.volley:volley:1.0.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.1'
implementation 'com.google.code.gson:gson:2.8.2'
}

android {
//Volley add lines
    useLibrary 'org.apache.http.legacy'
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'

    }
}

=================================================================================================

Create new class LruBitmapCache.java

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache {
private static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;

return cacheSize;
}

LruBitmapCache() {
this(getDefaultLruCacheSize());
}

private LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}

@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}

@Override
public Bitmap getBitmap(String url) {
return get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}

=================================================================================================

Create new class MultipartRequest.java

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

import org.apache.http.HttpEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

public class MultipartRequest extends Request {
//String KEY_PICTURE = "Post_Image";
private static final String TAG = "MutlipartRequest";

private HttpEntity mHttpEntity;
private final Class mClass;
private Response.Listener mListener;
private Map<String, String> mHeaders;
private Map<String, String> params;

public MultipartRequest(String mainUrl, HttpEntity httpEntity, Class clazz, Map<String, String> headers, Response.Listener listener, Response.ErrorListener errorListener) {
super(Method.POST, mainUrl, errorListener);
mHeaders = headers;
mClass = clazz;
mListener = listener;
mHttpEntity = httpEntity;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Log.d("TAG", "GET PARAM");
return mHeaders != null ? mHeaders : super.getHeaders();
}

@Override
public String getBodyContentType() {
return mHttpEntity.getContentType().getValue();
}

@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mHttpEntity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}

@SuppressWarnings("unchecked")
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
String json;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

} catch (UnsupportedEncodingException e) {
Log.e(TAG, String.format("Encoding problem parsing API response. NetworkResponse:%s",
response.toString()), e);
return Response.error(new ParseError(e));
}
try {
return Response.success(json, HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
Log.e(TAG, String.format("Couldn't API parse JSON response. NetworkResponse:%s",
response.toString()), e);
Log.e(TAG, String.format("Couldn't API parse JSON response. Json dump: %s", json));
return Response.error(new ParseError(e));
}
}

@Override
protected void deliverResponse(Object arg0) {
mListener.onResponse(arg0);
}

}

=================================================================================================

Create new class MyApplication

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * Created by msp on 6/7/16.
 */
public class MyApplication extends Application {
private static MyApplication appInstance;

private static Context mContext;

private static final String KEY_REMEBER = "REMEMBER";
public static final String TAG = MyApplication.class.getSimpleName();
private static final String KEY = "eCommerce";
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

@Override
public void onCreate() {
super.onCreate();
appInstance = this;
MyApplication.mContext = getApplicationContext();

}

public static boolean isConnectivityAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

public static Context getContext() {
return mContext;
}

public static void setContext(Context mctx) {
mContext = mctx;
}



public static synchronized MyApplication getInstance() {
return appInstance;
}




// for get getRequestQueue object
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}

return mRequestQueue;
}

// for get imageloader object
public com.android.volley.toolbox.ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new com.android.volley.toolbox.ImageLoader(this.mRequestQueue, new LruBitmapCache());
}
return this.mImageLoader;
}

// for add request to queue
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}

// for add request queue
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}

//for cancle pending request
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}

//for get keyhash of facebook
public void printKeyHash() {
try {
PackageInfo info = getPackageManager().getPackageInfo("com.weddingapp", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.e("NightLife", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {

} catch (NoSuchAlgorithmException e) {

}
}
}

=================================================================================================

Declare Application class in manifest file

android:name=".volley.MyApplication"

=================================================================================================

Create custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00000000"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

=================================================================================================

Create class VolleyJsonParser


import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.volleydataparsingdemo.R;

import org.json.JSONArray;

import java.util.HashMap;
import java.util.Map;

public class VolleyJsonParser {
    private Context context;
    private String s = null;
    private JSONArray objJson = null;
    private Map<String, String> mparams;
    private VolleyCallback mcallback;
    private VolleyCallback1 mcallback1;
    private Dialog dialog;

    public VolleyJsonParser(Context context) {
        this.context = context;
        initProcessDialog();
    }

    public JSONArray getObjectRequest(final ProgressBar pd, String url, final HashMap<String, String> params, VolleyCallback1 volleyCallback) {
        Log.d("TAG", url);
        // pd.setVisibility(View.VISIBLE);
        this.mparams = params;
        this.mcallback1 = volleyCallback;
        JsonArrayRequest req = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                objJson = response;
                mcallback1.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("TAG", "Error: " + error.getMessage());
                Log.e("onErrorResponse", "-->" + error.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                // TODO Auto-generated method stub
                return mparams;
            }
        };

        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(req, "jarray_req");
        return objJson;
    }

    public void makeStringReq(String url, final HashMap<String, String> params, VolleyCallback volleyCallback) {
        //showDialog();
        this.mparams = params;
        Log.d("TAG", "PARAM " + mparams);
        this.mcallback = volleyCallback;
        StringRequest strReq = new StringRequest(Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // Log.d("TAG", "Response==>" + response.toString());
                // pd.setVisibility(View.INVISIBLE);
//                dismissDialog();
                s = response;
                mcallback.onSuccess(response);

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
//                dismissDialog();
                VolleyLog.d("TAG", "Error: " + error.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                // TODO Auto-generated method stub
                return mparams;
            }

        };

        // Adding request to request queue
        ///strReq.setRetryPolicy(new DefaultRetryPolicy(10000, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        strReq.setRetryPolicy(new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        MyApplication.getInstance().addToRequestQueue(strReq, "string_req");

    }

    public interface VolleyCallback {
        void onSuccess(String result);
        void onFailure(String jsonResponse);
    }

    public interface VolleyCallback1 {
        void onSuccess(JSONArray result);
        void onFailure(JSONArray jsonResponse);
    }

    public void initProcessDialog() {

        ContextThemeWrapper themedContext;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            themedContext = new ContextThemeWrapper(context, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
        } else {
            themedContext = new ContextThemeWrapper(context, android.R.style.Theme_Light_NoTitleBar);
        }

        dialog = new Dialog(themedContext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.custom_dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialog.setCancelable(false);
    }

    public void showDialog() {
        try {
            if (dialog != null && (!dialog.isShowing())) {
                Log.d("TAG", "SHOW DIALOG");
                dialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissDialog() {
        try {
            if (dialog != null && dialog.isShowing()) {
                Log.d("TAG", "DISMISS DIALOG");
                dialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

=================================================================================================

Activity file
    VolleyJsonParser volleyParser;
    HashMap<String, String> params;
    RequestQueue requestQueue;
    ProductGridAdapter mAdapter;

onCreate {

volleyParser = new VolleyJsonParser(context);
        requestQueue = Volley.newRequestQueue(context);

//      RecyclerView.ItemDecoration itemDecoration1 = new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL);
//           recyclerView.addItemDecoration(itemDecoration1);

}

private void Forgotpassword() {
        volleyParser.showDialog();
        params = new HashMap<>();
        params.put("api", "forgetpassword");
        params.put("user_Email", "test@test.com");
        volleyParser.makeStringReq("https://swizletime.com/admin/main/frmSwizzleApi.php", params, vForgotpassword);
    }

VolleyJsonParser.VolleyCallback vForgotpassword = new VolleyJsonParser.VolleyCallback() {
        @Override
        public void onSuccess(String result) {
            // TODO Auto-generated method stub
            volleyParser.dismissDialog();
            Log.e("Result", ">>>>>>>>" + result);

            if (result != null) {
                String Result = null;
                try {

                    JSONObject json = new JSONObject(result);

                    String results = json.getString("result");
                    String message = null;
                    message = json.getString("message");
   
    if (results.equalsIgnoreCase("1")) {
//                        showAlertDialog(context, message);
                    } else if (results.equalsIgnoreCase("0")) {
//                        Utility.showAlertDialog(context, message);
                    }

//OR

    ProductResponse productResponse = new Gson().fromJson(response,
                            ProductResponse.class);

    if (productResponse.getStatus().equalsIgnoreCase("success")) {

    }
               
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                //no data found
                Log.e("TAG", " ---No Data found--- ");
            }
        }

        @Override
        public void onFailure(String jsonResponse) {
            // TODO Auto-generated method stub
            Log.e("TAG", "onFailure: " + jsonResponse);
        }
    };

That's it...

Tuesday 24 April 2018

Volley Json Request for api call Demo

Hi first of all add dependency on gradle file

//Volley libsimplementation 'com.android.volley:volley:1.0.0'implementation 'org.apache.httpcomponents:httpcore:4.4.1'

Add the below part on app build.gradle inside android { } block,

//Volley add linesuseLibrary 'org.apache.http.legacy'packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'    exclude 'META-INF/LICENSE.txt'    exclude 'META-INF/NOTICE.txt'    exclude 'META-INF/NOTICE'    exclude 'META-INF/LICENSE'    exclude 'META-INF/DEPENDENCIES'    exclude 'META-INF/notice.txt'    exclude 'META-INF/license.txt'    exclude 'META-INF/dependencies.txt'    exclude 'META-INF/LGPL2.1'
}

-> Create a LruBitmapCache.java class 

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache {
   public static int getDefaultLruCacheSize() {
      final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
      final int cacheSize = maxMemory / 8;

      return cacheSize;
   }

   public LruBitmapCache() {
      this(getDefaultLruCacheSize());
   }

   public LruBitmapCache(int sizeInKiloBytes) {
      super(sizeInKiloBytes);
   }

   @Override   protected int sizeOf(String key, Bitmap value) {
      return value.getRowBytes() * value.getHeight() / 1024;
   }

   @Override   public Bitmap getBitmap(String url) {
      return get(url);
   }

   @Override   public void putBitmap(String url, Bitmap bitmap) {
      put(url, bitmap);
   }
}

-> Create MyApplication class

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/** * Created by msp on 6/7/16. */public class MyApplication extends Application {
   private static MyApplication appInstance;

   private static Context mContext;

   private static final String KEY_REMEBER = "REMEMBER";
   public static final String TAG = MyApplication.class.getSimpleName();
   private static final String KEY = "eCommerce";
   private RequestQueue mRequestQueue;
   private ImageLoader mImageLoader;

   @Override   public void onCreate() {
      super.onCreate();
      appInstance = this;
      MyApplication.mContext = getApplicationContext();

   }

   public static boolean isConnectivityAvailable(Context context) {
      ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

      NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
      return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
   }

   public static Context getContext() {
      return mContext;
   }

   public static void setContext(Context mctx) {
      mContext = mctx;
   }



   public static synchronized MyApplication getInstance() {
      return appInstance;
   }




   // for get getRequestQueue object   public RequestQueue getRequestQueue() {
      if (mRequestQueue == null) {
         mRequestQueue = Volley.newRequestQueue(getApplicationContext());
      }

      return mRequestQueue;
   }

   // for get imageloader object   public com.android.volley.toolbox.ImageLoader getImageLoader() {
      getRequestQueue();
      if (mImageLoader == null) {
         mImageLoader = new com.android.volley.toolbox.ImageLoader(this.mRequestQueue, new LruBitmapCache());
      }
      return this.mImageLoader;
   }

   // for add request to queue   public <T> void addToRequestQueue(Request<T> req, String tag) {
      // set the default tag if tag is empty      req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
      getRequestQueue().add(req);
   }

   // for add request queue   public <T> void addToRequestQueue(Request<T> req) {
      req.setTag(TAG);
      getRequestQueue().add(req);
   }

   //for cancle pending request   public void cancelPendingRequests(Object tag) {
      if (mRequestQueue != null) {
         mRequestQueue.cancelAll(tag);
      }
   }

   //for get keyhash of facebook   public void printKeyHash() {
      try {
         PackageInfo info = getPackageManager().getPackageInfo("com.weddingapp", PackageManager.GET_SIGNATURES);
         for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.e("NightLife", Base64.encodeToString(md.digest(), Base64.DEFAULT));
         }
      } catch (PackageManager.NameNotFoundException e) {

      } catch (NoSuchAlgorithmException e) {

      }
   }
}

-- Register application class in android Manifest file
ex - 

    android:name=".volley.MyApplication"


-> Create custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#00000000"    android:orientation="vertical" >

    <ProgressBar        android:id="@+id/progressBar1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true" />

</RelativeLayout>

-> Create 





Tuesday 6 March 2018

Android Take Photo From Camera and Gallery - Code Sample

Objective

The main objective of this post is to help you understand how to take photo /picture/image from the camera or gallery in your Android phone. 


User will have two choices:
  1. Capture photo/ image from camera in Android
  2. Choose photo/ image from gallery in Android
User will need to choose one option from the above two options and then depending on the option chosen by the user, we will either capture an image from the camera or open the gallery.

You will get Final Output:



Step 1 Create Layout

First, we'll show a button to user – user can click the button and we'll give an option to user where he can get image from the camera or get image from gallery in Android. Lets get started with creating the layout
  • <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  •     xmlns:tools="http://schemas.android.com/tools"
  •     android:id="@+id/LinearLayout1"
  •     android:layout_width="match_parent"
  •     android:layout_height="match_parent"
  •     android:orientation="vertical"
  •     android:padding="10dp" >
  •  
  •     <LinearLayout
  •         android:layout_width="match_parent"
  •         android:layout_height="wrap_content"
  •         android:gravity="center"
  •         android:padding="5dp" >
  •  
  •         <Button
  •             android:id="@+id/btnSelectPhoto"
  •             android:layout_width="match_parent"
  •             android:layout_height="wrap_content"
  •             android:text="Select Photo" />
  •  
  •     </LinearLayout>
  •  
  •     <LinearLayout
  •         android:layout_width="match_parent"
  •         android:layout_height="wrap_content"
  •         android:gravity="center"
  •         android:orientation="vertical"
  •         android:padding="10dp" >
  •  
  •         <ImageView
  •             android:id="@+id/ivImage"
  •             android:layout_width="wrap_content"
  •             android:layout_height="wrap_content"
  •             android:src="@drawable/ic_launcher" />
  •     </LinearLayout>
  •  
  • </LinearLayout>

Step 2 Create options Dialog box

>> We want show the dialog box to user with options when user clicks on the Select Photo button.

So for this, we will create new method into MainActivity File called selectImage() Method. In this method we'll create the dialog box with the three options you can see in the screenshot above.
  • private void selectImage() {
  • final CharSequence[] items = { "Take Photo", "Choose from Library",
  • "Cancel" };
  • AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
  • builder.setTitle("Add Photo!");
  • builder.setItems(items, new DialogInterface.OnClickListener() {
  • @Override
  • public void onClick(DialogInterface dialog, int item) {
  • boolean result=Utility.checkPermission(MainActivity.this);
  • if (items[item].equals("Take Photo")) {
  • userChoosenTask="Take Photo";
  • if(result)
  • cameraIntent();
  • } else if (items[item].equals("Choose from Library")) {
  • userChoosenTask="Choose from Library";
  • if(result)
  • galleryIntent();
  • } else if (items[item].equals("Cancel")) {
  • dialog.dismiss();
  • }
  • }
  • });
  • builder.show();
  • }
Let's dig deeper and see what exactly we are doing in this method

2.1 Set Dialogbox Items

  • final CharSequence[] items = { "Take Photo", "Choose from Library",
  • "Cancel" };
  • AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
  • builder.setTitle("Add Photo!");
We are creating an AlertDialog with three items as given in an array called items, And in last line we are setting the title for the Dialog box as Add Photo! Now, lets see what we are doing when user chooses any of the options.

2.2 Requesting Permission at Runtime

If you are using a device having MarshMallow version of Android, then your application will definitely crash or will not work properly without calling below method.
  • boolean result=Utility.checkPermission(MainActivity.this);
Here, checkPermission() method checks the permission for storage group at runtime. Even if you have declared permission in AndroidManifest file, you need to check Runtime Permission in MarshMallow.
Let’s look at checkPermission() method:
  • public class Utility {
  • public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
  • @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  • public static boolean checkPermission(final Context context)
  • {
  • int currentAPIVersion = Build.VERSION.SDK_INT;
  • if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
  • {
  • if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  • if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
  • AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
  • alertBuilder.setCancelable(true);
  • alertBuilder.setTitle("Permission necessary");
  • alertBuilder.setMessage("External storage permission is necessary");
  • alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
  • @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  • public void onClick(DialogInterface dialog, int which) {
  • ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
  • }
  • });
  • AlertDialog alert = alertBuilder.create();
  • alert.show();
  • } else {
  • ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
  • }
  • return false;
  • } else {
  • return true;
  • }
  • } else {
  • return true;
  • }
  • }
  • }
This method will check permission at runtime for Marshmallow & greater than Marshmallow version.
If current API version is less than Marshmallow, then checkPermission() will return true, which means permission is granted (in Manifest file, no support for runtime permission).
If current API version is Marshmallow or greater, and if permission is already granted then the method returns true. Otherwise, the method returns false and will show a dialog box to a user with allow or deny options.

2.3 Check for Camera Request

  • if (items[item].equals("Take Photo")) {
  • userChoosenTask="Take Photo";
  • if(result)
  • cameraIntent();
  • }
If user chooses Take Photo option:
Here, I stored Take Photo in String variable userChoosenTask. This variable will be used in onRequestPermissionsResult() method to check which item is selected.
If permission has already been granted previously, then ‘result’ variable will contain true & call cameraIntent() method.
Let’s look at cameraIntent() method:
  • private void cameraIntent()
  • {
  • Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  • startActivityForResult(intent, REQUEST_CAMERA);
  • }
We are calling Implicit Intent to open the camera application on user's phone.
  • Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Learn more about Implicit Intent here please refer the following link:
Check the list of Common Intents here from the below link:
>> We are starting the Camera Activity, but instead of passing the intent in startActivity() we are passing the intent in method startActivityForResult(). This method will give us a result back. In our case, it will give us an image capture by camera.
  • startActivityForResult(intent, REQUEST_CAMERA);
Learn more about startActivityForResult() please refer the following link:
Now, we'll learn how to pick image from gallery in Android.

2.4 Check for Gallery Request

  • else if (items[item].equals("Choose from Library")) {
  • userChoosenTask="Choose from Library";
  • if(result)
  • galleryIntent();
  • }
If user chooses Take Photo option:
  • Here, I stored “Choose from Library” in String variable userChoosenTask. This variable will be used in onRequestPermissionsResult() method to check which item is selected.
  • If permission has already been granted previously, then ‘result’ variable will contain true & call galleryIntent() method.
Let’s look at galleryIntent() method:
  • private void galleryIntent()
  • {
  • Intent intent = new Intent();
  • intent.setType("image/*");
  • intent.setAction(Intent.ACTION_GET_CONTENT);//
  • startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
  • }
Similar to what we have done with the previous option, again we are calling an implicit intent to open the gallery and than calling startActivityForResult() and passing the intent.
  • intent.setType("image/*");
This line is used to select only images from the media storage.
Tip:  if you want to get images as well as videos, you can use following code
  • intent.setType("image/* video/*");
I think rest of the stuff is self-explanatory in this file. Lets move forward.

2.5 Grant Permission at Runtime

If permission has not been granted, then checkPermssion() method will display a dialog to user with two options.
  1. Allow the permission request or
  2. Deny the permission request
onRequestPermissionsResult() is inbuilt method which receives a callback of this dialog action for particular activity from which checkPermssion() has been called
  • @Override
  • public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  • switch (requestCode) {
  • case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
  • if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  • if(userChoosenTask.equals("Take Photo"))
  • cameraIntent();
  • else if(userChoosenTask.equals("Choose from Library"))
  • galleryIntent();
  • } else {
  • //code for deny
  • }
  • break;
  • }
  • }
If permission has been granted then the value of grantResults[0] would be PERMISSION_GRANTED. And if permission has been revoked then the value of grantResults[0] would be PERMISSION_DENIED.
Here, if permission has been granted, then I am calling method for specific Intent according to value of userChoosenTask variable.

Step 3 Handling Image

Now, we have got the image either from camera or from gallery, its time to handle that image. We need handle the result we have received by calling startActivityForResult() Method. So add onActivityResult() Method into Main activity class.
>> The code will look something like this:
  • @Override
  • public void onActivityResult(int requestCode, int resultCode, Intent data) {
  • super.onActivityResult(requestCode, resultCode, data);
  • if (resultCode == Activity.RESULT_OK) {
  • if (requestCode == SELECT_FILE)
  • onSelectFromGalleryResult(data);
  • else if (requestCode == REQUEST_CAMERA)
  • onCaptureImageResult(data);
  • }
  • }
  • @SuppressWarnings("deprecation")
  • private void onSelectFromGalleryResult(Intent data) {
  • Bitmap bm=null;
  • if (data != null) {
  • try {
  • bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
  • } catch (IOException e) {
  • e.printStackTrace();
  • }
  • }
  • ivImage.setImageBitmap(bm);
  • }
  • private void onCaptureImageResult(Intent data) {
  • Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
  • ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  • thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
  • File destination = new File(Environment.getExternalStorageDirectory(),
  • System.currentTimeMillis() + ".jpg");
  • FileOutputStream fo;
  • try {
  • destination.createNewFile();
  • fo = new FileOutputStream(destination);
  • fo.write(bytes.toByteArray());
  • fo.close();
  • } catch (FileNotFoundException e) {
  • e.printStackTrace();
  • } catch (IOException e) {
  • e.printStackTrace();
  • }
  • ivImage.setImageBitmap(thumbnail);
  • }
As mentioned earlier, onActivityResult() Method handles the results we have received.
Lets dissect the code and see what it does.
When we are taking an image from the camera:

3.1 onActivityResult() Method

  • @Override
  • protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  • super.onActivityResult(requestCode, resultCode, data);
Arguments:
int requestCode
The request code is what you have passed to startActivityForResult(). In our case it is REQUEST_CAMERA.
int resultCode
RESULT_OK if the operation was successful or
RESULT_CANCEL if the operation was somehow cancelled or unsuccessful.
intent dataThe intent carries the result data – in our case it is the image we have captured from the camera.
Bitmap.CompressFormat format
This argument states the format of a compressed image –
can be JPEG, PNG, WEBP More about CompressFormat class over here:
int quality
Quality on the scale of 0 to 100, with 0 being the lowest and 100 being the highest. PNG is lossless compression, so it will ignore the quality settings.
OutputStream streamThe stream to write the compressed data.

You can learn about onActivityResult() from the below link:
Next, we are handling the input we have received from Camera

3.2 Handling Camera Request For Capturing an Image

  • if (resultCode == RESULT_OK) {
  • if (requestCode == REQUEST_CAMERA) {
Here we are just checking if our operation was successful by checking RESULT_OK and then checking if the requestCode is REQUEST_CAMERA. If the both the conditions are satisfied, we move forward.
  • Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
We get our data in our Intent, so we are first getting that data through data.getsExtras().get("data") and then we are casting that data into Bitmap since we want it as an image.
  • ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  • thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
We want to make thumbnail of an image, so we need to first take the ByteArrayOutputStream and than pass it into thumbnail.compress() method.
Arguments:

Learn more about Bitmap.compress() method please refer the following link:
  • File destination = new File(Environment.getExternalStorageDirectory(),
  • System.currentTimeMillis() + ".jpg");
  • FileOutputStream fo;
  • try {
  • destination.createNewFile();
  • fo = new FileOutputStream(destination);
  • fo.write(bytes.toByteArray());
  • fo.close();
  • } catch (FileNotFoundException e) {
  • e.printStackTrace();
  • } catch (IOException e) {
  • e.printStackTrace();
  • }
Now, we are storing the file we have created into External Storage.
If you want to learn more about it, please refer the following link:
  • ivImage.setImageBitmap(thumbnail);
And in the end, we are just setting up the bitmap in our imageView.
When we select image from the gallery

3.3 Handling Gallery Request For Selecting Image

  • if (requestCode == SELECT_FILE)
  • onSelectFromGalleryResult(data);
On selecting image from gallery, onSelectFromGalleryResult(data) will be called
  • private void onSelectFromGalleryResult(Intent data) {
  • Bitmap bm=null;
  • if (data != null) {
  • try {
  • bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
  • } catch (IOException e) {
  • e.printStackTrace();
  • }
  • }
  • ivImage.setImageBitmap(bm);
  • }
Android saves the images in its own database. We can fetch it using different ways. I have used MediaStore.Images.Media.getBitmap() here.
Learn more about MediaStore.Images.Media please refer the following link:
Here, I am fetching image from specific path(here, data.getData() ) as Bitmap by calling getBitmap() method & displaying it in ImageView.

Step 4 Add permission to manifest file

  • <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  • <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For generating bitmap we need to add WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permission.
I hope you enjoy this tutorial and you have learnt how to get image from gallery or caputre image from camera in Android.
  •  
  •  
  •