android+studio实现数据存储
时间: 2023-12-15 13:32:58 浏览: 35
Android Studio提供了多种数据存储方式,以下是其中的三种:
1. 使用SharedPreferences存储数据
SharedPreferences是Android平台上一个轻量级的存储类,用来保存应用的一些常用配置,比如窗口状态,字体大小等。SharedPreferences存储的数据是以键值对的形式存储的,可以存储基本数据类型和String类型的数据。以下是一个使用SharedPreferences存储数据的例子:
```java
// 获取SharedPreferences对象
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
// 获取SharedPreferences.Editor对象
SharedPreferences.Editor editor = sharedPreferences.edit();
// 存储数据
editor.putString("name", "Tom");
editor.putInt("age", 18);
// 提交数据
editor.apply();
```
2. 文件存储数据
Android平台上可以使用File类来进行文件操作,可以通过FileOutputStream和FileInputStream来进行文件的读写操作。以下是一个使用文件存储数据的例子:
```java
// 获取文件路径
File file = new File(getFilesDir(), "data.txt");
// 写入数据
try {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write("Hello World".getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 读取数据
try {
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
String data = new String(bytes);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
```
3. SQLite数据库存储数据
SQLite是Android平台上的一个轻量级关系型数据库,可以用来存储结构化数据。可以使用Android提供的SQLiteOpenHelper类来创建和管理数据库。以下是一个使用SQLite存储数据的例子:
```java
// 创建数据库
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String CREATE_TABLE = "create table Book ("
+ "id integer primary key autoincrement, "
+ "author text, "
+ "price real, "
+ "pages integer, "
+ "name text)";
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
// 插入数据
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "The Da Vinci Code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
db.insert("Book", null, values);
// 查询数据
Cursor cursor = db.query("Book", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
String author = cursor.getString(cursor.getColumnIndex("author"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
double price = cursor.getDouble(cursor.getColumnIndex("price"));
} while (cursor.moveToNext());
}
cursor.close();
```