保存和恢复ArrayList

时间:2016-08-06 17:56:38

标签: java android

我的应用程序需要两张图片,并将每个URI放入一个ArrayList中,以便我可以从一个ImageView迭代它。我知道URI正常工作并被添加到ArrayList中。我假设活动在屏幕上为摄像机旋转(以前提到的图像),所以我使用onSaveInstanceState来保存我想要使用的数据。在我这样做之前,应用程序会在拍完照片后立即崩溃。现在它没有,但是当我尝试从列表中设置图像时,我得到一个NullPointer。我做错了吗?

logcat的:

FATAL EXCEPTION: main
                                                                              Process: my.package.myapplication, PID: 15047
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
                                                                                  at my.package.myapplication.Person1Screen$5.onClick(Person1Screen.java:130)
                                                                                  at android.view.View.performClick(View.java:5209)
                                                                                  at android.view.View$PerformClick.run(View.java:21174)
                                                                                  at android.os.Handler.handleCallback(Handler.java:739)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:148)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5477)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我在以下底部的setImageURI中获取NullPointer:

happy = (Button) findViewById(R.id.happy_btn);
happy.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){
            id = HAPPY;
            if(toggled){
                //picture mode
                dispatchTakePictureIntent();
            }
            else if(!toggled) {
                //display mode
                //happyIndex = 0;
                mainView.setImageURI(happyList.get(0)); // LINE 130
            }
        }
    });

我的onCreate中有以下内容:

happyList = new ArrayList<>();
    if (savedInstanceState != null) {
        happyList = savedInstanceState.getParcelableArrayList(HAPPY_LIST);
    }

我的onSaveInstance:

@Override
public void onSaveInstanceState (Bundle savedInstanceState) {
    savedInstanceState.putParcelableArrayList(HAPPY_LIST, happyList);
    super.onSaveInstanceState(savedInstanceState);
}

我的TakePictureIntent(从相机或图库中拍摄两张照片)和onActivityResult(获取URI并添加到列表中):

private void dispatchTakePictureIntent() {
    pictureCounter = -1;
    for(int i = 0; i < 2; i++) {
        pictureCounter++;
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
                outputFileUri = Uri.fromFile(photoFile);
            } catch (IOException ex) {
                Log.w("error","IOException");
            }catch (NullPointerException nullEx) {
                Log.w("error","NullPointerException");
            }
            // Camera.
            final List<Intent> cameraIntents = new ArrayList<Intent>();
            final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            final PackageManager packageManager = getPackageManager();
            final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
            for (ResolveInfo res : listCam) {
                final String packageName = res.activityInfo.packageName;
                final Intent intent = new Intent(captureIntent);
                intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                intent.setPackage(packageName);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                cameraIntents.add(intent);
            }
            // Filesystem.
            final Intent galleryIntent = new Intent();
            galleryIntent.setType("image/*");
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
            // Chooser of filesystem options.
            final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
            // Add the camera options.
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
            startActivityForResult(chooserIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_TAKE_PHOTO) {
                final boolean isCamera;
                if (data == null) {
                    isCamera = true;
                } else {
                    final String action = data.getAction();
                    if (action == null) {
                        isCamera = false;
                    } else {
                        isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    }
                }
                Uri selectedImageUri;
                if (isCamera) {
                    selectedImageUri = outputFileUri;
                } else {
                    selectedImageUri = data == null ? null : data.getData();
                }
               // mainView.setImageURI(selectedImageUri);
              //  Log.d("Before adding", selectedImageUri.toString());
                happyList.add(selectedImageUri);
               // Log.d("Array:", happyList.toString());
            }
        }
    }

2 个答案:

答案 0 :(得分:3)

首先,建议您在班级中存储密钥常量。主要原因是,保持一致并避免拼写错误。

SKUId

现在,无论何时保存和恢复

,都要使用它

其次,我认为这些应该被翻转,因为你想要输入你保存的东西,然后做超级电话所做的任何事情

Uri对象也是Parcelable,因此请使用适当的方法

public static final String HAPPY_LIST = "happyList";

最后,您可以在onRestoreInstanceState或onCreate中使用已恢复的包,但我认为您不需要同时执行这两项操作。

答案 1 :(得分:1)

在onSavedInstanceState()方法中,将键设置为“happylist”,将if条件中的“array”更改为“happylist”

if (savedInstanceState != null) {
    happyList = (ArrayList<Uri>)savedInstanceState.getSerializable("happylist");
}