简体   繁体   English

Android片段中的相机空指针?

[英]Camera null pointer in android fragment?

There's lots of questions on the same topic, however none of them provided me an answer that I needed. 关于同一主题有很多问题,但是没有一个问题为我提供了所需的答案。 I've tried a lot of solutions,and none of them is working for me so far. 我已经尝试了很多解决方案,但到目前为止,没有一个对我有用。 I stuck while trying to take picture in my fragment using Android's Camera and take picture from gallery, it because I always get NullPointerException . 在尝试使用Android的Camera在fragment拍照并从图库中拍照时,我卡住了,因为我总是收到NullPointerException this is my code while user click button for capture or taking picture from galery: 这是我的代码,当用户单击按钮以从图库中捕获或拍照时:

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

this my method : 这是我的方法:

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

            }   

this is my logcat's history while taking picture : 这是我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

and this is my logcat's history while taking picture from camera : 这是我从相机拍摄照片时的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

I hope somebody can help me to solve my problem. 我希望有人可以帮助我解决我的问题。 Thank you very much. 非常感谢你。

If you pass the extra parameter MediaStore.EXTRA_OUTPUT with the camera intent then camera activity will write the captured image to that path and it will not return the bitmap in the onActivityResult method. 如果通过摄像机意图传递了额外的参数MediaStore.EXTRA_OUTPUT ,则摄像机活动会将捕获的图像写入该路径,并且不会在onActivityResult方法中返回位图。

If you will check the path which you are passing then you will know that actually camera had write the captured file in that path. 如果您将检查通过的路径,那么您将知道照相机实际上已经在该路径中写入了捕获的文件。

For further information you can follow this , this and this 有关更多信息,您可以遵循

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM