Skip to content Skip to sidebar Skip to footer

App Is Crashing When We Upload The Image From Gallery?

I am new in android so, if you found any mistake please tell me.Now come to the point what i got the problem we click on image view then one popup will come and choose from where y

Solution 1:

try this: java code:

publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener {

privatestaticfinalintSELECT_PICTURE=100;
privatestaticfinalStringTAG="MainActivity";

CoordinatorLayout coordinatorLayout;
FloatingActionButton btnSelectImage;
AppCompatImageView imgView;


@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbartoolbar= (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Find the views...
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
    btnSelectImage = (FloatingActionButton) findViewById(R.id.btnSelectImage);
    imgView = (AppCompatImageView) findViewById(R.id.imgView);

    btnSelectImage.setOnClickListener(this);

}

/* Choose an image from Gallery */voidopenImageChooser() {
    Intentintent=newIntent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}

publicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            // Get the url from dataUriselectedImageUri= data.getData();
            if (null != selectedImageUri) {
                // Get the path from the UriStringpath= getPathFromURI(selectedImageUri);
                Log.i(TAG, "Image Path : " + path);
                // Set the image in ImageView
                imgView.setImageURI(selectedImageUri);
            }
        }
    }
}

/* Get the real path from the URI */public String getPathFromURI(Uri contentUri) {
    Stringres=null;
    String[] proj = {MediaStore.Images.Media.DATA};
    Cursorcursor= getContentResolver().query(contentUri, proj, null, null, null);
    if (cursor.moveToFirst()) {
        intcolumn_index= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        res = cursor.getString(column_index);
    }
    cursor.close();
    return res;
}

@OverridepublicvoidonClick(View v) {
    openImageChooser();
}

}

Add Permission

<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE" />

layout:

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:theme="@style/AppTheme.AppBarOverlay"><android.support.v7.widget.Toolbarandroid:id="@+id/toolbar"android:layout_width="match_parent"android:layout_height="?attr/actionBarSize"android:background="?attr/colorPrimary"app:popupTheme="@style/AppTheme.PopupOverlay" /></android.support.design.widget.AppBarLayout><android.support.v7.widget.AppCompatImageViewandroid:id="@+id/imgView"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_margin="@dimen/activity_horizontal_margin" /><android.support.design.widget.FloatingActionButtonandroid:id="@+id/btnSelectImage"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="bottom|end"android:layout_margin="@dimen/fab_margin"android:src="@android:drawable/ic_menu_gallery" /></android.support.design.widget.CoordinatorLayout>

Solution 2:

You are receiving an OutOfMemoryException since you are talking about several images. Here are your options:

  • Request a larger heap from the virtual machine by adding the following line into your AndroidManifest.xml in the application section: android:largeHeap="true"
  • Try to use images as small as possible for your gallery. Remeber: each image is stored uncompressed into your applications heap
  • Recycle images that are not visible at the moment using Bitmap.recycle() to free new memory.

Solution 3:

Try this java code it works. I used it recently in my android app

Pop up

PopupWindow popup;

privatevoidinitiatePopupWindow() {
    // TODO Auto-generated method stubtry {
        LayoutInflaterinflater= (LayoutInflater) getBaseContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Viewlayout= inflater.inflate(R.layout.change_profileimg, null);
        popup = newPopupWindow(layout, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT);
        Buttonimagefromgallery= (Button) layout
                .findViewById(R.id.imagefromgallery);
        RelativeLayoutrelPopup= (RelativeLayout) layout.findViewById(R.id.relativeLayoutMainPopup);
        Buttoncaptureimage= (Button) layout
                .findViewById(R.id.captureimage);
        imagefromgallery.setTypeface(Typeface.createFromAsset(getAssets(),
            "fonts/OpenSans-Regular.ttf"));
        captureimage.setTypeface(Typeface.createFromAsset(getAssets(),
                "fonts/OpenSans-Regular.ttf"));
        imagefromgallery.setOnClickListener(newOnClickListener() {

            @OverridepublicvoidonClick(View v) {
                // TODO Auto-generated method stub
                galleryPick();
                popup.dismiss();
            }
        });

        captureimage.setOnClickListener(newOnClickListener() {
            @OverridepublicvoidonClick(View v) {
                // TODO Auto-generated method stub// takePhoto();
                callCameraApp();
                popup.dismiss();
            }
        });
        relPopup.setOnClickListener(newOnClickListener() {

            @OverridepublicvoidonClick(View v) {

                popup.dismiss();

            }
        });
        popup.setOutsideTouchable(true);
        popup.setTouchInterceptor(newOnTouchListener() {

            @OverridepublicbooleanonTouch(View arg0, MotionEvent event) {
                // TODO Auto-generated method stubif (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    popup.dismiss();
                    returntrue;
                }
                returnfalse;
            }
        });
        popup.showAtLocation(layout, Gravity.BOTTOM, 0, 0);

    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

}

Gallery pick

privatevoidgalleryPick() {
    try {
        Intent gintent = new Intent();
        gintent.setType("image/*");
        gintent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(
                Intent.createChooser(gintent, "Select Picture"), PICK_IMAGE);
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(),
                Toast.LENGTH_LONG).show();
        Log.e(e.getClass().getName(), e.getMessage(), e);
    }
}

Call camera app

privatevoidcallCameraApp() {
    Intenti=newIntent();
    i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    StringfileName="new-photo-name.jpg";
    ContentValuesvalues=newContentValues();
    values.put(MediaColumns.TITLE, fileName);
    values.put(ImageColumns.DESCRIPTION, "Image captured by camera");
    // imageUri is the current activity attribute, define and save it for// later usage (also in onSaveInstanceState)
    imageUri = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    try {
        fileName = getPath(imageUri);
    } catch (Exception e) {
        // TODO: handle exception
    }
    i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(i, PICK_Camera_IMAGE1);
}

then to get the bitmap

public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

 privatestatic File getOutputMediaFile(int type) {

        // External sdcard locationFilemediaStorageDir=newFile(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "XYZ_");

        // Create the storage directory if it does not existif (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("errorrr", "Oops! Failed create "
                        + "XYZ_" + " directory");
                returnnull;

            }
        }

        // Create a media file nameStringtimeStamp=newSimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(newDate());
        File mediaFile;

            mediaFile = newFile(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".png");




        return mediaFile;

 }

String filePath;

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {

    UriselectedImageUri=null;
    UriselectedImagepicUri=null;

    filePath = null;
    switch (requestCode) {

    case PICK_Camera_IMAGE:
        if (resultCode == RESULT_OK) {
            // use imageUri here to access the image
            selectedImageUri = imageUri;
            /*
             * Bitmap mPic = (Bitmap) data.getExtras().get("data");
             * selectedImageUri =
             * Uri.parse(MediaStore.Images.Media.insertImage
             * (getContentResolver(), mPic,
             * getResources().getString(R.string.app_name),
             * Long.toString(System.currentTimeMillis())));
             */
        } elseif (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "Picture was not taken",
                    Toast.LENGTH_SHORT).show();
        }
        break;

    case PICK_Camera_IMAGE1:
        if (resultCode == RESULT_OK) {
            // use imageUri here to access the image
            selectedImagepicUri = imageUri;
            /*
             * Bitmap mPic = (Bitmap) data.getExtras().get("data");
             * selectedImageUri =
             * Uri.parse(MediaStore.Images.Media.insertImage
             * (getContentResolver(), mPic,
             * getResources().getString(R.string.app_name),
             * Long.toString(System.currentTimeMillis())));
             */
        } elseif (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "Picture was not taken",
                    Toast.LENGTH_SHORT).show();
        }
        break;

    case PICK_IMAGE:
        if (resultCode == Activity.RESULT_OK) {
            selectedImagepicUri = data.getData();
        }

    }

    if (selectedImagepicUri != null) {
        try {
            // OI FILE ManagerStringfilemanagerstring= selectedImagepicUri.getPath();

            // MEDIA GALLERYStringselectedImagePath= getPath(selectedImagepicUri);

            if (selectedImagePath != null) {
                filePath = selectedImagePath;
            } elseif (filemanagerstring != null) {
                filePath = filemanagerstring;
            } else {
                Toast.makeText(getApplicationContext(), "Unknown path",
                        Toast.LENGTH_LONG).show();
                Log.e("Bitmap", "Unknown path");
            }

            if (filePath != null) {
                decodeFile1(filePath);
            } else {
                bitmap = null;
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Internal error",
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }
    }

    if (selectedImageUri != null) {
        try {
            // OI FILE ManagerStringfilemanagerstring= selectedImageUri.getPath();

            // MEDIA GALLERYStringselectedImagePath= getPath(selectedImageUri);

            if (selectedImagePath != null) {
                filePath = selectedImagePath;
            } elseif (filemanagerstring != null) {
                filePath = filemanagerstring;
            } else {
                Toast.makeText(getApplicationContext(), "Unknown path",
                        Toast.LENGTH_LONG).show();
                Log.e("Bitmap", "Unknown path");
            }

            if (filePath != null) {
                decodeFile(filePath);
            } else {
                bitmap = null;
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Internal error",
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }
    }

}

public String getPath(Uri uri) {
    String[] projection = { MediaColumns.DATA };
    Cursorcursor= managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIAintcolumn_index= cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } elsereturnnull;
}

publicvoiddecodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Optionso=newBitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale tofinalintREQUIRED_SIZE=512;

    // Find the correct scale value. It should be the power of 2.intwidth_tmp= o.outWidth, height_tmp = o.outHeight;
    intscale=1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Optionso2=newBitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    /**Bitmap.createScaledBitmap(bitmap, 200, 200, false);*/if (bitmap == null) {
        Toast.makeText(getApplicationContext(), "Please select image",
                Toast.LENGTH_SHORT).show();
    } else {
        ivr.setImageBitmap(bitmap);
        ivrIn.setImageBitmap(bitmap);
        // new ImageGalleryTask().execute();
    }
}

publicvoiddecodeFile1(String filePath) {
    // Decode image size
    BitmapFactory.Optionso=newBitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale tofinalintREQUIRED_SIZE=512;

    // Find the correct scale value. It should be the power of 2.intwidth_tmp= o.outWidth, height_tmp = o.outHeight;
    intscale=1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Optionso2=newBitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    /**Bitmap.createScaledBitmap(bitmap, 200, 200, false);*/if (bitmap == null) {
        Toast.makeText(getApplicationContext(), "Please select image",
                Toast.LENGTH_SHORT).show();
    } else {
        ivr.setImageBitmap(bitmap);
        ivrIn.setImageBitmap(bitmap);
        // new ImageGalleryTask().execute();
    }

}

Async task to upload image

privateclassUploadFileToServerextendsAsyncTask<Void, Integer, String> {
        @OverrideprotectedvoidonPreExecute() {
            // setting progress bar to zero         
            progressDialog = newProgressDialog(Profile.this);
            //progressDialog.setTitle("Fetching data");
            progressDialog.setMessage("Uploading profile pic, Please Wait....");
            progressDialog.show();
            progressDialog.setCancelable(false);
            super.onPreExecute();
        }

        @OverrideprotectedvoidonProgressUpdate(Integer... progress) {
            // Making progress bar visibleSystem.out.println("progress update "+progress[0]);
           // progressBar.setVisibility(View.VISIBLE); // updating progress bar value// progressBar.setProgress(progress[0]); // updating percentage value// txtPercentage.setText(String.valueOf(progress[0]) + "%");
        }

        @OverrideprotectedStringdoInBackground(Void... params) {
            returnuploadFile();
        }

        @SuppressWarnings("deprecation")
        privateStringuploadFile() {
            String responseString = null;
            int count;
            try
            {       
                FileInputStream fileInputStream = newFileInputStream(newFile(filePath));                  
                URL url = newURL("url"); 
                System.out.println("url "+url);

                connection = (HttpURLConnection) url.openConnection();   

                // Allow Inputs &amp; Outputs.
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);

                // Set HTTP method to POST.
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                outputStream = newDataOutputStream( connection.getOutputStream() );
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + filePath + "\"" + lineEnd);
                Log.e("chhuuuh", filePath + System.currentTimeMillis());
                outputStream.writeBytes(lineEnd);

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0)
                {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }       
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


                responseString = connection.getResponseMessage();

                fileInputStream.close();
                outputStream.flush();                
                outputStream.close();
                InputStream is = null;
                try {
                  is = connection.getInputStream();
                  int ch;
                  StringBuffer sb = newStringBuffer();
                  while ((ch = is.read()) != -1) {
                    sb.append((char) ch);
                  }
                  return sb.toString();
                } catch (IOException e) {
                  throw e;
                } finally {
                  if (is != null) {
                    is.close();
                  }
                }
            }
            catch (Exception ex)
            {

            }
            return responseString;

        }

        @OverrideprotectedvoidonPostExecute(String result) {

            String result1 = result;
          Log.e("respons form server", "response from server: " + result); 
          if(progressDialog.isShowing())
          {
              progressDialog.dismiss();
          }
          try {
                JSONObject json = newJSONObject(result);
                int response = json.getInt("status_code");

                if(response == 1)
                {
                    if (result1.contains("null")) {
                        Toast.makeText(getApplicationContext(), "You didn't change the image,  please choose an image from gallery or click from the camera.", 2000).show();
                    } else {
                    JSONObject arr = json.getJSONObject("details");
                    String erer = arr.getString("error");
                    String message = arr.getString("message");
                    Toast.makeText(getApplicationContext(), message, 1000).show();
                    }
                }
                else
                {
                    showAlert("Error Uploading Image, Please try again!!!");    
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            super.onPostExecute(result);
        }

    }

get the correct path

publicstaticStringgetPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProviderif (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProviderif (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final Stringtype = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    returnEnvironment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProviderelseif (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                returngetDataColumn(context, contentUri, null, null);
            }
            // MediaProviderelseif (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final Stringtype = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } elseif ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } elseif ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = newString[] {
                        split[1]
                };

                returngetDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)elseif ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote addressif (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            returngetDataColumn(context, uri, null, null);
        }
        // Fileelseif ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        returnnull;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */publicstaticStringgetDataColumn(Context context, Uri uri, String selection,
            String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        returnnull;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */publicstaticbooleanisExternalStorageDocument(Uri uri) {
        return"com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */publicstaticbooleanisDownloadsDocument(Uri uri) {
        return"com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */publicstaticbooleanisMediaDocument(Uri uri) {
        return"com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */publicstaticbooleanisGooglePhotosUri(Uri uri) {
        return"com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

Permissions for 6.0 and above versions

     @Override
        publicvoidonRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            Log.d("", "Permission callback called-------");
            switch (requestCode) {
                case REQUEST_ID_MULTIPLE_PERMISSIONS: {

                    Map<String, Integer> perms = new HashMap<String, Integer>();
                    // Initialize the map with both permissions
                    perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
                    perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                    perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                    perms.put(Manifest.permission.CALL_PHONE, PackageManager.PERMISSION_GRANTED);
                    // Fill with actual results from userif (grantResults.length > 0) {
                        for (int i = 0; i < permissions.length; i++)
                            perms.put(permissions[i], grantResults[i]);
                        // Check for both permissionsif (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                                && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                                && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                                && perms.get(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                            Log.d("", " permission granted");
                            // process the normal flow//else any one or both the permissions are not granted
                        } else {
                                Log.d("", "Some permissions are not granted ask again ");
                                //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission// shouldShowRequestPermissionRationale will return true//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) 
                                        || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
                                        || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
                                    showDialogOK("This app have camera functionality so Camera and Write External Storage Permission required for this app",
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                publicvoidonClick(DialogInterface dialog, int which) {
                                                    switch (which) {
                                                        case DialogInterface.BUTTON_POSITIVE:
                                                            checkAndRequestPermissions();
                                                            break;
                                                        case DialogInterface.BUTTON_NEGATIVE:
                                                            // proceed with logic by disabling the related features or quit the app.
                                                             Toast.makeText(getApplicationContext(), "Please go to settings and enable permissions.", 2000).show();
                                                            break;
                                                    }
                                                }
                                            });
                                }
                                //permission is denied (and never ask again is  checked)//shouldShowRequestPermissionRationale will return falseelse {
                                    Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
                                            .show();
        //                            //proceed with logic by disabling the related features or quit the app.
                                }
                        }
                    }
                }
            }

        }

        privatevoidshowDialogOK(String message, DialogInterface.OnClickListener okListener) {
            new AlertDialog.Builder(this)
                    .setMessage(message)
                    .setPositiveButton("OK", okListener)
                    .setNegativeButton("Cancel", okListener)
                    .create()
                    .show();
        }

        private  boolean checkAndRequestPermissions() {
            int permissionCamera = ContextCompat.checkSelfPermission(this,  Manifest.permission.CAMERA);
            int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            int permissionWriteExternal = ContextCompat.checkSelfPermission(this,  Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int permissionCallPhone = ContextCompat.checkSelfPermission(this,  Manifest.permission.CALL_PHONE);

            List<String> listPermissionsNeeded = new ArrayList<String>();
            if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.CAMERA);
            }
            if (locationPermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (permissionCallPhone != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
                returnfalse;
            }
            returntrue;
        }

I know this code is too long to read but this is exactly what you want

Post a Comment for "App Is Crashing When We Upload The Image From Gallery?"