2016-04-13 1 views
1

J'ai deux options pour définir une image, soit en la choisissant dans la galerie ou en la capturant.Obtenir "Provoqué par: java.lang.NullPointerException: uri" lorsque vous essayez de définir l'image après l'avoir capturé

Lorsque l'utilisateur choisit l'image de la galerie, il renvoie un ImageView Clank et lorsque l'utilisateur essaie de mettre l'image après l'avoir capturée, les accidents d'applications donnant erreur suivant: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.abc.xyz/com.abc.xyz.Activity}: java.lang.NullPointerException: uri

Voilà comment je lance le chooser:

protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int position) { 
      switch (position) { 
       case 0: // Take picture 
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST); 
        break; 
       case 1: // Choose picture 
        Intent choosePhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
        choosePhotoIntent.setType("image/*"); 
        startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST); 
        break; 
      } 
     } 
    }; 

Voilà comment je mettre l'image à l'ImageView:

@Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if (resultCode == Activity.RESULT_OK) { 

      if (requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST) { 
       if (data == null) { 
        // display an error 
        return; 
       } 
       Uri selectedImage = data.getData(); 
       String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

       // error on the line below 
       Cursor cursor = this.getContentResolver().query(selectedImage, 
         filePathColumn, null, null, null); 
       // 
       cursor.moveToFirst(); 

       int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
       String picturePath = cursor.getString(columnIndex); 
       cursor.close(); 

       Picasso.with(this) 
         .load(picturePath) 
         .into(hPic); 
       hPicTag.setVisibility(View.INVISIBLE); 
      } 

     } else if (resultCode == Activity.RESULT_CANCELED) { 
      Toast.makeText(getBaseContext(), "Something went wrong!", Toast.LENGTH_LONG).show(); 
     } 

    } 

S'il vous plaît laissez-moi savoir ce qui ne va pas ici.

Désolé pour le mauvais formatage de la question. Je suis toujours un débutant ici.

+0

Voir cette Il vous aidera .. http://stackoverflow.com/questions/33938665/android-integrating-gallery -functionality-with-camera-capture/33939277 # 33939277 –

+0

cette réponse a fait l'affaire pour moi: http://stackoverflow.com/a/5991757/6144372 –

Répondre

0

Essayez comme ceci. Cela va sûrement vous aider ... .... Testé

final String[] items = new String[]{"Camera", "Gallery"};    
      new AlertDialog.Builder(getActivity()).setTitle("Select Picture") 
        .setAdapter(adapter, new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int item) { 
          if (items[item].equals("Camera")) { 

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
            startActivityForResult(intent, REQUEST_CAMERA); 


          } else if (items[item].equals("Gallery")) { 
           if (Build.VERSION.SDK_INT <= 19) { 
            Intent intent = new Intent(); 
            intent.setType("image/*"); 
            intent.setAction(Intent.ACTION_GET_CONTENT); 
            intent.addCategory(Intent.CATEGORY_OPENABLE); 
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE); 
           } else if (Build.VERSION.SDK_INT > 19) { 
            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE); 
           } 
          } 
         } 
        }).show(); 

     } 


     // get result after selecting image from Gallery 
     @Override 
     public void onActivityResult(int requestCode, int resultCode, Intent data) { 
      super.onActivityResult(requestCode, resultCode, data); 

      if (requestCode == PICK_IMAGE && resultCode == getActivity().RESULT_OK && null != data) { 
       Uri selectedImageUri = data.getData(); 
       String selectedImagePath = getRealPathFromURIForGallery(selectedImageUri); 
       decodeFile(selectedImagePath); 
      } else if (requestCode == REQUEST_CAMERA && resultCode == getActivity().RESULT_OK && null != data) { 
       Bitmap photo = (Bitmap) data.getExtras().get("data"); 
       profileImage.setImageBitmap(photo); 

       // CALL THIS METHOD TO GET THE URI FROM THE BITMAP 
       Uri tempUri = getImageUri(getActivity().getApplicationContext(), photo); 

       // CALL THIS METHOD TO GET THE ACTUAL PATH 
       File finalFile = new File(getRealPathFromURI(tempUri)); 
       decodeFile(finalFile.toString()); 
      } 
     } 

     public String getRealPathFromURIForGallery(Uri uri) { 
      if (uri == null) { 
       return null; 
      } 
      String[] projection = {MediaStore.Images.Media.DATA}; 
      Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null); 
      if (cursor != null) { 
       int column_index = cursor 
         .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
       cursor.moveToFirst(); 
       return cursor.getString(column_index); 
      } 
      return uri.getPath(); 
     } 

     public Uri getImageUri(Context inContext, Bitmap inImage) { 
      ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
      inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
      String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 
      return Uri.parse(path); 
     } 

     public String getRealPathFromURI(Uri uri) { 
      Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null); 
      cursor.moveToFirst(); 
      int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
      return cursor.getString(idx); 
     } 


     // decode image 
     public void decodeFile(String filePath) { 
      // Decode image size 
      BitmapFactory.Options o = new BitmapFactory.Options(); 
      o.inJustDecodeBounds = true; 
      BitmapFactory.decodeFile(filePath, o); 
      // The new size we want to scale to 
      final int REQUIRED_SIZE = 1024; 
      // Find the correct scale value. It should be the power of 2. 
      int width_tmp = o.outWidth, height_tmp = o.outHeight; 
      int scale = 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.Options o2 = new BitmapFactory.Options(); 
      o2.inSampleSize = scale; 
      bitmap = BitmapFactory.decodeFile(filePath, o2); 
      Security connection = new Security(context); 
      Boolean isInternetPresent = connection.isConnectingToInternet(); // true or false 
      if (isInternetPresent) { 
       // submit usr information to server 
       //first upload file 
       updateUserProfileImage(); 
       Log.i("IMAGEPATH", "" + imagePath); 
      } 
      profileImageView.setImageBitmap(bitmap); 
     } 
+0

pourquoi vous vérifiez la version sdk? –

+0

@ Rao..Je l'utilise pour différencier les différents niveaux de l'API –

+0

@hammad nasir..Est-ce que votre problème est résolu ou non? –

1

La façon d'obtenir un chemin est différent est certaines versions Android. J'utilise la classe Util suivante à cette fin.

public class RealPathUtil { 

    @SuppressLint("NewApi") 
    public static String getRealPathFromURI_API20(Context context, Uri uri){ 
     String filePath = ""; 
     String wholeID = DocumentsContract.getDocumentId(uri); 

     // Split at colon, use second item in the array 
     String id = wholeID.split(":")[1]; 

     String[] column = { MediaStore.Images.Media.DATA }; 

     // where id is equal to 
     String sel = MediaStore.Images.Media._ID + "=?"; 

     Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
       column, sel, new String[]{ id }, null); 

     int columnIndex = cursor.getColumnIndex(column[0]); 

     if (cursor.moveToFirst()) { 
      filePath = cursor.getString(columnIndex); 
     } 
     cursor.close(); 
     return filePath; 
    } 


    public static String getRealPathFromURI_API11to19(Context context, Uri contentUri) { 
     String[] proj = { MediaStore.Images.Media.DATA }; 
     String result = null; 

     if(Looper.myLooper() == null) { 
      Looper.prepare(); 
     } 
     CursorLoader cursorLoader = new CursorLoader(
       context, 
       contentUri, proj, null, null, null); 
     Cursor cursor = cursorLoader.loadInBackground(); 

     if(cursor != null){ 
      int column_index = 
        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      cursor.moveToFirst(); 
      result = cursor.getString(column_index); 
     } else { 
      result = contentUri.getPath(); 
     } 
     return result; 
    } 

    public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){ 
     String[] proj = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null); 
     int column_index 
       = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } 
} 

Maintenant, en fonction du périphérique appel de version OS méthodes appropriées:

if (Build.VERSION.SDK_INT < 11) { 
    RealPathUtil.getRealPathFromURI_BelowAPI11(...); 
} else if(Build.VERSION.SDK_INT >= 11 && <= 19) { 
    RealPathUtil.getRealPathFromURI_API11to19(...); 
} else if(Build.VERSION.SDK_INT > 19){ 
    RealPathUtil.getRealPathFromURI_API20(...); 
} 
+0

J'ai implémenté ceci et j'ai une erreur sur String wholeID = DocumentsContract.getDocumentId (uri); Erreur msg --- Tentative d'invocation de la méthode virtuelle 'java.util.List android.net.Uri.getPathSegments()' sur une référence d'objet null – Ahsan