Save and show an image in android studio -
i want know how can save , show image in image view.
my app have 2 buttons , depending on wich button pressed image view image. want save image , when open app again choosen image still there.
the way know save shared preferences in case doesnt work.
someone can my? thank
this 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(); }
}
you save uri in string format of drawable in shared preference. (rename yourimagename 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 mainactivity, in onresume
set image source of imageview :
sharedpreferences preferences = getsharedpreferences("preferencias", context.mode_private); string imageuri = preferences.getstring("imageuri",null); if (imageuri != null) { uri uri = uri.parse(imageuri); yourimageview.setimageuri(uri); }
Comments
Post a Comment