码迷,mamicode.com
首页 > 移动开发 > 详细

[安卓基础]010. 存储数据(上)

时间:2015-08-09 23:53:25      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

存储数据(上)

这篇文章学到的内容:
1、key-value形式数据的存储方式
2、xml的存储方式


app都要存储数据。androd提供到了四种存储数据的方式:
1、使用shared preferences文件来存储key-value。
2、使用xml存储
3、使用数据库存储。
4、使用文件存储。

这里介绍前两种。

如果你的数据非常的少,比如,就几个key-value值需要存储。如存储玩家玩游戏的进度,存储积分,这些数据都可以用一个key来查询出对应的value,那采用第一种。

如果你的数据有非常多的key-value,建议用xml来存储,而且xml还可以存储较为复杂的数据。

如果你的数据要经常使用快速的增删改查,那就要采用数据库来存储了。

接下来详细的介绍这两种存储方式吧。

 

 

key-value形式数据的存储方式

SharedPreferences提供了一个文件来记录key和value值。它也提供了简单的方法来对这些key和value进行读和写。

SharedPreferences提供了两种方法来得到SharedPreferences文件:
1、getSharePrefences()如果你的应用会用到多个SharedPreferences文件,用这个方法。
2、getPreferences()得到这个Activity对应的SharedPreferences文件。
代码如下:

 1 package com.babybus.study.savingdata.sharepreferneces;
 2 
 3 import android.app.Activity;
 4 import android.content.Context;
 5 import android.content.SharedPreferences;
 6 
 7 /**
 8  * SharePreferences工具类
 9  * @author k-yuyonghao
10  *
11  */
12 public class BBSharePreferencesUtil {
13 
14     public static void saveData(Context cxt, String sharePreferencesFileName, String key, String value) {
15         
16         SharedPreferences sharedPref = cxt.getSharedPreferences(sharePreferencesFileName, Context.MODE_PRIVATE);
17         SharedPreferences.Editor editor = sharedPref.edit();
18         editor.putString(key, value);
19         editor.commit();
20     }
21     
22     public static void saveData(Context cxt, String sharePreferencesFileName, String key, int value) {
23         
24         SharedPreferences sharedPref = cxt.getSharedPreferences(sharePreferencesFileName, Context.MODE_PRIVATE);
25         SharedPreferences.Editor editor = sharedPref.edit();
26         editor.putInt(key, value);
27         editor.commit();
28     }
29     
30     public static void saveData(Context cxt, String sharePreferencesFileName, String key, boolean value) {
31         
32         SharedPreferences sharedPref = cxt.getSharedPreferences(sharePreferencesFileName, Context.MODE_PRIVATE);
33         SharedPreferences.Editor editor = sharedPref.edit();
34         editor.putBoolean(key, value);
35         editor.commit();
36     }
37     
38     public static String readStringData(Context cxt, String sharePreferencesFileName, String key) {
39         
40         SharedPreferences sharedPref = cxt.getSharedPreferences(sharePreferencesFileName, Context.MODE_PRIVATE);
41         return sharedPref.getString(key, null);
42     }
43     
44     public static Integer readIntegerData(Context cxt, String sharePreferencesFileName, String key) {
45         
46         SharedPreferences sharedPref = cxt.getSharedPreferences(sharePreferencesFileName, Context.MODE_PRIVATE);
47         return sharedPref.getInt(key, -1);
48     }
49     
50     public static Boolean readBooleanData(Context cxt, String sharePreferencesFileName, String key) {
51         
52         SharedPreferences sharedPref = cxt.getSharedPreferences(sharePreferencesFileName, Context.MODE_PRIVATE);
53         return sharedPref.getBoolean(key, false);
54     }
55     
56     
57     public static void saveData(Activity act, String key, String value) {
58         
59         SharedPreferences sharedPref = act.getPreferences(Context.MODE_PRIVATE);
60         SharedPreferences.Editor editor = sharedPref.edit();
61         editor.putString(key, value);
62         editor.commit();
63     }
64     
65     public static void saveData(Activity act, String key, int value) {
66         
67         SharedPreferences sharedPref = act.getPreferences(Context.MODE_PRIVATE);
68         SharedPreferences.Editor editor = sharedPref.edit();
69         editor.putInt(key, value);
70         editor.commit();
71     }
72     
73     public static void saveData(Activity act, String key, boolean value) {
74         
75         SharedPreferences sharedPref = act.getPreferences(Context.MODE_PRIVATE);
76         SharedPreferences.Editor editor = sharedPref.edit();
77         editor.putBoolean(key, value);
78         editor.commit();
79     }
80     
81     public static String readStringData(Activity act, String key) {
82         
83         SharedPreferences sharedPref = act.getPreferences(Context.MODE_PRIVATE);
84         return sharedPref.getString(key, null);
85     }
86     
87     public static Integer readIntegerData(Activity act, String key) {
88         
89         SharedPreferences sharedPref = act.getPreferences(Context.MODE_PRIVATE);
90         return sharedPref.getInt(key, -1);
91     }
92     
93     public static Boolean readBooleanData(Activity act, String key) {
94         
95         SharedPreferences sharedPref = act.getPreferences(Context.MODE_PRIVATE);
96         return sharedPref.getBoolean(key, false);
97     }
98 }

 

 

xml的存储方式

android建议使用pull方式来对xml进行读写。

有的时候,我们需要类似xml那样的结构来存储数据。例如,我需要存储一个班级中的每个学生的信息。学生有姓名,性别,年龄,籍贯等,这些复杂的数据,用sharePreferences来存储显然是不合适的。当然,你可也说,那我可以用数据库,但如果只有几百个学生,没必要用数据库啦,最好的方式,就是把这些信息存放在xml文件里去管理,有轻量又方便。


例如这样的数据:

 1 <class>
 2     <student>
 3         <id>1</id>
 4         <name>奇奇</name>
 5         <sex></sex>
 6         <age>3</age>
 7         <address>宝宝巴士熊猫镇竹林村123弄</address>
 8     </student>
 9     <student>
10         <id>2</id>
11         <name>妙妙</name>
12         <sex></sex>
13         <age>2</age>
14         <address>宝宝巴士熊猫镇竹林村123弄</address>
15     </student>
16     <student>
17         <id>3</id>
18         <name>兔一一</name>
19         <sex></sex>
20         <age>2</age>
21         <address>宝宝巴士兔坡512洞3号</address>
22     </student>
23     <student>
24         <id>4</id>
25         <name>小皮猴</name>
26         <sex></sex>
27         <age>5</age>
28         <address>宝宝巴士花果山180街66号</address>
29     </student>
30 </class>

 

我们一起尝试着写一段代码,在手机的sdcard卡里创建一个xml文件,写入这些学生的信息,然后再把他们读取出来。(掌握了这样的操作,xml的读写就差不多了。)

 

1、先根据xml格式创建两个类:ClassPo类和StudentPo类。

StudentPo

 1 public class StudentPo {
 2 
 3     private int id;
 4     private String name;
 5     private byte sex;
 6     private int age;
 7     private String address;
 8     
 9     
10     
11     public int getId() {
12         return id;
13     }
14     public void setId(int id) {
15         this.id = id;
16     }
17     public String getName() {
18         return name;
19     }
20     public void setName(String name) {
21         this.name = name;
22     }
23     public byte getSex() {
24         return sex;
25     }
26     public void setSex(byte sex) {
27         this.sex = sex;
28     }
29     public int getAge() {
30         return age;
31     }
32     public void setAge(int age) {
33         this.age = age;
34     }
35     public String getAddress() {
36         return address;
37     }
38     public void setAddress(String address) {
39         this.address = address;
40     }
41 }

我们根据xml定义了一个po。

 

ClassPo类

 1 public class ClassPo {
 2 
 3 
 4     private List<StudentPo> students;
 5     
 6     /**
 7      * 获得学生的信息
 8      * @return
 9      */
10     public  List<StudentPo> getStudents() {
11         return students;
12     }
13     /**
14      * 把学生信息写入xml中
15      * @param infos
16      */
17     public void setInfos(List<StudentPo> students) {
18         this.students = students;
19     }
20 }

 

最重要的,就是使用android提供的XmlSerializer,来进行文件的写和读操作。我在此写了一个管理xml读和写的类:

PullBBStudentService:

  1 package com.babybus.study.savingdata.xml;
  2 
  3 import java.io.InputStream;
  4 import java.io.OutputStream;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import org.xmlpull.v1.XmlPullParser;
  9 import org.xmlpull.v1.XmlSerializer;
 10 
 11 import android.util.Xml;
 12 
 13 /**
 14  * 使用pull方法来存储学生信息
 15  * @author k-yuyonghao
 16  *
 17  */
 18 public class PullBBStudentService {
 19     
 20     
 21     /**
 22      * 保存classPo
 23      * @param classPo
 24      * @param outStream
 25      * @param rn 根节点
 26      */
 27     public static void saveClassInfo(ClassPo classPo, OutputStream outStream) throws Exception{
 28         
 29         XmlSerializer serializer = Xml.newSerializer();
 30         serializer.setOutput(outStream, "UTF-8");
 31         serializer.startDocument("UTF-8", true);
 32         serializer.startTag(null, "class");
 33         if (classPo != null) {
 34             ArrayList<StudentPo> students = (ArrayList<StudentPo>) classPo.getStudents();
 35             if (students != null && students.size() > 0) {
 36                 for (StudentPo student : students) {
 37                     
 38                     // 得到信息
 39                     int id = student.getId();
 40                     String name = student.getName();
 41                     byte sex = student.getSex();
 42                     String address = student.getAddress();
 43                     int age = student.getAge();
 44                     
 45                     // 把信息写入
 46                     serializer.startTag(null, "student");
 47                     serializer.startTag(null, "id");
 48                     serializer.text(id + "");
 49                     serializer.endTag(null, "id");
 50                     
 51                     serializer.startTag(null, "name");
 52                     serializer.text(name + "");
 53                     serializer.endTag(null, "name");
 54                     
 55                     serializer.startTag(null, "sex");
 56                     serializer.text(sex + "");
 57                     serializer.endTag(null, "sex");
 58                     
 59                     serializer.startTag(null, "age");
 60                     serializer.text(age + "");
 61                     serializer.endTag(null, "age");
 62                     
 63                     serializer.startTag(null, "address");
 64                     serializer.text(address + "");
 65                     serializer.endTag(null, "address");
 66                     serializer.endTag(null, "student");
 67                 }
 68             }
 69             serializer.endTag(null, "class");
 70             serializer.endDocument();
 71             outStream.flush();
 72             outStream.close();
 73         }
 74     }
 75     
 76     /**
 77      * 把xml文件中的数据读取出来
 78      * @param inStream
 79      * @return
 80      * @throws Exception
 81      * <uti-8>
 82      */
 83     public static ClassPo getClassInfo(InputStream inStream) throws Exception{
 84 
 85         ClassPo classPo = null;
 86         List<StudentPo> students = null;
 87         StudentPo student = null;
 88         
 89         XmlPullParser pullParser = Xml.newPullParser();
 90         pullParser.setInput(inStream, "UTF-8");
 91         int event = pullParser.getEventType();
 92         while (event != XmlPullParser.END_DOCUMENT) {
 93             
 94             String eventName = pullParser.getName();
 95             switch (event) {
 96             case XmlPullParser.START_DOCUMENT:
 97                 // 开始初始化
 98                 classPo = new ClassPo();
 99                 students= new ArrayList<StudentPo>();
100                 break;
101             case XmlPullParser.START_TAG:
102                 String key = eventName;
103                 
104                 if (key != null && "student".equals(key)) {
105                     
106                     student = new StudentPo();
107                     
108                 }
109                 if (key != null && "id".equals(key)) {
110                     
111                     int id = student.getId();
112                     if (student != null) {
113                         student.setId(id);
114                     }
115                 }
116                 if (key != null && "name".equals(key)) {
117                     
118                     String name = student.getName();
119                     if (student != null) {
120                         student.setName(name);
121                     }
122                 }
123                 if (key != null && "sex".equals(key)) {
124                     
125                     byte sex = student.getSex();
126                     if (student != null) {
127                         student.setSex(sex);
128                     }
129                 }
130                 if (key != null && "age".equals(key)) {
131                     
132                     int age = student.getAge();
133                     if (student != null) {
134                         student.setAge(age);
135                     }
136                 }
137                 if (key != null && "address".equals(key)) {
138                     
139                     String address = student.getAddress();
140                     if (student != null) {
141                         student.setAddress(address);
142                     }
143                 }
144                 
145                 break;
146             case XmlPullParser.END_TAG:
147                 if (students != null) {
148                     if (student != null) {
149                         students.add(student);
150                     }
151                     
152                 }
153                 student = null;
154                 break;
155             }
156             event = pullParser.next();
157         }
158         // 把信息写入到classPo类中
159         classPo.setInfos(students);
160         return classPo;
161     }
162 }

使用这两个方法,就可以把学生的信息存储在xml中,也可以从xml文件中,读取每一个学生信息到内存中。

(Note:在这里提一个,pull方式写xml是非常快的,如果你要修改某个学生信息,该怎么做呢?在这里告诉我的工作经验,就是把这些信息全部读出来,然后修改List中对应的学生信息后,你可也使用hasnmap来存储,这样查询速度就非常快。再全部重新写入进去。pull方式写xml是非常快的,在此你不用担心效率问题,这样就解决了修改的问题。)

 

技术分享

本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 

转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4716495.html

 

[安卓基础]010. 存储数据(上)

标签:

原文地址:http://www.cnblogs.com/superdo/p/4716495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!