首頁 收藏 QQ群
 網(wǎng)站導(dǎo)航

ZNDS智能電視網(wǎng) 推薦當貝市場

TV應(yīng)用下載 / 資源分享區(qū)

軟件下載 | 游戲 | 討論 | 電視計算器

綜合交流 / 評測 / 活動區(qū)

交流區(qū) | 測硬件 | 網(wǎng)站活動 | Z幣中心

新手入門 / 進階 / 社區(qū)互助

新手 | 你問我答 | 免費刷機救磚 | ROM固件

查看: 13583|回復(fù): 0
上一主題 下一主題
[案例]

sharepreference方式保存帶圖片的例子

[復(fù)制鏈接]
跳轉(zhuǎn)到指定樓層
樓主
發(fā)表于 2013-8-28 16:29 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
2
通常,Sharepreference方式保存數(shù)據(jù)只能保存簡單類型的數(shù)據(jù),對于像圖片等,就需要對這些數(shù)據(jù)進行編碼,然后將編碼后的數(shù)據(jù)按字符串的形式保存到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("選擇產(chǎn)品圖像")
                                                 .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騰訊微薄客戶端開發(fā)八:微博查看(轉(zhuǎn)播,對話,點評)
下一篇:android開發(fā)總結(jié).docx
您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

Archiver|新帖|標簽|軟件|Sitemap|ZNDS智能電視網(wǎng) ( 蘇ICP備2023012627號 )

網(wǎng)絡(luò)信息服務(wù)信用承諾書 | 增值電信業(yè)務(wù)經(jīng)營許可證:蘇B2-20221768 丨 蘇公網(wǎng)安備 32011402011373號

GMT+8, 2024-10-20 07:50 , Processed in 0.066652 second(s), 13 queries , Redis On.

Powered by Discuz!

監(jiān)督舉報:report#znds.com (請將#替換為@)

© 2007-2024 ZNDS.Com

快速回復(fù) 返回頂部 返回列表