重新进入应用程序后,将最后选择的图像加载到ImageView中

时间:2016-08-29 16:07:38

标签: java android bitmap imageview sharedpreferences

我的目标是在关闭(销毁)应用程序然后重新打开应用程序后,让最后选择的图像保留在ImageView中。

我尝试加载以在SharedPreference中保存位图“(How can I store images using sharedpreference in android?),然后我尝试将路径存储到SharedPreferences中的位图并使用Picasso加载它:(Picasso Load image from filesystem),并尝试加载它将值传递给BitmapFactory.decodeFile(completePath);,如我在代码中所见。

无论如何输出总是一样的;我收到了NullPointerException。

我是初学Android和编程的新手,请原谅我凌乱的代码。

private String picturePass;
private ImageView imageView;
private Bitmap picBitmap;
private boolean yes;
private static final int SELECT_PICTURE = 1;
private static final String SAVE_NAME = "MyFile";)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity_page);
    if (savedInstanceState != null) {
        savedInstanceState.get("path");
    }
//loading
    SharedPreferences preferences = getSharedPreferences(SAVE_NAME, MODE_PRIVATE);
    //boolean to check if Image was chosen
    yes = preferences.getBoolean("yes", true);
    if(yes){
         picturePass = preferences.getString("path", null);
         String completePath = picturePass;
        //just to check the content
        Toast.makeText(this, completePath, Toast.LENGTH_LONG).show();
        File file = new File(completePath);
        if (file.exists()) {
            picBitmap = BitmapFactory.decodeFile(completePath);
            imageView.setImageBitmap(picBitmap);
        }
    }
}
 //Choosing a picture from gallery
public void onClickImage(View view) {
    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, SELECT_PICTURE);
    yes = true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data) {
        //The only way I maneged to get the file path, that's a messy part
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        //Setting picture in imageView
        if (selectedImage != null) {

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
                imageView = (ImageView) findViewById(R.id.imageView);
                imageView.setImageBitmap(bitmap);
                picBitmap = bitmap;
                //Tried to use  Environment.getExternalStorageDirectory().getAbsolutePath() + imageName with no success
                //File f = new File(picturePath);
                //String imageName = f.getName();
                //picturePass = imageName;
                picturePass = picturePath;
                //Saving image path
                //just too check the content
                Toast.makeText(this, picturePath, Toast.LENGTH_LONG).show();
                SharedPreferences.Editor editor = getSharedPreferences(SAVE_NAME, MODE_PRIVATE).edit();
                editor.putString("path", picturePass);
                editor.putBoolean("yes", true);
                editor.commit();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("path", picturePass);
}
}

08-29 19:05:46.263 16436-16436/com.amberapply.vitaliy.iloveyou E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amberapply.vitaliy.iloveyou, PID: 16436
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amberapply.vitaliy.iloveyou/com.amberapply.vitaliy.iloveyou.MainActivityPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
     at android.app.ActivityThread.access$800(ActivityThread.java:151)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:135)
     at android.app.ActivityThread.main(ActivityThread.java:5258)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:735)
  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
     at com.amberapply.vitaliy.iloveyou.MainActivityPage.onCreate(MainActivityPage.java:60)
     at android.app.Activity.performCreate(Activity.java:6005)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
     at android.app.ActivityThread.access$800(ActivityThread.java:151) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5258) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:735)                                                                     

2 个答案:

答案 0 :(得分:1)

首先在SharedPreferences中存储图像将是一个非常糟糕的主意。 您应该在SharedPreferences中存储图像路径,并且您可以在第一次加载应用时读取该图像,阅读SharedPreferences,获取图像路径,从存储中读取它并在ImageView中显示它。

所以,这就是程序,这很简单,不需要编写这么多代码。 现在你真的不需要在SharedPreferences中存储boolean,你可以使用contains()方法: https://developer.android.com/reference/android/content/SharedPreferences.html

关于NullPointerException,我想说请检查logcat,如果可能的话,然后在NullPointerException时复制你的logcat并在这里发布你的logcat,这会更有帮助。 以下是如何获取logcat:https://developer.android.com/studio/debug/am-logcat.html

答案 1 :(得分:1)

@Nikunj Sardhara解决方案应该有效

如果你修复了npe:在onCreate中,在`imageView.setImageBitmap(picBitmap)之前没有imageView = (ImageView) findViewById(R.id.imageView);;