【问题标题】:Camera null pointer in android fragment?android片段中的相机空指针?
【发布时间】:2015-11-05 09:33:50
【问题描述】:

有很多关于同一主题的问题,但没有一个问题能提供我需要的答案。我已经尝试了很多解决方案,但到目前为止没有一个对我有用。 我在尝试使用 Android 的相机在我的fragment 中拍照并从图库中拍照时卡住了,因为我总是得到NullPointerException。这是我的代码,当用户单击按钮以从图库中捕获或拍照时:

capture_dp.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, TAKE_PHOTO_CODE);
                }
        });
add_galery_dp[counter2].setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                   Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                   startActivityForResult(i,
                            PICK_FROM_GALLERY);
                    }
        });

这是我的方法:

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

         super.onActivityResult(requestCode, resultCode, data);
                    if (requestCode == TAKE_PHOTO_CODE && data != null) {
                            selectedImagePath = getImagePath();
                            nama_foto[counter]=new File(path1,"foto"+GetTime.getCurrentDate("yyyyMMddhhmmss")+".jpg");
                            FileOutputStream fos = null;
                            if(! nama_foto[counter].exists())   
                            {
                                try {
                                    Bitmap bitmap= rotateBitmap(selectedImagePath);
        //                           nama_foto[counter].createNewFile();
        //                          copyFile(new File(selectedImagePath),  nama_foto[counter]); //untuk copy file dari selected image path ke nama_foto
                                    fos = new FileOutputStream( nama_foto[counter]);
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
                                    fos.flush();
                                    fos.close();
        //                            MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "Screen", "screen");
                                } catch (FileNotFoundException e) {
                                    throw new RuntimeException(e);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                                foto_dp[counter].setImageBitmap(rotateBitmap(selectedImagePath));
                    }

                    else if (requestCode == PICK_FROM_GALLERY&& data != null) {
                                Uri selectedImageUri = data.getData();
                                selectedImagePath = getPath(selectedImageUri);
                                System.out.println("Image Path : " + selectedImagePath);
        //                      File photo = new File(selectedImagePath);
                                nama_foto[counter]=new File(path1,"foto"+GetTime.getCurrentDate("yyyyMMddhhmmss")+".jpg");  
                                FileOutputStream fos = null;
                                if(! nama_foto[counter].exists())   
                                {
                                    try {
        //                               nama_foto[counter].createNewFile();
        ////                                 foto_dp[counter].setImageBitmap(resizeimage(selectedImagePath));
        //                               rotateBitmap(selectedImagePath);
        //                                copyFile(new File(selectedImagePath),  nama_foto[counter]);
                                        Bitmap bitmap= rotateBitmap(selectedImagePath);
                                        fos = new FileOutputStream( nama_foto[counter]);
                                       bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
                                       fos.flush();
                                       fos.close();
        //                               MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "Screen", "screen");
                                    } catch (FileNotFoundException e) {
                                        throw new RuntimeException(e);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                             foto_dp[counter].setImageBitmap(rotateBitmap(selectedImagePath));
                    }
                    else{

                    }
                }

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

              //Method camera
                public Uri setImageUri() {
                    FileOutputStream out = null;
                      // Store image in dcim
                      nama_foto[counter] = new File(Environment.getExternalStorageDirectory() +"/android/data/ESPAJ/spaj_foto/"+GetTime.getCurrentDate("yyyyMMddhhmmss")+".jpg");
                      Uri imgUri = Uri.fromFile(nama_foto[counter]);
                      this.imgPath = nama_foto[counter].getAbsolutePath();
                      return imgUri;
                  }
                 public String getImagePath() {
    //               Log.i("tes", imgPath);
                        return imgPath;
                    }
    //resize             
            public Bitmap resizeimage(String path) throws FileNotFoundException {
                FileInputStream ostream = null;
                try {
                    ostream = new FileInputStream(path);
                     BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 1; //subsampling

                        int compress = 20;
                        BitmapFactory.decodeStream(ostream, null, options).compress(CompressFormat.JPEG, compress, new FileOutputStream(path));


    //                return BitmapFactory.decodeFile(path, o2);
                } catch (FileNotFoundException e) {

                    e.printStackTrace();
                }

                    return null;

                }   
    //decode memory image
            public static Bitmap decodeFile(String path) {
                try {
                    // Decode image size
                    BitmapFactory.Options o = new BitmapFactory.Options();
                    o.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(path, o);
                    // The new size we want to scale to
                    final int REQUIRED_SIZE = 250;

                    // Find the correct scale value. It should be the power of 2.
                    int scale = 4;
                    while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                        scale *= 2;

                    // Decode with inSampleSize
                    BitmapFactory.Options o2 = new BitmapFactory.Options();
                    o2.inSampleSize = scale;
                    return BitmapFactory.decodeFile(path, o2);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                return null;

            }   

这是我的logcat在拍照时的历史:

    11-05 13:53:15.778: E/AndroidRuntime(11152): FATAL EXCEPTION: main
11-05 13:53:15.778: E/AndroidRuntime(11152): java.lang.RuntimeException: Unable to resume activity {id.co.ajsmsig.espaj/id.co.ajsmsig.espaj.Menu_SPPAJ}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:9, request=0, result=-1, data=null} to activity {id.co.ajsmsig.espaj/id.co.ajsmsig.espaj.Menu_SPPAJ}: java.lang.NullPointerException
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2613)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2641)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2127)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3550)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.access$700(ActivityThread.java:140)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.os.Looper.loop(Looper.java:137)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.main(ActivityThread.java:4895)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at java.lang.reflect.Method.invokeNative(Native Method)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at java.lang.reflect.Method.invoke(Method.java:511)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at dalvik.system.NativeStart.main(Native Method)
11-05 13:53:15.778: E/AndroidRuntime(11152): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:9, request=0, result=-1, data=null} to activity {id.co.ajsmsig.espaj/id.co.ajsmsig.espaj.Menu_SPPAJ}: java.lang.NullPointerException
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3179)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2600)
11-05 13:53:15.778: E/AndroidRuntime(11152):    ... 13 more
11-05 13:53:15.778: E/AndroidRuntime(11152): Caused by: java.lang.NullPointerException
11-05 13:53:15.778: E/AndroidRuntime(11152):    at id.co.ajsmsig.espaj.DokumenPendukung.rotateBitmap(DokumenPendukung.java:794)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at id.co.ajsmsig.espaj.DokumenPendukung.onActivityResult(DokumenPendukung.java:734)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.Activity.dispatchActivityResult(Activity.java:5351)
11-05 13:53:15.778: E/AndroidRuntime(11152):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3175)
11-05 13:53:15.778: E/AndroidRuntime(11152):    ... 14 more

这是我从相机拍照时 logcat 的历史:

11-05 15:48:13.578: E/AndroidRuntime(14633): java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:1, request=1, result=-1, data=Intent { dat=content://media/external/images/media/22 (has extras) }} to activity {id.co.ajsmsig.espaj/id.co.ajsmsig.espaj.Menu_SPPAJ}: java.lang.NullPointerException

我希望有人可以帮助我解决我的问题。非常感谢。

【问题讨论】:

标签: android android-fragments android-camera


【解决方案1】:

如果您将额外参数MediaStore.EXTRA_OUTPUT 与相机意图一起传递,则相机活动会将捕获的图像写入该路径,并且不会在onActivityResult 方法中返回位图。

如果您检查您所传递的路径,那么您将知道实际上相机已将捕获的文件写入该路径。

如需了解更多信息,您可以关注thisthisthis

【讨论】:

  • 我已经尝试过你的答案,但意图数据仍然为空 T.T
  • 没有强制关闭但捕获的图像仍然没有显示在 ImageView 中,当我调试它时,意图数据仍然为空 T.T
  • 您提供了正确的图像路径,当意图开始时检查是否有图像捕获照片时。
  • 拍照时如何判断是否有图片?
  • setImageUri() 如何返回路径..你必须检查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 2022-07-06
相关资源
最近更新 更多