Android 提供了多种本地数据存储方案,每种方案都有其优缺点。下面是一些常用的本地数据存储方案及其特点:

Shared Preferences(共享首选项):
优点:简单易用、轻量级,适用于存储少量的键值对数据。
缺点:不适合存储大量数据,不支持复杂数据结构。

// 存储数据
SharedPreferences sharedPrefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("key", "value");
editor.apply();

// 读取数据
String value = sharedPrefs.getString("key", "");
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

Internal Storage(内部存储):
优点:应用私有,数据安全,适用于存储较小的文件。
缺点:存储空间相对较小,无法直接与其他应用共享数据。

// 存储数据
String filename = "myfile.txt";
String content = "Hello, World!";
try {
    FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
    fos.write(content.getBytes());
    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}

// 读取数据
try {
    FileInputStream fis = openFileInput(filename);
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(isr);
    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    fis.close();
    String content = sb.toString();
} catch (IOException e) {
    e.printStackTrace();
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

External Storage(外部存储):
优点:可存储大量数据,支持读写权限控制。
缺点:存储性能相对较低,需要进行运行时权限检查,可能受到设备上其他应用和用户的操作影响。

// 存储数据
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
    File file = new File(Environment.getExternalStorageDirectory(), "my_file.txt");
    String content = "Hello, World!";
    try {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(content.getBytes());
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 读取数据
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
    File file = new File(Environment.getExternalStorageDirectory(), "my_file.txt");
    try {
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        fis.close();
        String content = sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.

SQLite 数据库:
优点:支持结构化数据存储,提供查询、排序和过滤功能,适用于存储大量结构化数据。
缺点:使用复杂,需要编写 SQL 查询语句,不适用于存储非结构化数据。

// 创建数据库表
public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "my_database";
    private static final int DATABASE_VERSION = 1;

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTableQuery = "CREATE TABLE my_table (id INTEGER PRIMARY KEY, name TEXT)";
        db.execSQL(createTableQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 升级数据库版本时的操作
    }
}

// 存储数据
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
long rowId = db.insert("my_table", null, values);

// 查询数据
Cursor cursor = db.query("my_table", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
    do {
        int id = cursor.getInt(cursor.getColumnIndex("id"));
        String name = cursor.getString(cursor.getColumnIndex("name"));
        // 处理数据
    } while (cursor.moveToNext());
}
cursor.close();
db.close();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.

Content Providers(内容提供器):
优点:提供标准化的界面和访问方式,可以与其他应用共享数据。
缺点:使用复杂,需要定义 URI 和 MIME 类型,不适合简单的数据存储。

// 自定义内容提供器
public class MyContentProvider extends ContentProvider {
    // 实现必要的方法
}

// 存储数据
ContentValues values = new ContentValues();
values.put("key", "value");
Uri uri = getContentResolver().insert(Uri.parse("content://com.example.provider/my_table"), values);

// 查询数据
Cursor cursor = getContentResolver().query(Uri.parse("content://com.example.provider/my_table"), null, null, null, null);
if (cursor.moveToFirst()) {
    do {
        String key = cursor.getString(cursor.getColumnIndex("key"));
        // 处理数据
    } while (cursor.moveToNext());
}
cursor.close();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

Room Persistence Library(Room 持久化库):
优点:基于 SQLite,提供了更简单易用的接口和对象关系映射(ORM),可实现数据库的高级操作。
缺点:相对于 SQLite,引入了一定的复杂性。

选择哪种本地数据存储方案取决于你所需的功能和数据量。如果只需要存储小量简单的键值对数据,可以选择 Shared Preferences;如果需要存储较小的文件,并且数据私有性较重要,可以选择 Internal Storage;如果需要存储大量数据,并且需要与其他应用共享,可以选择 External Storage 或 Content Providers;如果需要存储结构化数据并进行高级操作,可以选择 SQLite 数据库或 Room Persistence Library。

最后

如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。

如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。

Android数据本地存储_ide