SharedPreferes
SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中 重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长 整形、Int整形、String字符串型的保存。
1、 实现保存
private void findViews() { nameEt = (EditText) this.findViewById(R.id.nameEt); ageEt = (EditText) this.findViewById(R.id.ageEt); saveBtn = (Button) this.findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String name = nameEt.getText().toString().trim(); int age = Integer.valueOf(ageEt.getText().toString().trim());
SharedPreferences sharedPreferences = SharedpreferencesTestActivity.this .getSharedPreferences("myOption", MODE_PRIVATE); Editor editor = sharedPreferences.edit(); editor.putString("name" ,name); editor.putInt("age", age);
editor.commit(); } }); } |
2、 添加读取功能
资源添加
<string name="read_text">读取</string> |
public void onClick(View v) {
SharedPreferences sp = getSharedPreferences("myOption",
MODE_PRIVATE);
String name="无名氏";
int age = -1;
switch (v.getId()) {
case R.id.saveBtn:
name = nameEt.getText().toString().trim();
age = Integer.valueOf(ageEt.getText().toString().trim());
Editor editor = sp.edit();
editor.putString("name", name);
editor.putInt("age", age);
editor.commit();
break;
case R.id.readBtn:
name = sp.getString("name", "无名氏");
age = sp.getInt("age", -1);
Toast.makeText(this,
"姓名: "+name+ " 年龄: " +String.valueOf(age),
Toast.LENGTH_SHORT).show();
break;
}
}
3、 读取其它应用程序的SharedPreferences
首先保证创建SharedPreferences的工程中使用的是:
Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE |
其次,当前工程中读取的代码为:
try { Context otherContext = this.createPackageContext("cn.class3g.activity", Context.CONTEXT_IGNORE_SECURITY); SharedPreferences sp = otherContext.getSharedPreferences("myOption", MODE_PRIVATE);
String res = "姓名:"+ sp.getString("name", null).toString() + " 年龄:"+ String.valueOf(sp.getInt("age", -1)); Toast.makeText(this, res, Toast.LENGTH_LONG).show();
} catch (NameNotFoundException e) { e.printStackTrace(); } |
SQLite
SQLite 是一个开源的嵌入式关系数据库
使用SQLiteOpenHelper抽象类建立数据库
为了实现对数据库版本进行管理, SQLiteOpenHelper 类提供了两个重要的方法 , 分别onCreate(SQLiteDatabase db) 和 onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)用于初次使用软件时生成数据库表,后者用于升级软件时更新数据库表结构。
public SQLiteOpenHelper (Context context, String name,
SQLiteDatabase.CursorFactory factory, int version)
Context :代表应用的上下文。
Name : 代表数据库的名称。
Factory: 代表记录集游标工厂 , 是专门用来生成记录集游标, 记录集游标是对查询结果进行迭代的,后面我们会继续介绍。
Version :代表数据库的版本,如果以后升级软件的时候,需要更改 Version 版本号,那么onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 方法会被调用,在这个方法中比较适合实现软件更新时修改数据库表结构的工作。
实验步骤
1、建立数据库类DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper { static String dbName = "myAndroid_db.db"; static int version=1;
public DatabaseHelper(Context context) { super(context, dbName, null, version); } //第一次使用的时候会被调用,用来建库 public void onCreate(SQLiteDatabase db) { String sql = "create table person11(personid integer primary key autoincrement, name varchar(20),age integer)"; db.execSQL(sql); }
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "drop table if exists person"; onCreate(db); } } |
2、编写测试类进行测试
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // String sql = "drop table if exists person"; // Log.i("TAG","我被删除了"); // onCreate(db);
String sql = "alter table person add phone char(20) null"; db.execSQL(sql); } |
CRUD
实验步骤
建立PersonService业务类
package cn.class3g.service; … public class PersonService {
private DatabaseHelper dbHelper; private Context context;
public PersonService(Context context) { this.context = context; dbHelper = new DatabaseHelper(context); }
public void save(Person person) { SQLiteDatabase db = dbHelper.getWritableDatabase(); // String sql = "insert into person(name,age) values('Tom',21)"; // db.execSQL(sql);
// 防止用户输入数据错误,如:name="T'om" String sql = "insert into person(name,age) values(?,?)"; db.execSQL(sql, new Object[] { person.getName(), person.getAge() }); }
public void update(Person person, int id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String sql = "update person set name=?,age=? where personid=?"; db.execSQL(sql, new Object[] { person.getName(), person.getAge(), id }); }
public Person find(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select * from person where personid=?"; Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(id) });
if (cursor.moveToNext()) { Person person = new Person(); person.setName(cursor.getString(cursor.getColumnIndex("name"))); person.setId(cursor.getInt(0)); person.setAge(cursor.getInt(2));
cursor.close(); // 关闭游标 return person; } return null; }
public void delete(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "delete from person where personid=?"; db.execSQL(sql, new Object[] { id }); }
public List<Person> getScrollData(int startIdx, int count) {
SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select * from person limit ?,?"; Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(startIdx), String.valueOf(count) });
List<Person> list = new ArrayList<Person>();
while(cursor.moveToNext()){ Person p = new Person(); p.setId(cursor.getInt(0)); p.setName(cursor.getString(1)); p.setAge(cursor.getInt(2));
list.add(p); } cursor.close(); return list; } public long getRecordsCount() { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select count(*) from person"; Cursor cursor = db.rawQuery(sql, null); cursor.moveToFirst(); long count = cursor.getInt(0); cursor.close(); return count; } } |
在测试类cn.class3g.db. PersonServiceTest中添加对应测试方法
package cn.class3g.db; … public class PersonServiceTest extends AndroidTestCase {
public void testSave() throws Throwable{ PersonService service = new PersonService(this.getContext());
Person person = new Person(); person.setName("zhangxiaoxiao"); service.save(person);
Person person2 = new Person(); person2.setName("laobi"); service.save(person2);
Person person3 = new Person(); person3.setName("lili"); service.save(person3);
Person person4 = new Person(); person4.setName("zhaoxiaogang"); service.save(person4); } public void testUpdate() throws Throwable{ PersonService ps = new PersonService(this.getContext()); Person person = new Person("Ton", 122); ps.update(person, 2);//需要实现查看数据库中Ton的id值 } public void testFind() throws Throwable{ PersonService ps = new PersonService(this.getContext()); Person person = ps.find(2); Log.i("TAG",person.toString()); } public void testDelete() throws Throwable{ PersonService ps = new PersonService(this.getContext()); ps.delete(2); } public void testScroll() throws Throwable{ PersonService service = new PersonService(this.getContext()); List<Person> personList = service.getScrollData(3, 2);
Log.i("TAG",personList.toString()); } public void testCount() throws Throwable{ PersonService service = new PersonService(this.getContext()); long count = service.getRecordsCount(); Log.i("TAG", String.valueOf(count)); } } |
常见异常
android.database.sqlite.SQLiteException: Can't upgrade read-only database from version 0 to 1:
这个错误基本上都是sql有问题导致的,仔细检查sql即可。