如何在android中使用共享首选项存储图像?

时间:2011-12-05 12:11:20

标签: android

我想使用sharedpreference在android中保存图像。我有两个活动类,当我点击第一个活动的按钮时它将调用第二个活动,第二个活动在列表视图中显示我的首选名称,并且还将android壁纸重置为我设置为首选壁纸的图像。第一项活动。

对于第二项活动,代码是:

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));
    }

第一个活动调用第二个活动但不调用if(wallPaper != null){}

为什么不起作用?

3 个答案:

答案 0 :(得分:72)

您所要做的就是将图片转换为Base64字符串表示形式:

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();

然后,在检索时,将其转换回位图:

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);
}

但是,我必须告诉您,Base64支持最近才包含在API8中。要以较低的API版本为目标,您需要先添加它。幸运的是,this guy已经有了所需的教程。

另外,我创建了quick and dirty example我在github上发布。

答案 1 :(得分:28)

不建议将图像存储在共享首选项中并且您应该将该图像存储到sdcard.And然后将图像路径(从sdcard)存储到共享首选项中,如下所示 -

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

然后使用此路径从sdcard获取图像

答案 2 :(得分:2)

嘿朋友我得到了上述问题的解决方案。在这里发布我的完整源代码,以便其他人可以使用此解决方案。

这是我对这个问题的第二个解决方案,我已经发布了一个答案,这是同一问题的不同答案。 How to save Image in shared preference in Android | Shared preference issue in Android with Image

按照以下步骤操作: -

  1. 将位图和字符串声明为静态

    public static final String PRODUCT_PHOTO = "photo";
    public static Bitmap product_image;
    
  2. 在onCreate()中编写一些代码。

    //---------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. 在方法
    2. 中写下代码

      setDefaults();

      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);
        }
        

        现在,如果您想在其他活动中访问此图片文件,请按照以下步骤操作。

      2. 将String声明为静态

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

        在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);
        
      3. 用于decodeBase64();

             public static Bitmap decodeBase64(String input)
             {
             byte[] decodedByte = Base64.decode(input, 0);
             return BitmapFactory.decodeByteArray(decodedByte, 0,   decodedByte.length);
             }