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();
这些方法各有优劣,选择合适的方法取决于数据的大小、类型和使用场景。