¿Cómo puedo almacenar imágenes usando sharedpreference en android?

Quiero guardar imágenes en android usando sharedpreference. Tengo dos clases de actividad, cuando hago clic en el botón de la primera actividad que llamará a la segunda actividad y la segunda actividad muestra mi nombre preferido en una vista de lista y también restablece el fondo de pantalla de Android a la imagen que había establecido como fondo de pantalla preferido en el Primera actividad.

Para la segunda actividad el código es:

public class PreferencesActivityTest extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); String prefName = myPrefs.getString("PREF_USERNAME", "nothing"); String wallPaper = myPrefs.getString("PREFS_NAME", null); if(wallPaper != null) { try { Bitmap bm = BitmapFactory.decodeFile("/data/misc/wallpaper/"+wallPaper); Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ wallPaper); setWallpaper(bm); Toast.makeText(this, "Wall paper has been changed." + "You may go to the home screen to view the same", Toast.LENGTH_LONG).show(); } catch (FileNotFoundException fe){ Log.e(getClass().getSimpleName(),"File not found"); } catch (IOException ie) { Log.e(getClass().getSimpleName()," IO Exception"); } } ArrayList<String> results = new ArrayList<String>(); results.add("Your Preferred name is: " + prefName); this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results)); } 

La primera actividad llama a la segunda actividad, pero no llama if(wallPaper != null){}

¿Por qué no funciona?

Su no recomendado para almacenar la imagen en las preferencias de compartir Y debe almacenar esa imagen en sdcard.And luego almacenar la ruta de la imagen (de sdcard) en compartir preferencias como este–

  SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this); Editor edit=shre.edit(); edit.putString("imagepath","/sdcard/imh.jpeg"); edit.commit(); 

Y luego buscar la imagen de sdcard mediante el uso de esta ruta de acceso

Todo lo que tiene que hacer es, convertir su imagen a su Base64 cadena de representación:

 Bitmap realImage = BitmapFactory.decodeStream(stream); ByteArrayOutputStream baos = new ByteArrayOutputStream(); realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String encodedImage = Base64.encodeToString(b, Base64.DEFAULT); textEncode.setText(encodedImage); SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this); Editor edit=shre.edit(); edit.putString("image_data",encodedImage); edit.commit(); 

Y luego, al recuperar, convertirlo de nuevo en mapa de bits:

 SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this); String previouslyEncodedImage = shre.getString("image_data", ""); if( !previouslyEncodedImage.equalsIgnoreCase("") ){ byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length); imageConvertResult.setImageBitmap(bitmap); } 

Sin embargo, tengo que decirle que el soporte de Base64 sólo se incluye recientemente en API8. Para orientar en la versión de API más baja, primero debe agregarla. Afortunadamente, este tipo ya tiene el tutorial necesario.

Además, he creado un ejemplo rápido y sucio que publico en github.

Hola amigos tengo la solución del problema anterior. Aquí pongo mi código fuente completo para que otros puedan usar esta solución.

Esta es mi segunda solución en este problema, ya he puesto una respuesta esta es la respuesta diferente para la misma pregunta. Cómo guardar la imagen en preferencia compartida en Android | Problema de preferencia compartida en Android con Image .

Siga los siguientes pasos:

  1. Declare bitmap y String como static

     public static final String PRODUCT_PHOTO = "photo"; public static Bitmap product_image; 
  2. En onCreate () escribe algún código.

     //---------set the image to bitmap product_image= BitmapFactory.decodeResource(getResources(), .drawable.logo); //____________convert image to string String str_bitmap = BitMapToString(product_image); //__________create two method setDefaults() andgetDefaults() setDefaults(PRODUCT_PHOTO, str_bitmap, this) getDefaults(PRODUCT_PHOTO, this); 
    1. Escriba a continuación el código en los métodos

    Configurar valores predeterminados();

     public static void setDefaults(String str_key, String value, Context context) { SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor edit=shre.edit(); edit.putString(str_key, value); edit.apply(); } 

3.2.setDefaults ();

  public static String getDefaults(String key, Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); return preferences.getString(key, null); } 
  1. BitMapToString ();

     public static String BitMapToString(Bitmap bitmap) { ByteArrayOutputStream baos=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100, baos); byte[] arr = baos.toByteArray(); return Base64.encodeToString(arr, Base64.DEFAULT); } 

    Ahora, si desea acceder a este archivo de imagen en otra actividad, siga los pasos a continuación.

  2. Declara String como estática

     public static final String PRODUCT_PHOTO = "photo"; String str_bitmap; private Bitmap bitmap; private ImageView imageView_photo; 

    En onCreate ():

      //--------get image form previous activity,here ProductActivity is my previous activity. str_bitmap =ProductActivity.getDefaults(PRODUCT_PHOTO, this); //-------------- decode the string to the bitmap bitmap=decodeBase64(str_bitmap); //----------- finally set the this image to the Imageview. imageView_photo.setImageBitmap(bitmap); 

Para decodeBase64 ();

  public static Bitmap decodeBase64(String input) { byte[] decodedByte = Base64.decode(input, 0); return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); } 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.