在Android应用程序上保存两个字符串有多种方法,以下是其中几种常见的方法:
// 读取数据
SharedPreferences sharedPreferences = getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
String string1 = sharedPreferences.getString("string1", "");
String string2 = sharedPreferences.getString("string2", "");
```
// 插入数据
ContentValues values = new ContentValues();
values.put("string1", "value1");
values.put("string2", "value2");
database.insert("my_table", null, values);
// 查询数据
Cursor cursor = database.query("my_table", new String[]{"string1", "string2"}, null, null, null, null, null);
if (cursor.moveToFirst()) {
String string1 = cursor.getString(cursor.getColumnIndex("string1"));
String string2 = cursor.getString(cursor.getColumnIndex("string2"));
}
cursor.close();
database.close();
```
// 读取数据
try {
FileInputStream fis = openFileInput(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
stringBuilder.append(line);
}
br.close();
fis.close();
String[] strings = stringBuilder.toString().split("\n");
String string1 = strings[0];
String string2 = strings[1];
} catch (IOException e) {
e.printStackTrace();
}
```
以上是保存两个字符串的几种常见方法,具体选择哪种方法取决于数据的类型、规模和使用场景。
领取专属 10元无门槛券
手把手带您无忧上云