Android本地存储(无数据库)可以使用SharedPreferences、文件存储和内部存储等方式来实现。下面给出这三种方法的代码示例:
// 获取SharedPreferences对象
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// 获取SharedPreferences的编辑器
SharedPreferences.Editor editor = sharedPreferences.edit();
// 存储数据
editor.putString("username", "John");
editor.putInt("age", 25);
editor.putBoolean("isMarried", false);
// 提交保存数据
editor.apply();
// 获取存储的数据
String username = sharedPreferences.getString("username", "");
int age = sharedPreferences.getInt("age", 0);
boolean isMarried = sharedPreferences.getBoolean("isMarried", false);
// 获取应用的内部存储目录
File file = new File(getApplicationContext().getFilesDir(), "data.txt");
try {
// 创建文件输出流
FileOutputStream fos = new FileOutputStream(file);
// 写入数据
fos.write("Hello, World!".getBytes());
// 关闭文件输出流
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// 创建文件输入流
FileInputStream fis = new FileInputStream(file);
// 创建字节数组
byte[] buffer = new byte[(int) file.length()];
// 读取文件数据到字节数组
fis.read(buffer);
// 关闭文件输入流
fis.close();
// 将字节数组转换为字符串
String data = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
// 获取应用的内部存储目录
File file = new File(getApplicationContext().getFilesDir(), "data.txt");
try {
// 创建文件输出流
FileWriter writer = new FileWriter(file);
// 写入数据
writer.write("Hello, World!");
// 关闭文件输出流
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// 创建文件输入流
FileReader reader = new FileReader(file);
// 创建字符数组
char[] buffer = new char[(int) file.length()];
// 读取文件数据到字符数组
reader.read(buffer);
// 关闭文件输入流
reader.close();
// 将字符数组转换为字符串
String data = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
以上是三种常用的Android本地存储解决方法的代码示例。根据你的需求和实际情况选择适合的方法。