0

So basically I want the app to: after pressing a button opens the gallery, the user selects one image and after that saves the uri in a variable. That's all it needs to do but what I found is that after calling startActivityForResult() subsequent code still runs in the background creating a NullPointerException error, since the variable I wanted has not yet been retrieved from the intent.

public class MainActivity extends AppCompatActivity {

    final static int PICK_IMAGE_REQUEST = 1;

    private String imageUriStr;

    SharedPreferences prefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        prefs = this.getSharedPreferences("MyPreferences",MODE_PRIVATE);

        ImageView addImgButton = (ImageView) findViewById(R.id.add_img_button);

        addImgButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

                if (prefs.contains(imageUriStr)) {
                    imageUriStr = prefs.getString("imageUriStr", ""); //Get the data from prefs
                }

                Log.d("Value",imageUriStr); //verify if it is correct

                prefs.edit().clear();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            imageUriStr = data.getData().toString(); //convert to string to use it with SharedPreferences

            prefs.edit().putString("imageUriStr",imageUriStr).apply();

        }

    }
}

One solution would be to do everything inside the onActivityresult, but I also want to later user another intent to crop the image based on that uri, but I think an Intent inside an onActivityresult will be too messy or is it acceptable? I guess I'm missing something.

Keeping with my code will generate this

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.prototypeapp, PID: 17826
java.lang.NullPointerException: println needs a message
    at android.util.Log.println_native(Native Method)
    at android.util.Log.d(Log.java:154)
    at com.example.android.prototypeapp.MainActivity$1$override.onClick(MainActivity.java:41)
    at com.example.android.prototypeapp.MainActivity$1$override.access$dispatch(MainActivity.java)
    at com.example.android.prototypeapp.MainActivity$1.onClick(MainActivity.java:0)
    at android.view.View.performClick(View.java:5264)
    at android.view.View$PerformClick.run(View.java:21297)
    at android.os.Handler.handleCallback(Handler.java:743)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:150)
    at android.app.ActivityThread.main(ActivityThread.java:5546)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
User
  • 4,023
  • 4
  • 37
  • 63
J. Doe
  • 1
  • 1
  • Your `imageUriStr` in `Log.d("Value",imageUriStr);` is null – SripadRaj Jul 13 '16 at 05:41
  • if (prefs.contains(imageUriStr)) change to if (prefs.contains("imageUriStr")) and add Log.d inside if – comeback4you Jul 13 '16 at 05:43
  • Thanks that worked! So it works like this?: After you call startActivityForResult subsequent code will still run in background and after it returns, it is going to pick up from the line after startActivityForResult? – J. Doe Jul 13 '16 at 06:47
  • Calling `startActivity(...)` or `startActivityForResult(...)` doesn't immediately start an activity. Think of it as asking the Android framework to maybe, pretty please, start the activity sometime in the future. – Kevin Krumwiede Jul 13 '16 at 07:09
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Janki Gadhiya Jul 13 '16 at 07:11
  • @Kevin So let's say I have a huge code ahead of that startActivity(...), everything should be inside an If to not screw up or is there another more elegant way to do it? – J. Doe Jul 13 '16 at 07:28
  • You mean like this? `if(condition) { startActivity(...) } else { /* do something else */ }` I've written something like that a few times, even though it makes me feel like there's something wrong with how I'm doing things. – Kevin Krumwiede Jul 13 '16 at 07:35
  • More like: `startActivityForResult(...) if(condition) {/* Large chunk of code */}`. Like my issue here, in which the variable must be first set in another activity in order for the code to work as intended. – J. Doe Jul 13 '16 at 07:40
  • @jankigadhiya I don't consider it similar to that question, my confusion revolved around how the startActivityForResult(...) behaves more than the null pointer exception, I didn't understand the flow of the code enough. – J. Doe Jul 13 '16 at 07:45

2 Answers2

0

Your private String imageUriStr; is null.Since it is null you are getting null pointer exception. Assign it with the empty string like : private String imageUriStr = "";.

AND

Check in shared preference like : if(prefs.contains("imageUriStr"))

Akshay Bhat 'AB'
  • 2,690
  • 3
  • 20
  • 32
0

Your Code is crashing on this line:

 Log.d("Value",imageUriStr); 

Reason: imageUriStr value is null and a valid message is required to print the log

You can either use Log as :

 Log.d("Value","Image URI Value: "+imageUriStr); 

or you can put your Log inside if block like:

      if (prefs.contains(imageUriStr)) {
                        imageUriStr = prefs.getString("imageUriStr", "");//Get the data from prefs
          Log.d("Value",imageUriStr); //verify if it is correct
                                       }
Nargis
  • 4,687
  • 1
  • 28
  • 45