android数据持久化方法

本文介绍了Android中四种数据持久化的方法:使用SharedPreferences进行简单的数据存储;利用FileInputStream和FileOutputStream进行文件读写;采用SQLite数据库处理较大数据量;以及通过ContentProvider实现跨应用数据共享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android数据持久化方法:
第一种,最简单的方式,使用SharedPreferences
 1.getPreferences (int mode)
     通过Activity对象获取,获取的是本Activity私有的Preference,保存路径为/data/data/com.example.testandroid/shared_prefs,其中包名以自己实际的为准,保存为activity.xml,其中activity为本Activity名称。因此一个Activity只能有一个,属于这个Activity。

2.getSharedPreferences (String name, int mode)
    因为Activity继承了ContextWrapper,因此也是通过Activity对象获取,但是属于整个应用程序,可以有多个,保存为name.xml。

3.PreferenceManager.getDefaultSharedPreferences(this);
    PreferenceManager的静态函数,保存PreferenceActivity中的设置,属于整个应用程序,但是只有一个,Android会根据包名和PreferenceActivity的布局文件来起一个名字保存,比如我的为com.example.testandroid_preferences.xml

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sp.edit().putBoolean("key", true).commit();
boolean bFLag = sp.getBoolean("key");

第二种,最熟悉的方式,使用FileInputStream,FileOutputStream,通过文件的读写来实现
public String readFile(String fileName) {
        String res = null;
        try {
            File file = new File(fileName);
            FileInputStream fis = new FileInputStream(file);
            int length = fis.available();
            byte[] buffer = new byte[length];
            fis.read(buffer);
            res = EncodingUtils.getString(buffer, "UTF-8");
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return res;
    }
    
    private void writeFile(String fileName, String strContent) {
        try {
            File file = new File(fileName);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bytes = strContent.getBytes();
            fos.write(bytes);
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

第三种,可以使用SQLite数据库,针对数据量比较大的情况
第四种,可以使用ContentProvider,在不同应用程序之间共享数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值