2015-12-29 46 views
16

我正在使用相機意圖在我的應用程序中捕獲圖像。使用相機時,我的應用在Android 5.0.2上崩潰的問題。我正在使用片段中的意圖。下面是我裏面的片段代碼:Android:使用相機意圖時,應用程序在onActivityResult上崩潰

法拍照

private void takePhoto() { 
    mHighQualityImageUri = Util.generateTimeStampPhotoFileUri(getActivity()); 
    Log.d(UploadPicturesFragment.class.getSimpleName(), 
      "URI: " + mHighQualityImageUri.toString()); 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mHighQualityImageUri); 
    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); 
} 

onActivityResult在我的片段

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode != Activity.RESULT_OK) { 
     return; 
    } 

    if (requestCode == REQUEST_IMAGE_CAPTURE) { 
    Log.d(UploadPicturesFragment.class.getSimpleName(), 
       "IMAGE URI NOT NULL: " + (mHighQualityImageUri == null)); 
     try { 
      Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), 
        mHighQualityImageUri); 
      DroomUtil.beginCrop(mHighQualityImageUri, getActivity(), this, true, bitmap.getWidth(), 
        bitmap.getHeight()); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

日誌跟蹤

12-29 10:28:03.491: E/AndroidRuntime(9780): java.lang.RuntimeException:  Unable to resume activity {in.droom/in.droom.activity.MainActivity}:  java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:2, request=1, result=-1, data=null} to activity {in.droom/in.droom.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3224) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3257) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2479) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread.access$800(ActivityThread.java:144) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.os.Handler.dispatchMessage(Handler.java:102) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.os.Looper.loop(Looper.java:155) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread.main(ActivityThread.java:5702) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at java.lang.reflect.Method.invoke(Native Method) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at java.lang.reflect.Method.invoke(Method.java:372) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824) 
12-29 10:28:03.491: E/AndroidRuntime(9780): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:2, request=1, result=-1, data=null} to activity {in.droom/in.droom.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread.deliverResults(ActivityThread.java:3881) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3197) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  ... 11 more 
12-29 10:28:03.491: E/AndroidRuntime(9780): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.content.ContentResolver.openInputStream(ContentResolver.java:651) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:1019) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at in.droom.fragments.UploadPicturesFragment.onActivityResult(UploadPicturesFragment.java:395) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.Activity.dispatchActivityResult(Activity.java:6164) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  at android.app.ActivityThread.deliverResults(ActivityThread.java:3877) 
12-29 10:28:03.491: E/AndroidRuntime(9780):  ... 12 more 

行號395是:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), 
        mHighQualityImageUri); 
+0

http://stackoverflow.com/a/11351580/4067759 – therealprashant

+0

我認爲你是什麼地方 –

+0

完成你的活動@VivekMishra但問題僅限Android 5.0.2。 – Nitish

回答

6

按照以下的步驟,以從相機拍攝圖像並顯示到ImageView

1)啓動相機意圖

Uri fileUri; 
String photoPath = ""; 

private void startingCameraIntent() 
    { 
     String fileName = System.currentTimeMillis()+".jpg"; 
     ContentValues values = new ContentValues(); 
     values.put(MediaStore.Images.Media.TITLE, fileName); 
     fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 

     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 
     startActivityForResult(intent, YOUR_REQ_CODE); 
    } 

2)回調onActivityResult功能

@Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     if (resultCode == Activity.RESULT_OK) 
     { 
      try 
      { 
       photoPath = getPath(fileUri); 

       System.out.println("Image Path : " + photoPath); 

       Bitmap b = decodeUri(fileUri); 
       your_image_view.setImageBitmap(b); 
      } 
      catch(Exception e) 
      { 
       e.printStackTrace(); 
      } 
     } 
    } 

3)decodeUri功能

private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException 
    { 
     BitmapFactory.Options o = new BitmapFactory.Options(); 

     o.inJustDecodeBounds = true; 

     BitmapFactory.decodeStream(getContentResolver() 
              .openInputStream(selectedImage), null, o); 

     final int REQUIRED_SIZE = 72; 

     int width_tmp = o.outWidth, height_tmp = o.outHeight; 

     int scale = 1; 

     while (true) 
     { 
      if (width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE) 
      { 
       break; 
      } 
      width_tmp /= 2; 

      height_tmp /= 2; 

      scale *= 2; 
     } 

     BitmapFactory.Options o2 = new BitmapFactory.Options(); 

     o2.inSampleSize = scale; 

     Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver() 
                  .openInputStream(selectedImage), null, o2); 

     return bitmap; 
    } 

4)圖像的的getPath

@SuppressWarnings("deprecation") 
    private String getPath(Uri selectedImaeUri) 
    { 
     String[] projection = { MediaStore.Images.Media.DATA }; 

     Cursor cursor = managedQuery(selectedImaeUri, projection, null, null, 
            null); 

     if (cursor != null) 
     { 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 

      return cursor.getString(columnIndex); 
     } 

     return selectedImaeUri.getPath(); 
    } 

最後清單中定義的權限

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

注意:如果您使用棉花糖(Android 6.0),您必須在使用相機應用程序之前設置權限檢查。你可以閱讀關於安卓Requesting Permissions at Run Time

2

在Android上,我看到不同的設備exibit不同的行爲選擇圖像與相機和畫廊。我發現更好的方法是:

  1. 在您的應用程序中創建一個內容提供程序。
  2. 從您的內容提供商處獲取Uri並將其傳遞給相機意圖。
  3. 相機會將拍攝的圖像寫入您的Uri。
  4. 使用context.getContentResolver()。openInputStream()讀取它。

此方法使您的代碼獨立於返回的Uri,因爲您擁有Uri。此外,這也支持圖庫挑選,只需稍作修改即可。

我發現你也有相機的設備方向問題。這(不幸)需要在你的應用程序中進行處理,在後期處理步驟中獲取圖像。我在下面也列出了它的代碼。大多數情況下,方向問題發生在三星設備上,相機僅以橫向模式拍攝圖像。

圖像創建烏里:

string imageId = "IMG" + System.currentTimeMillis(); 
Uri attachmentUri = Uri.parse("content://"+ AttachmentContentProvider.AUTHORITY + "/images/" + imageId); 
// Store this as a member in your activity/fragment as mAttachmentUri 

注意:它的重要的是你使用使用的onSaveInstanceState()共享偏好或活動捆綁否則,當你的應用程序就會被殺死開放的我們可能會丟失堅持mAttachmentUri

入門相機意圖:

public static Intent getImageCaptureIntent(Context context, Uri outputFileUri) 
{ 
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
    return cameraIntent; 
} 

讀取圖像:

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if (resultCode != Activity.RESULT_OK) { 
     return; 
    } 

    if (requestCode == REQUEST_IMAGE_CAPTURE) 
    { 

     try { 
      Bitmap bitmap = decodeSampledBitmapFromResource(getActivity(), mAttachmentUri, Config.RGB_565); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

    public static Bitmap decodeSampledBitmapFromResource(Context context, Uri uri, Config config) 
    { 
     Bitmap bmp = null; 
     InputStream is = null; 
     if (uri != null) 
     { 
      try 
      { 
       is = context.getContentResolver().openInputStream(uri); 

       boolean resize = true; 
       // First decode with inJustDecodeBounds=true to check dimensions 
       BitmapFactory.Options options = new BitmapFactory.Options(); 
       options.inJustDecodeBounds = true; 
       BitmapFactory.decodeStream(is, null, options); 
       mLogger.d("Image Original Width:" + options.outWidth + " Height:" + options.outHeight); 
       // close and open the stream again 
       is.close(); 

       is = context.getContentResolver().openInputStream(uri); 
       int reqWidth = options.outWidth; 
       int reqHeight = options.outHeight; 

       // Decode bitmap with inSampleSize set 
       options.inJustDecodeBounds = false; 
       options.inPreferredConfig = config;  
       bmp = BitmapFactory.decodeStream(is, null, options); 

       if(bmp != null) 
       { 
        bmp = correctImageRotation(context, bmp, uri); 
       } 
       else 
       { 
        mLogger.e("BitmapFactory.decodeStream returned null bitmap , skip correctImageRotation"); 
       } 
      } 
      catch (FileNotFoundException fnfex) 
      { 
       mLogger.e("FileNotFoundException : while decoding inline image bitmap: " + fnfex.getMessage()); 
      } 
      catch (IOException ioex) 
      { 
       mLogger.e("IOException : while decoding inline image bitmap: " + ioex.getMessage()); 
      } 
      catch (OutOfMemoryError e) 
      { 
       mLogger.e("OutOfMemoryError : in decodeSampledBitmapFromResource BitmapFactory.decodeStream . Skip loading Resource"); 
      } 
      finally 
      { 
       try 
       { 
        if (is != null) 
        { 
         is.close(); 
        } 
       } 
       catch (IOException ioex2) 
       { 
        mLogger.e("IOException2 : while decoding inline image bitmap: " + ioex2.getMessage()); 
       } 
      } 
     } 
     return bmp; 
    } 

    // Seemed necessary on a lot of Samsung devices 
    public static Bitmap correctImageRotation(Context context, Bitmap bitmap , Uri inputUri) throws FileNotFoundException 
    { 
     int orientation = ExifInterface.ORIENTATION_UNDEFINED; 

     try 
     { 
      String appfilesDir = context.getApplicationContext().getFilesDir().getAbsolutePath(); 
      String attachmentDirPath = appfilesDir + ('/') + "images"); 
      String fileName = ContentUris.parseId(uri) + ".jpg"; 
      String absolutePath = attachmentDirPath + ('/') + fileName; 
      ExifInterface exif = new ExifInterface(path); 
      orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); 
     } 
     catch (IOException e) 
     { 
     } 

     return rotateBitmap(bitmap, orientation); 
    } 

    /** 
    * rotate bitmap code reference: 
    * http://stackoverflow.com/questions/20478765/how-to-get-the-correct-orientation-of-the-image-selected-from-the-default-image 
    */ 
    private static Bitmap rotateBitmap(Bitmap bitmap, int orientation) 
    { 
     Matrix matrix = new Matrix(); 
     switch (orientation) 
     { 
     case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: 
      matrix.setScale(-1, 1); 
      break; 
     case ExifInterface.ORIENTATION_ROTATE_180: 
      matrix.setRotate(180); 
      break; 
     case ExifInterface.ORIENTATION_FLIP_VERTICAL: 
      matrix.setRotate(180); 
      matrix.postScale(-1, 1); 
      break; 
     case ExifInterface.ORIENTATION_TRANSPOSE: 
      matrix.setRotate(90); 
      matrix.postScale(-1, 1); 
      break; 
     case ExifInterface.ORIENTATION_ROTATE_90: 
      matrix.setRotate(90); 
      break; 
     case ExifInterface.ORIENTATION_TRANSVERSE: 
      matrix.setRotate(-90); 
      matrix.postScale(-1, 1); 
      break; 
     case ExifInterface.ORIENTATION_ROTATE_270: 
      matrix.setRotate(-90); 
      break; 
     case ExifInterface.ORIENTATION_NORMAL: 
     case ExifInterface.ORIENTATION_UNDEFINED: 
     default: 
      return bitmap; 
     } 
     try 
     { 
      Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 
      bitmap.recycle(); 
      return bmRotated; 
     } 
     catch (OutOfMemoryError e) 
     { 
      mLogger.e("OutOfMemoryError occured while rotating the image"); 
      return bitmap; 
     } 
    } 

內容提供商:

對於內容提供商實現,您可以使用android的FileProvider或者工具nt像下面這樣的內容提供者。此內容提供商將在您的應用容器中打開相機應用寫入的文件。

public class AttachmentContentProvider extends ContentProvider 
{ 
    public static final String AUTHORITY = "com.yourcompany.yourapp.AttachmentContentProvider"; 
    public static final int ENTITY_ATTACHMENT = 1; 
    public static final int ENTITY_ATTACHMENT_ID = 2; 

    private static final UriMatcher sUriMatcher; 
    static 
    { 
     sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); 
     sUriMatcher.addURI(AUTHORITY, "images", ENTITY_ATTACHMENT); 
     sUriMatcher.addURI(AUTHORITY, "images"+"/#", ENTITY_ATTACHMENT_ID); 
    } 

    @Override 
    public boolean onCreate() 
    { 
     return true; 
    } 

    @Override 
    public int delete(Uri uri, String where, String[] whereArgs) 
    { 
     return 0; 
    } 

    @Override 
    public String getType(Uri uri) 
    { 
     int match = sUriMatcher.match(uri); 
     switch (match) 
     { 
     case ENTITY_ATTACHMENT: 
     case ENTITY_ATTACHMENT_ID: 
      return "image/jpeg"; 

     default: 
      return null; 
     } 
    } 

    @Override 
    public Uri insert(Uri uri, ContentValues initialValues) 
    { 
     return null; 
    } 

    @Override 
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) 
    { 
     return null; 
    } 

    @Override 
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) 
    { 
     return 0; 
    } 

    public static File getAttachmentFile(String fileName) 
    { 
     String appfilesDir = context.getApplicationContext().getFilesDir().getAbsolutePath(); 
     String attachmentDirPath = appfilesDir + ('/') + "images"); 
     File newFile = new File(AttachmentHelper.getAttachmentsDir() + File.separator + fileName); 
     newFile.getParentFile().mkdirs(); 
     return newFile; 
    } 


    @Override 
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException 
    { 
     long id = -1; 
     try 
     { 
      id = ContentUris.parseId(uri); 
     } 
     catch (NumberFormatException e) 
     { 
      m_logger.e("Invalid id for Uri : " + uri); 
     } 

     String filename = id + ".jpg"; // id will be IMG+current time millis 
     File imageFile = getAttachmentFile(id); 
     return (ParcelFileDescriptor.open(file, parseMode(mode))); 
    } 
} 

總之,此代碼應在測試的大多數設備上工作,並在必要時從相機接收到的圖像做校正。

0

以下是我經常在我的項目中做的,請看看。希望能幫助到你!

片段類:

btnCapturePicture.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) {  
     captureImage();  
    } 
}); 

btnSelectPicture.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) {  
     selectImage(); 
    } 
}); 

... 

private void captureImage() { 
    mFileUri = Uri.fromFile(Utils.getOutputMediaFile(MEDIA_TYPE_IMAGE)); 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri); 
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); 
} 

private void selectImage() {  
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType(MIME_IMAGE_ALL); 
    startActivityForResult(intent, SELECT_PHOTO_CODE); 
} 

... 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch (requestCode) { 
     case SELECT_PHOTO_CODE: 
      if (resultCode == Activity.RESULT_OK) { 
       mFileUri = imageReturnedIntent.getData(); 
       if (mFileUri != null) { 
        mFilePath = Utils.getRealPathFromUri(mContext, mFileUri); 
        mFilePath = mFilePath.replace("file://", ""); 
        // do something such as display ImageView... 
       } 
      } 
      break; 
     case CAMERA_CAPTURE_IMAGE_REQUEST_CODE: 
      if (resultCode == Activity.RESULT_OK) { 
       if (mFileUri != null) { 
        mFilePath = mFileUri.toString(); 
        mFilePath = mFilePath.replace("file://", ""); 
        // do something such as display ImageView... 
       } 
      } 
      break; 
    } 

    // refresh phone's folder content 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
     Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);  
     mediaScanIntent.setData(mFileUri); 
     getActivity().sendBroadcast(mediaScanIntent); 
    } else { 
     getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 
    } 
} 

的Utils類:

//returning image, video 
public static File getOutputMediaFile(int type) { 

    // External sdcard location 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "DCIM/Camera"); 

    // Create the storage directory if it does not exist 
    if (!mediaStorageDir.exists()) { 
     if (!mediaStorageDir.mkdirs()) { 
      return null; 
     } 
    } 

    // Create a media file name 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); 
    File mediaFile; 
    if (type == MEDIA_TYPE_IMAGE) { 
     mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); 
    } else if (type == MEDIA_TYPE_VIDEO) { 
     mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); 
    } else { 
     return null; 
    } 

    return mediaFile; 
} 

//For select picture 
public static String getRealPathFromUri(Context context, Uri contentUri) { 
    Cursor cursor = null; 
    try { 
     String[] proj = {MediaStore.Images.Media.DATA}; 
     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); 
    } finally { 
     if (cursor != null) { 
      cursor.close(); 
     } 
    } 
} 
11
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference 

這意味着mHighQualityImageUrinull,在所有的升ikelihood。如果您未能使用onSaveInstanceState()來保留該Uri,則會發生這種情況。當您的應用程序處於後臺並且相機應用程序處於前臺時,您的進程完全可能會被終止。

+0

@ CommonsWare它不爲空,但仍然給出相同的錯誤 – Juni

+0

所以我怎麼能做到這一點在我的設備,就像做同樣的情況下測試? –

+0

@SagarNayak:如果我正確解釋你的問題,而相機應用程序在前臺,請從Android Studio終止你的應用程序的進程。然後,用相機拍照。當控制權返回到您的應用程序時,Android需要爲您分配一個新的流程。 – CommonsWare

2
please check your path from mHighQualityImageUri because output path is not found, below code is modify please check it, it work and remember camera result is give in Main Activity class because You used Fragment so declare on activity Result in Main Activity (Fragment Activity) class. 
//on Fragment Class 
private void takePhoto() { 
      /* mHighQualityImageUri = Util.generateTimeStampPhotoFileUri(getActivity()); 
       Log.d(UploadPicturesFragment.class.getSimpleName(), 
         "URI: " + mHighQualityImageUri.toString());*/ 
       imageUri =Uri.fromFile(new File("/sdcard/")); 
       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
       context.startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); 
      } 

    //on Main Activity Class 
     @Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
      if (requestCode == 1) { 
      /* Log.d(UploadPicturesFragment.class.getSimpleName(), 
         "IMAGE URI NOT NULL: " + (mHighQualityImageUri == null));*/ 
       try { 

        /*if(imageUri==null){ 
         Log.i("Bitmap", "Image URI Null"); 
        }else { 
         Log.i("Bitmap","Image URI is not Null"); 
        }*/ 
        Uri imageUri = Uri.fromFile(new File("/sdcard/")); 
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri); 
    //      mHighQualityImageUri); 
        if(bitmap !=null) 
        { 
         Log.i("Bitmap", "Bitmap not Null"); 
        }else { 
         Log.i("Bitmap","Bitmap is Null"); 
        } 
        // DroomUtil.beginCrop(mHighQualityImageUri, getActivity(), this, true, bitmap.getWidth(), 
        // bitmap.getHeight()); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
      super.onActivityResult(requestCode, resultCode, data); 
     } 
4

首先檢查是否dataonActivityResultnull通過增加一個額外的代碼,這將防止您的應用程序被撞壞,這樣

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
if (resultCode != Activity.RESULT_OK && data !=null) { 
    return; 
} 
} 

再考慮這個教訓這就解釋了how to capture photos using an existing camera application.

有關於的完整參考使用uses-feature tagGetting a thumbnailSaving full size photo,更多的人可能是對你非常有幫助的完成你的任務......

+0

data!= null 是嗎?爲什麼它不是「data == null」? – Xiaofeng

2

按日誌

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference 

它明確指出,您呼叫getScheme()上空對象。因此在處理之前,您需要檢查空意圖數據。

此外,從Android M開始,您需要向用戶請求相機權限。由於缺乏相機許可,應用程序將崩潰。

要知道如何使用新的許可結構的工作,你看它:http://developer.android.com/training/permissions/index.html