android 缓存数据示例
时间: 2023-07-22 22:39:16 浏览: 138
以下是几个 Android 缓存数据的示例:
1. Shared Preferences:
```java
// 保存数据到 SharedPreferences
SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit();
editor.putString("key", "value");
editor.apply();
// 从 SharedPreferences 中获取数据
SharedPreferences preferences = getSharedPreferences("my_prefs", MODE_PRIVATE);
String value = preferences.getString("key", "");
```
2. SQLite 数据库:
```java
// 创建 SQLiteOpenHelper 对象
SQLiteOpenHelper dbHelper = new MyDatabaseHelper(context, "my_database", null, 1);
// 保存数据到 SQLite 数据库
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
values.put("age", 25);
db.insert("user", null, values);
// 从 SQLite 数据库中获取数据
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] columns = {"name", "age"};
Cursor cursor = db.query("user", columns, null, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
}
cursor.close();
```
3. 文件缓存:
```java
// 保存数据到文件缓存
String data = "Hello, world!";
File cacheDir = context.getCacheDir();
File cacheFile = new File(cacheDir, "data.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(cacheFile));
writer.write(data);
writer.close();
// 从文件缓存中获取数据
File cacheDir = context.getCacheDir();
File cacheFile = new File(cacheDir, "data.txt");
BufferedReader reader = new BufferedReader(new FileReader(cacheFile));
String data = "";
String line;
while ((line = reader.readLine()) != null) {
data += line;
}
reader.close();
```
4. 内存缓存:
```java
// 使用 LruCache 进行内存缓存
LruCache<String, String> cache = new LruCache<>(10);
cache.put("key", "value");
String value = cache.get("key");
// 使用其他缓存框架进行内存缓存,如 Glide、Volley 等
Glide.with(context).load(url).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
```
以上示例仅供参考,实际使用时需要根据具体需求进行调整。
阅读全文