Android数据存储是很重要的一个环节,有以下几种方式:
一、Shared Preference
使用:
SharedPreferences sp =
MainHello.this.getSharedPreferences("hello", 0);
int age = sp.getInt(“Age”, 0); // read
SharedPreferences.Editor ed = sp.edit(); // write
ed.putString("Name", "mike");
ed.putInt("Age", 33);
ed.putFloat("Salary", 1080.55f);
ed.commit();
Data is stored in xml format, located at
/data/data/
XML file Content:
使用:
try {
String str = "Hello World";
FileOutputStream fos =
MainHello.this.openFileOutput("hello.txt", MODE_PRIVATE);
fos.write(str.getBytes());
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
/data/data/
三、External Storage
使用:
String str = "Hello World";
File file = new File(getExternalFilesDir(null), "hello.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(str.getBytes());
fos.close();
/mnt/sdcard/Android/data/
四、SQL Lite
使用:
public class MyDB extends SQLiteOpenHelper {
public MyDB(Context context) {
super(context, "TestDB", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE stu (" +
"sid INTEGER," +
"sname TEXT)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Used when 模式更新
}
}
MyDB d = new MyDB(MainHello.this);
SQLiteDatabase db = d.getWritableDatabase();
db.execSQL("INSERT INTO stu(sid, sname) VALUES(3, 'Jason')");
/data/data/com.hezongjian/databases/
五、Content Provider
使用:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI, null, null, null, null);
cur.moveToFirst();
int num = cur.getColumnIndex(CallLog.Calls.NUMBER);
do
{
Log.e("CALLLOG", cur.getString(num));
}while(cur.moveToNext());
cur.close();
// android.permission.READ_CONTACTS permission