I am trying to make an app where I can let a user select a picture to display on their profile. I am able to browse and set their selected image on imageview. But the image is lost once the the activity is destroyed. I tried to implement onSaveInstanceState
but still it's the same. I'm wondering if I am using it correctly. I hope you can help a newbie like me. Thanks in advance. Here's the code that I'm using:
PS: I am using External library to Set image
Library I am using:-
implementation 'com.github.dhaval2404:imagepicker:2.1'
Main Activity code:-
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.github.dhaval2404.imagepicker.ImagePicker;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.jetbrains.annotations.NotNull;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
FloatingActionButton fab;
Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView1);
fab = findViewById(R.id.floatingActionButton1);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ImagePicker.with(MainActivity.this)
// .crop() //Crop image(Optional), Check Customization for more option
// .compress(1024) //Final image size will be less than 1 MB(Optional)
// .maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional)
.start();
}
});
if(savedInstanceState != null){
uri = savedInstanceState.getParcelable("savedImage");
imageView.setImageURI(uri);
}else {
Toast.makeText(MainActivity.this,"No Image",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uri = data.getData();
imageView.setImageURI(uri);
}
@Override
protected void onSaveInstanceState(@NonNull @NotNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("savedImage",uri);
}
}