ZNDS智能电视网 推荐当贝市场

TV应用下载 / 资源分享区

软件下载 | 游戏 | 讨论 | 电视计算器

综合交流 / 评测 / 活动区

交流区 | 测硬件 | 网站活动 | Z币中心

新手入门 / 进阶 / 社区互助

新手 | 你问我答 | 免费刷机救砖 | ROM固件

查看: 15088|回复: 0
上一主题 下一主题
[案例]

sharepreference方式保存带图片的例子

[复制链接]
跳转到指定楼层
楼主
发表于 2013-8-28 16:29 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
2
通常,Sharepreference方式保存数据只能保存简单类型的数据,对于像图片等,就需要对这些数据进行编码,然后将编码后的数据按字符串的形式保存到xml中去。
本项目需要用到一个第三方的jar包(common-codec-1.4.jar)
在选择图片的时候我们采用画廊视图来选择一张图片。
核心代码如下:
package net.blogjava.mobile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
public class Main extends Activity implements OnClickListener
{
       private SharedPreferences mySharedPreferences;
       private EditText etProductID;
       private EditText etProductName;
       private EditText etProductPrice;
       private ImageView imageView;
       private List<Integer> imageResIdList = new ArrayList<Integer>();
       public class ImageAdapter extends BaseAdapter
       {
              int mGalleryItemBackground;
              private Context mContext;
              public ImageAdapter(Context context)
              {
                     mContext = context;
                     TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery1);
                     mGalleryItemBackground = typedArray.getResourceId(
                                   R.styleable.Gallery1_android_galleryItemBackground, 0);
              }
              public int getCount()
              {
                     return imageResIdList.size();
              }
              public Object getItem(int position)
              {
                     return position;
              }
              public long getItemId(int position)
              {
                     return position;
              }
              public View getView(int position, View convertView, ViewGroup parent)
              {
                     ImageView imageView = new ImageView(mContext);
                     imageView.setImageResource(imageResIdList.get(position));
                     imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                     imageView.setLayoutParams(new Gallery.LayoutParams(136, 88));
                     imageView.setBackgroundResource(mGalleryItemBackground);
                     return imageView;
              }
       }
       @Override
       public void onClick(View view)
       {
              try
              {
                     switch (view.getId())
                     {
                            case R.id.btnSave:
                                   Product product = new Product();
                                   product.setId(etProductID.getText().toString());
                                   product.setName(etProductName.getText().toString());
                                   product.setPrice(Float.parseFloat(etProductPrice.getText()
                                                 .toString()));
                                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                   ObjectOutputStream oos = new ObjectOutputStream(baos);
                                   oos.writeObject(product);
                                   mySharedPreferences = getSharedPreferences("base64",
                                                 Activity.MODE_PRIVATE);
                                   String productBase64 = new String(Base64.encodeBase64(baos
                                                 .toByteArray()));
                                   SharedPreferences.Editor editor = mySharedPreferences
                                                 .edit();
                                   editor.putString("product", productBase64);
               
                                   baos = new ByteArrayOutputStream();
                                   ((BitmapDrawable) imageView.getDrawable()).getBitmap()
                                                 .compress(CompressFormat.JPEG, 50, baos);
                                   
                                   String imageBase64 = new String(Base64.encodeBase64(baos
                                                 .toByteArray()));
                                   editor.putString("productImage", imageBase64);
                                   editor.commit();
                                   oos.close();
                                   new AlertDialog.Builder(this).setTitle("保存成功.")
                                                 .setPositiveButton("确定", null).show();
                                   break;
                            case R.id.btnSelectImage:
                                   View myView = getLayoutInflater().inflate(R.layout.gallery,
                                                 null);
                                   final Gallery gallery = (Gallery) myView
                                                 .findViewById(R.id.gallery);
                                   ImageAdapter imageAdapter = new ImageAdapter(this);
                                   gallery.setAdapter(imageAdapter);
                                   new AlertDialog.Builder(this)
                                                 .setTitle("选择产品图像")
                                                 .setView(myView)
                                                 .setPositiveButton(
                                                               "确定",
                                                               new android.content.DialogInterface.OnClickListener()
                                                               {
                                                                      @Override
                                                                      public void onClick(
                                                                                    DialogInterface dialog,
                                                                                    int which)
                                                                      {
                                                                             imageView
                                                                                           .setImageResource(imageResIdList
                                                                                                         .get(gallery
                                                                                                                       .getSelectedItemPosition()));
                                                                      }
                                                               }).setNegativeButton("取消", null).show();
                                   break;
                     }
              }
              catch (Exception e)
              {
                     setTitle("error:" + e.getMessage());
              }
       }
       @Override
       public void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              Button btnSave = (Button) findViewById(R.id.btnSave);
              Button btnSelectImage = (Button) findViewById(R.id.btnSelectImage);
              etProductID = (EditText) findViewById(R.id.etProductID);
              etProductName = (EditText) findViewById(R.id.etProductName);
              etProductPrice = (EditText) findViewById(R.id.etProductPrice);
              imageView = (ImageView) findViewById(R.id.imageview);
              btnSave.setOnClickListener(this);
              btnSelectImage.setOnClickListener(this);
              byte[] base64Bytes;
              ByteArrayInputStream bais;
              try
              {
                     mySharedPreferences = getSharedPreferences("base64",
                                   Activity.MODE_PRIVATE);
                     String productBase64 = mySharedPreferences.getString("product", "");
                     base64Bytes = Base64.decodeBase64(productBase64.getBytes());
                     bais = new ByteArrayInputStream(base64Bytes);
                     ObjectInputStream ois = new ObjectInputStream(bais);
                     Product product = (Product) ois.readObject();                  
                     etProductID.setText(product.getId());
                     etProductName.setText(product.getName());
                     etProductPrice.setText(String.valueOf(product.getPrice()));
                     ois.close();
              }
              catch (Exception e)
              {
                     
              }
              try
              {
                     String imageBase64 = mySharedPreferences.getString("productImage",
                                   "");
                     base64Bytes = Base64.decodeBase64(imageBase64.getBytes());
                     bais = new ByteArrayInputStream(base64Bytes);
                     imageView.setImageDrawable(Drawable.createFromStream(bais,
                                   "product_image"));
                     Field[] fields = R.drawable.class.getDeclaredFields();
                     for (Field field : fields)
                     {
                            if (!"icon".equals(field.getName()))
                                   imageResIdList.add(field.getInt(R.drawable.class));
                     }
                     
              }
              catch (Exception e)
              {
                     // TODO: handle exception
              }
       }
}
</div

上一篇:Android腾讯微薄客户端开发八:微博查看(转播,对话,点评)
下一篇:android开发总结.docx
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|新帖|标签|软件|Sitemap|ZNDS智能电视网 ( 苏ICP备2023012627号 )

网络信息服务信用承诺书 | 增值电信业务经营许可证:苏B2-20221768 丨 苏公网安备 32011402011373号

GMT+8, 2025-4-27 21:09 , Processed in 0.071286 second(s), 13 queries , Redis On.

Powered by Discuz!

监督举报:report#znds.com (请将#替换为@)

© 2007-2025 ZNDS.Com

快速回复 返回顶部 返回列表