简体   繁体   中英

After calling startActivityForResult() subsequent code still runs

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)

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"))

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
                                       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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