我们可以通过SharedPreferences方式存储一些复杂的数据,如图片或类的存储,(当然,建议不要用这种方式存储)下面我们通过代码来学习:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fuza_sharedpref);
Button save = (Button) findViewById(R.id.save);
Button selectImage = (Button) findViewById(R.id.selectImage);
studentID = (EditText) findViewById(R.id.studentID);
studentName = (EditText) findViewById(R.id.studentName);
imageView = (ImageView) findViewById(R.id.imageview);
save.setOnClickListener(this);
selectImage.setOnClickListener(this);
init();
enumerateImage();
}
/**
* 第一次运行ObjectInputStream objectIs = new ObjectInputStream(byteArray)会抛异常
*/
public void init()
{
byte[] base64Bytes;
ByteArrayInputStream byteArray;
try
{
mySharedPreferences = getSharedPreferences(name_sharedP,Activity.MODE_PRIVATE);
//获取存储在xml文件中的Base64编码的字符串
String studentBase64 = mySharedPreferences.getString("student", "");
//解码
base64Bytes = Base64.decode(studentBase64.getBytes(),Base64.DEFAULT);
byteArray = new ByteArrayInputStream(base64Bytes);
ObjectInputStream objectIs = new ObjectInputStream(byteArray);
//获取student对象
Student student = (Student) objectIs.readObject();
studentID.setText(student.getId());
studentName.setText(student.getName());
//获取student头像
String imageBase64 = mySharedPreferences.getString("studentImage","");
base64Bytes = Base64.decode(imageBase64.getBytes(),Base64.DEFAULT);
byteArray = new ByteArrayInputStream(base64Bytes);
//利用Drawable创建图像
imageView.setImageDrawable(Drawable.createFromStream(byteArray,"student_image"));
objectIs.close();
byteArray.close();
}
catch (Exception e)
{
System.out.println("---init-e=" + e);
}
}
/**
* 枚举图片,利用java的反射技术,枚举R.drawable类中所有的Field,获取所有Field的值
* 如此一来,再添加新的图片或删除图片时,程序并不需要修改,就可以显示最新的图片列表
*/
public void enumerateImage()
{
try
{
Field[] fields = R.drawable.class.getDeclaredFields();
for(Field field : fields)
{
if(!"icon".equals(field.getName()) && !"browser1".equals(field.getName()) && !"browser2".equals(field.getName())
&& !"browser".equals(field.getName()))
{
imageList.add(field.getInt(R.drawable.class));
}
}
System.out.println("---size-=" + imageList.size());
}catch(Exception e)
{
System.out.println("---enumerateImage-e=" + e);
}
}
@Override
public void onClick(View v)
{
try
{
switch (v.getId())
{
case R.id.save:
savaInfo();
break;
case R.id.selectImage:
selectImage();
break;
}
}catch(Exception e)
{
setTitle("---error:" + e.getMessage());
System.out.println("---onClick-init-e=" + e);
}
}
/**
* 保存所有信息
* @throws Exception
*/
public void savaInfo() throws Exception
{
Student student = new Student();
student.setId(studentID.getText().toString());
student.setName(studentName.getText().toString());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(student);
//获取SharedPreferences对象
mySharedPreferences = getSharedPreferences(name_sharedP,Activity.MODE_PRIVATE);
//Base64编码
String studentBase64 = new String(Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("student", studentBase64);
baos = new ByteArrayOutputStream();
//将图片压缩成JPEG各式,并保存在baos流中,
//50表示压缩质量,取值范围是0~100,0表示最高的压缩比,但图像效果最差
((BitmapDrawable) imageView.getDrawable()).getBitmap().compress(CompressFormat.JPEG, 50, baos);
String imageBase64 = new String(Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));
editor.putString("studentImage", imageBase64);
//提交保存
editor.commit();
oos.close();
baos.close();
new AlertDialog.Builder(this).setTitle("保存成功.").setPositiveButton("确定", null).show();
}
public void selectImage()
{
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(imageList.get(gallery.getSelectedItemPosition()));
}
}).setNegativeButton("取消", null).show();
}
/**
* 内部类
* @author wanglejun
*/
public class ImageAdapter extends BaseAdapter
{
int mGalleryItemBackground;
private Context mcontext;
public ImageAdapter(Context context)
{
mcontext = context;
//TypedArray是一个数组容器
TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery1);
//防止在XML文件里没有定义,加上了默认值0. 获取里面属性用<名字_ 属性>连接起来
mGalleryItemBackground = typedArray.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
}
public int getCount()
{
return imageList.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(imageList.get(position));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(136, 120));
imageView.setBackgroundResource(mGalleryItemBackground);
return imageView;
}
}