Android有多種方法可以保存數(shù)據(jù),以下是一些常用的方法:
// 保存數(shù)據(jù)
SharedPreferences sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("key", "value");
editor.apply();
// 讀取數(shù)據(jù)
String value = sharedPreferences.getString("key", "");
// 保存數(shù)據(jù)
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();
}
// 讀取數(shù)據(jù)
try {
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
// 創(chuàng)建數(shù)據(jù)庫
SQLiteDatabase database = openOrCreateDatabase("data.db", Context.MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, name TEXT)");
// 插入數(shù)據(jù)
ContentValues values = new ContentValues();
values.put("name", "John");
database.insert("user", null, values);
// 查詢數(shù)據(jù)
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();
這些方法各有優(yōu)劣,選擇合適的方法取決于數(shù)據(jù)的大小、類型和使用場景。