我们可以通过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;

}

}

通过SharedPreferences方式存储复杂数据相关推荐

  1. mongodb存储二进制数据的二种方式——binary bson或gridfs

    python 版本为2.7 mongodb版本2.6.5 使用mongodb存储文件,可以使用两种方式,一种是像存储普通数据那样,将文件转化为二进制数据存入mongodb,另一种使用gridfs,咱们 ...

  2. smartforms句柄与以簇的方式存储数据。

    说明:Smartforms输出打印,设置句柄,用于传递参数. REPORT  ZIEB_WWFLD. *-----------------      TABLES      ------------- ...

  3. Android学习笔记36:使用SQLite方式存储数据

    在Android中一共提供了5种数据存储方式,分别为: (1)Files:通过FileInputStream和FileOutputStream对文件进行操作.具体使用方法可以参阅博文<Andro ...

  4. 尽量使用写文本方式存储数据(pandas 和 file write效率对比)

    对比:使用 pandas 存储数据 VS 使用写文本 方式存储数据 import pandas as pd import time def pandasWrite():t0 = time.time() ...

  5. python numpy读取数据_numpy中以文本的方式存储以及读取数据方法

    这篇文章主要介绍了关于numpy中以文本的方式存储以及读取数据方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下 Numpy中除了能够把数据以二进制文件的方式保存到文件中以外,还可以选 ...

  6. 数据存储-大数据的三种存储方式

    互联网时代各种存储框架层出不穷,眼花缭乱,比如传统的关系型数据库:Oracle.MySQL:新兴的NoSQL:HBase.Cassandra.Redis:全文检索框架:ES.Solr等.如何为自己的业 ...

  7. php数据存储mysql_php – 在MySQL中存储路线数据的最佳方式

    我正在开发一个应用程序,它要求我存储一些位置的方向,下面是我试图存储的数据的示例: 方向1 从西部:乘528 East(Beechline),经过机场出口,然后从13号出口驶入Narcoossee R ...

  8. android sharedpreferences 存储对象,android中SharedPreferences实现存储用户名功能

    1. 简介 SharedPreferences是一种轻型的数据存储方式,通过key-value键值对的方式将数据存储在xml文件中,常用于存储简单的配置信息. 2. 使用方式 2.1 获取Shared ...

  9. 数据存储:数据备份:自动备份

    自从Android 6.0(API 23)以来,Android已经提供了自动备份应用程序功能,作为开发人员快速添加备份功能到他们的应用程序的一种方式. 自动备份通过将应用数据上传到用户的Google云 ...

最新文章

  1. java.lang.RuntimeException: Parcelable encountered IOException writing
  2. C++ string详解
  3. 科大星云诗社动态20210216
  4. 手写简版spring --10--容器事件和事件监听器
  5. Leetcode题库 110.平衡二叉树(递归 C实现)
  6. springboot activiti工作流简单示例
  7. java控制台输出五行字符串_java五行代码导出Excel
  8. 【Flink】Flink flink-runtime.version.properties generated correctly. You MUST run mvn generate-source
  9. 互联网的逻辑和电商的逻辑是不一样的
  10. 物联网时代,隐私还有救吗?
  11. Android Retrofit下载文件进度
  12. HTTP:一次完整的HTTP服务过程
  13. Javascrīpt开发工具大集合
  14. java基础知识——JAVA中的函数(方法)
  15. ESP8285开发、比ESP8266好,利用率比ESP-01更好
  16. 中文code:blocks安装(三分钟包安装成功,不成功你找我)
  17. pip install pyodbc : ERROR: Command errored out with exit status 1
  18. bugku ctf 杂项 旋转跳跃 (熟悉的声音中貌似又隐藏着啥,key:syclovergeek)
  19. php编码小坑之调用新浪天气api和阿凡达天气api
  20. idea 编译通过,无法调试 Frames are not available

热门文章

  1. android graphic(15)—fence
  2. 《AngularJS高级程序设计》——第2章 你的第一个AngularJS应用 2.1 准备项目
  3. 使用开源库 Objective-C RegEx Categories 处理正则表达式
  4. MySQL/MariaDB Tips
  5. MapReduce运行时出现java.lang.NoClassDefFoundError
  6. ubuntu下查看apache的日志
  7. JQuery合并table单元格--有限制(table格式需要注意)
  8. 自定义事件(如未作说明,本博客文档都是用C#代码)
  9. Springboot2.0从零开始搭建脚手架-初始化和整合MybatisPlus3.0+...
  10. CIO关注:数字化转型带来的IT版图巨变正在成为新的挑战