private void load() {
BufferedReader in=null;
StringBuilder content=new StringBuilder();
try {
in=new BufferedReader(new InputStreamReader(openFileInput("data")));
String text="";
while ((text=in.readLine())!=null){
content.append(text);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
edit.setText(content);
}
}
}
SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据。
//实例化SharedPreferences对象(第一步)
SharedPreferences mySharedPreferences= getSharedPreferences("test",
Activity.MODE_PRIVATE);
//实例化SharedPreferences.Editor对象(第二步)
SharedPreferences.Editor editor = mySharedPreferences.edit();
//用putString的方法保存数据
editor.putString("name", "Karl");
editor.putString("habit", "sleep");
//提交当前数据
editor.commit();
android为了方便对数据库进行创建(onCreate)和升级(onUpdate),专门提供了一个SQLiteOpenHelper帮助类。数据库的操作是增删改查(CRUD).
建立表
create table [表名]
(
–[字段] [数据类型] [列的特征],
id int identity(1,1) not null,–identity(1,1) 是自动增长(起始值,递增值) ,not null 是不许为空(默认允许为空)
name varchar(20) not null,
)
protected static final String CREATE_BOOK="create table Book(" + "id integer primary key autoincrement," + "author text," + "price real," + "pages integer," + "name text," + "category_id integer)";
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
Cursor cursor=db.query("Book",null,null,null,null,null,null);
if (cursor.moveToFirst()) {
while(cursor.moveToNext()){
String name=cursor.getString(cursor.getColumnIndex("name"));
String author=cursor.getString(cursor.getColumnIndex("author"));
int pages=cursor.getInt(cursor.getColumnIndex("pages"));
double price=cursor.getDouble(cursor.getColumnIndex("price"));
Log.d("MainActivity","book name is"+name);
Log.d("MainActivity","book author is"+author);
Log.d("MainActivity","book pages is"+pages);
Log.d("MainActivity","book price is"+price);
}
}
cursor.close();
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
db.beginTransaction();
try {
db.delete("Book",null,null);
if (true) {
throw new NullPointerException();
}
ContentValues values=new ContentValues();
values.put("name","Game");
values.put("author","TT");
values.put("pages",123);
values.put("price",222);
db.insert("Book", null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
}finally {
db.endTransaction();//如果事务没有执行成功,删除操作是不能生效的。
}
参考的资料和文献:
DataOutputStream、FileOutputStream和ByteArrayOutputStream:http://m.blog.csdn.net/blog/linchengzhi/7620634
java中的IO操作:http://www.zaojiahua.com/1453.html
经典SQL语句大全: http://www.cnblogs.com/yubinfeng/archive/2010/11/02/1867386.html