Android數據存儲方式及存儲位置
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//shared_prefs/hello.xml
XML file Content:
二、Internal Storage
使用:
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//files/hello.txt
三、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//files/hello.txt
四、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