Android-Android数据存储1

Android提供了几种数据存储的方式  我们一般根据存储的数据是否是私有的 数据量大不大 和存储的数据是否结构化

官网给我们的建议是:

Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.

另外 Android还提供了content provider 如果你应用的私有数据真的需要提供给其他应用程序用 你可以通过这个机制来实现


1.Shared Preferences


有两种方式得到它

  • getSharedPreferences() - Use this if you need multiple preferences files identified by name,which you specify with the first parameter.
  • getPreferences() - Use this if you needonly one preferences file for your Activity. Because this will be the only preferences filefor your Activity, you don't supply a name.

第一种需要指定 sharedpreferences的名字和mode 第二种只用一个参数mode


然后得到Editor 通过putBoolean() and putString() 写入数据 最后commit 这个比较简单



2.Internal Storage 内部存储


写入信息:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();


读取信息:

  1. Call openFileInput() and pass it thename of the file to read. This returns a FileInputStream.
  2. Read bytes from the file with read().
  3. Then close the stream with close().

另外:你可以在res/raw/目录下存放一些静态的文件 比如说一些小声音什么的 然后openRawResource() 读取返回InputStream

但是你不能再改变这个文件了 因为他是静态的



3.External Storage


这个更加见到啦 就是保存到SDcard中

首先你得声明权限

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值