安卓实现四种数据存储方式
时间: 2024-05-23 16:06:09 浏览: 13
以下是Android实现四种数据存储方式的介绍:
1. SharePreference存储数据
```java
// 获取SharePreference对象
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
// 获取Editor对象
SharedPreferences.Editor editor = sharedPreferences.edit();
// 存储数据
editor.putString("name", "Tom");
editor.putInt("age", 18);
// 提交数据
editor.commit();
```
2. File存储数据
```java
// 获取FileOutputStream对象
FileOutputStream fos = openFileOutput("data.txt", MODE_PRIVATE);
// 写入数据
fos.write("Hello World".getBytes());// 关闭流
fos.close();
```
3. SQLite数据库存储数据
```java
// 创建数据库
SQLiteDatabase db = openOrCreateDatabase("test.db", MODE_PRIVATE, null);
// 创建表
db.execSQL("CREATE TABLE IF NOT EXISTS person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER)");
// 插入数据
db.execSQL("INSERT INTO person (name, age) VALUES ('Tom', 18)");
// 查询数据
Cursor cursor = db.rawQuery("SELECT * FROM person", null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.d("TAG", "name: " + name + ", age: " + age);
}
// 关闭游标和数据库
cursor.close();
db.close();
```
4. ContentProvider存储数据
```java
// 创建ContentValues对象
ContentValues values = new ContentValues();
values.put("name", "Tom");
values.put("age", 18);
// 插入数据
Uri uri = getContentResolver().insert(Uri.parse("content://com.example.provider/person"), values);
// 查询数据
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.d("TAG", "name: " + name + ", age: " + age);
}
// 关闭游标
cursor.close();
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)