android 中数据存取有5种,SharedPreference、File、SQLite、网络和Content Provider。
1、SharedPreference接口
SharedPreference.Editor.putString("name","小明");
SharedPreference.getString("name","");
2、File
openFileOutput("msg.txt",MODE_PRIVATE).write("小明有话说".getBytes());
byte[] b=new byte[1024];
int len=openFileInput("msg.txt").read(b);
String str=new String(b,0,len);
InputStream is=getResources().openRawResource(R.raw.data);
byte[] b=new byte[is.avaliable()];
is.read(b);
String str=new String(b);
3、SQLite
SQLiteDatabase sql=SQLiteDatabase.openOrCreateDatabase("/data/data/com.example.app/databases/user.db",null);
String str="create table student(_id integer primary key autoincrement,name nvarchar(10))";
sql.execSQL(str);
str="insert into student(name) values('小明')";
sql.execSQL(str);
ContentValues valuse=new ContentValues();
valuse.put("name","小华");
sql.insert("student",null,valuse);Cursor cur=sql.query("student",new String[]{"name"},"_id=?",new String[]{"1"},null,,null,null,null,null);
while(cur.moveToNext()){
System.out.println(cur.getString(cur.getColumnIndex("name")));
}
ContentValues valuse=new ContentValues();
valuse.put("name","小黄");
sql.update("student",valuse,"_id=?",new String[]{"2"});sql.delete("student", "_id=?", new String[]{"1"});
class UserDao extends SQLiteOpenHelper{
public StuDao(Context context, String name, int version) {
super(context, name, null, version);
}
public void getAll(){
Cursor cur=getWritableDatabase().query("student", null, null, null, null, null, null);
while(cur.moveToNext()){
String name=cur.getString(cur.getColumnIndex("name"));
System.out.println("name"+name);
}
}
}