2016-04-13 6 views
1

イメージをギャラリーから選択するか、キャプチャするかの2つのオプションがあります。ユーザーは、ギャラリーから画像を選択すると、ユーザはそれをキャプチャした後の画像を設定しようとすると、キャプチャ後にイメージを設定しようとすると「原因:java.lang.NullPointerException:uri」が発生する

することは、それはアプリがクラッシュし、次のエラーを与えて、クランクのImageViewのを返して: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

は、ここで私はチューを起動しています方法は次のとおりです。

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; 
      } 
     } 
    }; 

は、ここで私は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(); 
     } 

    } 

私はここで間違っているものを教えてください。

申し訳ありませんが、質問のフォーマットが間違っています。私はまだ初心者です。

+0

それはあなたを助ける、これを参照してください。.. http://stackoverflow.com/questions/33938665/android-integrating-gallery -functional-with-camera-capture/33939277#33939277 –

+0

この回答は私の仕事でした:http://stackoverflow.com/a/5991757/6144372 –

答えて

0

このようにしてください。 これは確かに...テスト済み役立ちます....

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

なぜあなたはsdkのバージョンをチェックしていますか? –

+0

@ Rao .. APIのさまざまなレベルを区別するために使用しています –

+0

@hammad nasir ..あなたの問題は解決しましたか? –

1

パスを取得する方法が異なることは、特定のAndroidのバージョンです。私は、この目的のために次のUtilクラスを使用します。今、デバイスのOSバージョンコール適切な方法に基づいて

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); 
    } 
} 

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

これを実装して、文字列でエラーが発生しました。wholeID = DocumentsContract.getDocumentId(uri);エラーmsg - ヌルオブジェクトリファレンスで仮想メソッド 'java.util.List android.net.Uri.getPathSegments()'を呼び出そうとしています – Ahsan

関連する問題