0

My goal is to make last chosen image to stay in ImageView after an app was closed (destroyed) and then re-opened.

I tried to load to save bitmap in SharedPreference "(How can I store images using sharedpreference in android?), then I tried to store path to bitmap in SharedPreferences and load it using Picasso: (Picasso Load image from filesystem), and tried to load it by passing the value to BitmapFactory.decodeFile(completePath); as you can see in my code.

Anyway the output is always the same; I'm getting an NullPointerException.

I'm new to Android and programming in general so forgive my messy code.

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)                                                                     
Community
  • 1
  • 1
Mikhail
  • 133
  • 2
  • 9

2 Answers2

1

First of all storing an image in SharedPreferences would be a very bad idea. You should store path of image in SharedPreferences and you can read that image when your app loads for the first time, read the SharedPreferences, get your image path, read it from storage and show it in your ImageView.

So, that was the procedure and that is simple, It does't require writing this much code. Now you don't really need to store boolean in SharedPreferences, you can use contains() method : https://developer.android.com/reference/android/content/SharedPreferences.html

And about NullPointerException, i would say please check logcat and if possible then copy your logcat at the time of NullPointerException and post your logcat here, that would be more helpful. Here's how you can get logcat : https://developer.android.com/studio/debug/am-logcat.html

Nikunj Sardhara
  • 638
  • 1
  • 5
  • 20
  • Thank you for your replay! I will remember not to use SharedPreferences for soring images. And thank you for the logcat tutorial, that was handy. – Mikhail Aug 30 '16 at 00:59
1

@Nikunj Sardhara solution should work

if you fix the npe : in onCreate there is no imageView = (ImageView) findViewById(R.id.imageView); before `imageView.setImageBitmap(picBitmap);

k3b
  • 14,517
  • 7
  • 53
  • 85
  • Thank you, it worked! After you pointed it that seems so obvious, even for my level this is a silly mistake. I will be more cautious next time before asking a question. . – Mikhail Aug 30 '16 at 00:55