startActivityForResult() crashs if called more than once

101 views Asked by At

I have an Activity that calls startActivityForResult() so that user can pick an image from gallery. I'm getting the result in this same Activity and showing it in an ImageView. I also have a spinner populated dynamically onCreate(). It works great only at the first time that user picks an image, if he tries it again, my app crashs because it attempts to load the spinner again (in other words, it calls onCreate() but it doesn't if it's the first time!).

Relevant part of code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    spinner = (Spinner) findViewById(R.id.spinner);
    loadSpinnerData(); // populate spinner from DB
    loadImageFromGalleryListener(); // click listener
}

private void loadImageFromGalleryListener() { // Called when user clicks on a button
    loadFile.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(Intent.createChooser(intent, "Select picture"), LOAD_FILE_REQUEST);
        }
    });     
}

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

    if(resultCode != RESULT_CANCELED){
        if (requestCode == LOAD_FILE_REQUEST && resultCode == RESULT_OK) {
            // ... LOGIC TO WRITE FILE ON IMAGEVIEW
        } 
    }
} 

So.. how can I avoid calling onCreate() at the second time the user attempts to pick an image?

1

There are 1 answers

0
fweigl On

You cannot prevent onCreate() being called. Check if (savedInstanceState == null) in onCreate instead to prevent doing stuff twice.