Android有多種方法可以保存數據,以下是一些常用的方法:
// 保存數據
SharedPreferences sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("key", "value");
editor.apply();
// 讀取數據
String value = sharedPreferences.getString("key", "");
// 保存數據
String data = "Hello, World!";
File file = new File(getFilesDir(), "data.txt");
try {
FileWriter writer = new FileWriter(file);
writer.write(data);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
// 讀取數據
try {
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
// 創建數據庫
SQLiteDatabase database = openOrCreateDatabase("data.db", Context.MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, name TEXT)");
// 插入數據
ContentValues values = new ContentValues();
values.put("name", "John");
database.insert("user", null, values);
// 查詢數據
Cursor cursor = database.rawQuery("SELECT * FROM user", null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
Log.d("TAG", name);
}
cursor.close();
database.close();
這些方法各有優劣,選擇合適的方法取決于數據的大小、類型和使用場景。