Android 提供了多種本地數據存儲方案,每種方案都有其優缺點。下面是一些常用的本地數據存儲方案及其特點:
Shared Preferences(共享首選項):
優點:
簡單易用、輕量級,適用于存儲少量的鍵值對數據。
缺點:
不適合存儲大量數據,不支持復雜數據結構。
// 存儲數據
SharedPreferences sharedPrefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("key", "value");
editor.apply();
// 讀取數據
String value = sharedPrefs.getString("key", "");
Internal Storage(內部存儲):
優點:
應用私有,數據安全,適用于存儲較小的文件。
缺點:
存儲空間相對較小,無法直接與其他應用共享數據。
// 存儲數據
String filename = "myfile.txt";
String content = "Hello, World!";
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// 讀取數據
try {
FileInputStream fis = openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
fis.close();
String content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
External Storage(外部存儲):
優點:
可存儲大量數據,支持讀寫權限控制。
缺點:
存儲性能相對較低,需要進行運行時權限檢查,可能受到設備上其他應用和用戶的操作影響。
// 存儲數據
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File file = new File(Environment.getExternalStorageDirectory(), "my_file.txt");
String content = "Hello, World!";
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 讀取數據
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File file = new File(Environment.getExternalStorageDirectory(), "my_file.txt");
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
fis.close();
String content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
SQLite 數據庫:
優點:
支持結構化數據存儲,提供查詢、排序和過濾功能,適用于存儲大量結構化數據。
缺點:
使用復雜,需要編寫 SQL 查詢語句,不適用于存儲非結構化數據。
// 創建數據庫表
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "my_database";
private static final int DATABASE_VERSION = 1;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE my_table (id INTEGER PRIMARY KEY, name TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升級數據庫版本時的操作
}
}
// 存儲數據
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
long rowId = db.insert("my_table", null, values);
// 查詢數據
Cursor cursor = db.query("my_table", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
// 處理數據
} while (cursor.moveToNext());
}
cursor.close();
db.close();
Content Providers(內容提供器):
優點:
提供標準化的界面和訪問方式,可以與其他應用共享數據。
缺點:
使用復雜,需要定義 URI 和 MIME 類型,不適合簡單的數據存儲。
// 自定義內容提供器
public class MyContentProvider extends ContentProvider {
// 實現必要的方法
}
// 存儲數據
ContentValues values = new ContentValues();
values.put("key", "value");
Uri uri = getContentResolver().insert(Uri.parse("content://com.example.provider/my_table"), values);
// 查詢數據
Cursor cursor = getContentResolver().query(Uri.parse("content://com.example.provider/my_table"), null, null, null, null);
if (cursor.moveToFirst()) {
do {
String key = cursor.getString(cursor.getColumnIndex("key"));
// 處理數據
} while (cursor.moveToNext());
}
cursor.close();
Room Persistence Library(Room 持久化庫):
優點:
基于 SQLite,提供了更簡單易用的接口和對象關系映射(ORM),可實現數據庫的高級操作。
缺點:
相對于 SQLite,引入了一定的復雜性。
選擇哪種本地數據存儲方案取決于你所需的功能和數據量。如果只需要存儲小量簡單的鍵值對數據,可以選擇 Shared Preferences;如果需要存儲較小的文件,并且數據私有性較重要,可以選擇 Internal Storage;如果需要存儲大量數據,并且需要與其他應用共享,可以選擇 External Storage 或 Content Providers;如果需要存儲結構化數據并進行高級操作,可以選擇 SQLite 數據庫或 Room Persistence Library。