Reputation: 187
I want to know how can I do to save and show an image in the image view.
My app has 2 buttons and depending on which button was pressed the image view gets an image. What I want to do is to save that image and when I open the app again the chosen image is still there.
The only way I know to save something is shared preferences but in this case it doesn't work.
Someone can help me? Thanks
This is my code:
public class MainActivity extends AppCompatActivity {
ImageView imagen;
Button boton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagen = (ImageView) findViewById(R.id.imagen);
boton = (Button) findViewById(R.id.boton);
SharedPreferences preferences= getSharedPreferences("Preferencias", MODE_PRIVATE);
String imagen= preferences.getString("Imagen", null);
}
public void boton1(View view){
imagen.setImageResource(R.drawable.imagen1);
SharedPreferences preferences = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Imagen", imagen.getResources().toString());
editor.apply();
}
public void boton2(View view){
imagen.setImageResource(R.drawable.imagen2);
SharedPreferences preferences = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Imagen", imagen.getResources().toString());
editor.apply();
}
}
Upvotes: 0
Views: 115
Reputation: 955
You could save the URI in String format of the drawable in your shared preference. Like this (rename yourImageName by the drawable name) :
Uri imageUri = Uri.parse("android.resource://"+context.getPackageName()+"/drawable/yourImageName");
String uri_toString = imageUri.toString();
SharedPreferences preferences = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("imageUri", uri_toString);
editor.apply();
In your MainActivity, in onResume
set the image source of your ImageView like this :
SharedPreferences preferences = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
String imageUri = preferences.getString("imageUri",null);
if (imageUri != null) {
Uri uri = Uri.parse(imageUri);
yourImageView.setImageURI(uri);
}
Upvotes: 0