Android数据的几种存储方式和方法
sharedPreference入门
1.保存信息
SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
2.获取信息SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
sp.getString("username", "");
sp.getString("password", "");
?
xml文件的序列化
?
public void save(View view) {
XmlSerializer xmlSerializer = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory(),
"config.xml");
try {
FileOutputStream fos = new FileOutputStream(file);
xmlSerializer. setOutput(fos, "utf-8");
xmlSerializer. startDocument("utf-8", true);
xmlSerializer. startTag(null, "smss");
for (SmsInfo info : infos) {
xmlSerializer.startTag(null, "sms");
xmlSerializer. attribute(null, "id", info.getId() + "");
xmlSerializer.startTag(null, "date");
xmlSerializer. text(info.getDate() + "");
xmlSerializer.endTag(null, "date");
xmlSerializer.startTag(null, "address");
xmlSerializer.text(info.getAddress());
xmlSerializer.endTag(null, "address");
xmlSerializer.startTag(null, "body");
xmlSerializer.text(info.getBody());
xmlSerializer.endTag(null, "body");
xmlSerializer.endTag(null, "sms");
}
xmlSerializer.endTag(null, "smss");
xmlSerializer.endDocument();
fos.close();
Toast.makeText(this, "保存成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "保存失败", 0).show();
}
}
采用pull解析xml文件
1.准备一个xml文件,将其拷贝到工程的src目录下
<?xml version="1.0" encoding="utf-8"?>
<infos>
<city id="1">
<temp>20'C/30'C</temp>
<weather>多云</weather>
<wind>南风3级</wind>
<name>上海</name>
<pm>200</pm>
</city>
<city id="2">
<temp>20'C/35'C</temp>
<weather>暴雨</weather>
<wind>南风10级</wind>
<name>北京</name>
<pm>800</pm>
</city>
<city id="3">
<temp>0'C/10'C</temp>
<weather>暴雪</weather>
<wind>北风32级</wind>
<name>广州</name>
<pm>200</pm>
</city>
</infos>
2.核心代码
public static ArrayList<WeatherInfo> getWeatherInfo(InputStream is)
throws Exception {
ArrayList<WeatherInfo> infos = null;
WeatherInfo info = null;
// XmlPullParser parser = Xml.newPullParser();
XmlPullParserFactory fac = XmlPullParserFactory.newInstance();
XmlPullParser parser = fac.newPullParser();
parser.setInput(is, "utf-8");
int type = parser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("infos".equals(parser.getName())) {
infos = new ArrayList<WeatherInfo>();
} else if ("city".equals(parser.getName())) {
info = new WeatherInfo();
info.setId(Integer.parseInt(parser.getAttributeValue(0)));
} else if ("temp".equals(parser.getName())) {
info.setTemp(parser.nextText());
} else if ("weather".equals(parser.getName())) {
info.setWeather(parser.nextText());
} else if ("wind".equals(parser.getName())) {
info.setWind(parser.nextText());
} else if ("name".equals(parser.getName())) {
info.setName(parser.nextText());
} else if ("pm".equals(parser.getName())) {
info.setPm(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("city".equals(parser.getName())) {
infos.add(info);
info = null;
}
break;
}
type = parser.next();
}
return infos;
}
3.调用
public class WeatherActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv_info = (TextView) this.findViewById(R.id.vt_info);
try {
ArrayList<WeatherInfo> infos = WeaterService
.getWeatherInfo(WeatherActivity.class.getClassLoader()
.getResourceAsStream("weather.xml"));
StringBuffer sb = new StringBuffer();
for (WeatherInfo info : infos) {
sb.append(info);
sb.append("\n");
}
tv_info.setText(sb.toString());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "xml解析失败", 0).show();
}
}
}
android下创建一个sqlite数据库
public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {
private static final String DBFILENAME = "person.db";
private static int db_version = 2;
public PersonSQLiteOpenHelper(Context context) {
super(context, DBFILENAME, null, db_version);
}
/**
* 当数据库第一次创建时调用
*/
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table person(id integer primary key autoincrement,name varchar(20),number varchar(20))";
db.execSQL(sql);
}
/**
* 当数据库的版本号发生增加的时候调用
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("数据库更改!");
String sql = "alter table person add account varchar(20)";
db.execSQL(sql);
}
}
sql语句实现数据库的增删改查
1.添加条目
public void add(String name, String number) {
SQLiteDatabase db = this.helper.getWritableDatabase();
db.execSQL("insert into person(name,number) values(?,?)", new Object[] {
name, number });
db.close();
}
2.查找条目是否存在
public boolean find(String name) {
SQLiteDatabase db = this.helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from person where name=?",
new String[] { name });
boolean result = cursor.moveToNext();
cursor.close();
db.close();
return result;
}
3.更新条目
public void update(String name, String newNumber) {
SQLiteDatabase db = this.helper.getWritableDatabase();
db.execSQL("update person set number=? where name=?", new Object[] {
newNumber, name });
db.close();
}
4.删除条目
public void delete(String name) {
SQLiteDatabase db = this.helper.getWritableDatabase();
db.execSQL("delete from person where name=?", new Object[] { name });
db.close();
}
5.查找所有条目
public ArrayList<Person> findAll() {
SQLiteDatabase db = this.helper.getReadableDatabase();
ArrayList<Person> persons = new ArrayList<Person>();
Cursor cursor = db.rawQuery("select * from person", null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String number = cursor.getString(cursor.getColumnIndex("number"));
Person p = new Person(id, name, number);
persons.add(p);
}
cursor.close();
db.close();
return persons;
}
系统api实现数据库的增删改查&sqlite3工具的使用
1.添加条目
public long add(String name, String number) {
SQLiteDatabase db = this.helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("number", number);
long id = db.insert("person", null, values);
db.close();
return id;
}
2.查找条目是否存在
public boolean find(String name) {
SQLiteDatabase db = this.helper.getReadableDatabase();
Cursor cursor = db.query("person", null, "name=?",
new String[] { name }, null, null, null);
boolean result = cursor.moveToNext();
cursor.close();
db.close();
return result;
}
3.更新条目
public int update(String name, String newNumber) {
SQLiteDatabase db = this.helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("number", newNumber);
int number = db.update("person", values, "name=?",
new String[] { name });
db.close();
return number;
}
4.删除条目
public int delete(String name) {
SQLiteDatabase db = this.helper.getWritableDatabase();
// db.execSQL("delete from person where name=?", new Object[] { name });
int number = db.delete("person", "name=?", new String[] { name });
db.close();
return number;
}
5.查找所有条目
public ArrayList<Person> findAll() {
SQLiteDatabase db = this.helper.getReadableDatabase();
ArrayList<Person> persons = new ArrayList<Person>();
Cursor cursor = db.query("person", null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String number = cursor.getString(cursor.getColumnIndex("number"));
Person p = new Person(id, name, number);
persons.add(p);
}
cursor.close();
db.close();
return persons;
}
数据库的事务
public void testTransaction() {
PersonSQLiteOpenHelper helper = new PersonSQLiteOpenHelper(getContext());
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
db.execSQL(
"update person set account = account + 1000 where name=?",
new Object[] { "tom" });
int i = 1 / 0;
db.execSQL(
"update person set account = account - 1000 where name=?",
new Object[] { "jerry" });
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
db.close();
}
}
posted on 2012-10-04 17:59 Freedom000 阅读(155) 评论(0) 编辑 收藏 举报