Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 數據存儲方式及存儲位置總覽

編輯:關於 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();

存儲位置:以 XML 格式存放於 /data/data/<package name>/shared_prefs/hello.xml

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="Name">mike</string>
    <float name="Salary" value="1080.55" />
    <int name="Age" value="33" />
</map>

二、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/<package name>/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/<package name>/files/hello.txt

四、SQLite

使用:

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) {
        // 模式更新時使用
    }
}

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 權限

以上五種方式各有適用情境:Shared Preferences 適合少量鍵值資料,內部/外部存儲適合檔案,SQLite 適合結構化資料,Content Provider 則用於跨應用共享數據。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved