Android开发基础(四)

Android开发基础(四)
本篇将从Android数据存储方式去理解Android开发。
Android开发

Android数据存储方式

Android提供了多种数据存储方式。

一、SharedPreferences存储

主要用于存储一些简单的配置信息,如登录账号密码等;
这种存储方式采用Map数据结构,以key-value的方式存储数据,可以更方便地进行读写操作;
数据存储在设备中,采用XML格式;
以下代码是Java编写,Kotlin实际上是相同的。

// 获取SharedPreferences对象  
SharedPreferences sharedPreferences = getSharedPreferences("my_data", MODE_PRIVATE);  
  
// 写入数据  
SharedPreferences.Editor editor = sharedPreferences.edit();  
editor.putString("key1", "value1");  
editor.putInt("key2", 123);  
editor.apply();  
  
// 读取数据  
String value1 = sharedPreferences.getString("key1", null);  
int value2 = sharedPreferences.getInt("key2", 0);

二、文件存储

这是一种比较常见的方式,可以用来存储图片、视频、文本等数据;
在读取和写入文件时,与Java中的I/O程序完全一样,提供了openFileInput()和openFileOutput()方法来读取设备上的文件;
以下代码是Java编写的,Kotlin要注意空值判断,可以参考Android开发基础(二)

// 创建文件对象  
File file = new File(context.getFilesDir(), "my_file.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);  
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);  
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
    String line;  
    while ((line = bufferedReader.readLine()) != null) {  
        Log.d("File Content", line);  
    }  
    inputStream.close();  
} catch (IOException e) {  
    e.printStackTrace();  
}

三、SQLite数据库存储

SQLite是一种轻量级的数据库,适用于移动设备;
Android系统提供了SQLite数据库引擎,开发者可以使用它来创建和管理数据库;
使用SQLite数据库可以方便地存储、检索和管理数据。

// 创建SQLite数据库  
val db = openOrCreateDatabase("my_database.db", Context.MODE_PRIVATE)  
  
// 创建表  
db.execSQL("CREATE TABLE IF NOT EXISTS my_table (id INTEGER PRIMARY KEY, name TEXT)")  
  
// 插入数据  
val insertStatement = "INSERT INTO my_table (name) VALUES (?)"  
db.beginTransaction()  
try {  
    val statement = db.compileStatement(insertStatement)  
    for (name in names) {  
        statement.bindString(1, name)  
        statement.executeInsert()  
    }  
    db.setTransactionSuccessful()  
} catch (e: Exception) {  
    e.printStackTrace()  
} finally {  
    db.endTransaction()  
}  
  
// 查询数据  
val cursor = db.query("my_table", null, null, null, null, null, "name ASC")  
while (cursor.moveToNext()) {  
    val id = cursor.getInt(cursor.getColumnIndex("id"))  
    val name = cursor.getString(cursor.getColumnIndex("name"))  
    Log.d("Data", "ID: $id, Name: $name")  
}  
cursor.close()  
  
// 删除数据  
db.delete("my_table", "name = ?", arrayOf("John"))

四、ContentProvider存储

当一个应用实例继承ContentProvider类并重写该类用于提供数据和存储数据的方法时,就可以向其他应用共享其数据;
通过ContentProvider,应用程序可以访问其他应用程序的数据或提供自己的数据供其他应用程序使用。

// 创建ContentProvider  
public class MyContentProvider extends ContentProvider {  
    private static final String AUTHORITY = "com.example.myapp.provider";  
    private static final String PATH = "my_table";  
    private static final int BASE_URI = 0;  
    private static final UriMatcher uriMatcher;  
  
    static {  
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);  
        uriMatcher.addURI(AUTHORITY, PATH, BASE_URI);  
    }  
  
    @Override  
    public boolean onCreate() {  
        return true;  
    }  
  
    @Override  
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {  
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();  
        queryBuilder.setTables("my_table");  
        queryBuilder.setProjectionMap(null); // 设置投影映射  
        queryBuilder.setSortOrder(sortOrder); // 设置排序方式  
        Cursor cursor = queryBuilder.query(dbHelper.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder);  
        return cursor;  
    }  
  
    @Override  
    public String getType(Uri uri) {  
        return null;  
    }  
  
    @Override  
    public Uri insert(Uri uri, ContentValues values) {  
        long rowId = dbHelper.getWritableDatabase().insert("my_table", null, values);  
        Uri newUri = Uri.withAppendedPath(uri, rowId + "");  
        return newUri;  
    }  
  
    @Override  
    public int delete(Uri uri, String selection, String[] selectionArgs) {  
        int count = dbHelper.getWritableDatabase().delete("my_table", selection, selectionArgs);  
        return count;  
    }  
  
    @Override  
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {  
        int count = dbHelper.getWritableDatabase().update("my_table", values, selection, selectionArgs);  
        return count;  
    }  
}

五、网络存储

通过网络接口进行数据的存储和上传等操作,适用于比较重要的事情,如科研、勘探、航空等实时采集到的数据需要马上通过网络传输到数据处理中心进行存储和处理。

import okhttp3.MediaType;  
import okhttp3.OkHttpClient;  
import okhttp3.RequestBody;  
import okhttp3.Request;  
import okhttp3.Response;  
  
public class NetworkStorageExample {  
  
    public static void main(String[] args) {  
        OkHttpClient client = new OkHttpClient();  
  
        MediaType mediaType = MediaType.parse("application/json");  
        RequestBody requestBody = RequestBody.create(mediaType, "{\"key\":\"value\"}"); // 你的JSON数据  
        Request request = new Request.Builder()  
                .url("http://example.com/api") // 你的API URL  
                .post(requestBody)  
                .build();  
  
        try {  
            Response response = client.newCall(request).execute();  
            if (response.isSuccessful()) {  
                // 请求成功处理响应  
            } else {  
                // 请求失败处理错误情况  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kevin写代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值