android之数据存储基础:

概述

  • Shared Preferences:以键值对的方式存储私有的基本数据类型
  • Internal Storage 保存私有的数据到设备内存储
  • External Storage保存公共数据到共享外部存储如SD卡
  • SQLite Databases保存结构化数据到私有的数据库(ANDROID内置数据库)

Shared Preferences使用

Shared Preferences类供开发人员保存和获取基本数据类型的键值对.该类主要用于基本类型,
例如booleans,floats.ints,longs和strings.在应用程序结束后,数据仍旧会保存.有两种方式可以
获得SharedPreferences对象

  • getSharedPreferences():如果需要多个使用名称来区分的共享文件,则可以使用该方法,其第一
    个参数就是共享文件的名称.对于使用同一个名称获得的多个SharedPreferences引用,其指向
    同一个对象.
  • getPreferences():如果Activty仅需要一个文件,则可以使用该方法.因为只有一个文件,它并不需
    要提供名称

完成SharedPreferences类中使用的步骤如下:

  • 调用SharedPreferences类的edit()方法获得SharedPreferences.Editor引用对象
  • 调用诸如putBoolean(),putString()等方法增加值.
  • 使用commit()方法提交新值.
  • 从SharedPreferences类中取值时,主要使用该类中定义的getXxx()方法.

存储操作模式有:

  • MODE_PRIVATE
  • MODE_APPEND
  • MODE_WORLD_READABLE
  • MODE_WORLD_WRITEABLE

示例代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到控件
mEditText = (EditText) findViewById(R.id.edit);
//如果存在取出数据:
mEditText.setText(loadData());
button=(Button) findViewById(R.id.but);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.but:
//提交并保存数据到xml中
SharedPreferences sharedPreferences=getSharedPreferences(“at22”,MODE_PRIVATE);
Editor edit = sharedPreferences.edit();
edit.putString(“hello”,mEditText.getText().toString());
//一定要事务提交:
edit.commit();
Toast.makeText(this, “toast”, Toast.LENGTH_LONG).show();;
break;
default:
break;
}
}
//在xml中取出数据:
public String loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(“at22”, MODE_PRIVATE);
String string = sharedPreferences.getString(“hello”,”hello>.>….”);
return string;
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}

Internal Storage 使用

Internal Storage是指直接将文件保存到系统内部存储空间.默认情况下,使用该方法保存的文件
会对当前应用程序可见,对于其它应用程序,是不可见的,如果用户卸载了该应该程序,则保存数据
的文件也会一起被删除
步骤如下

  • 使用文件名和操作模式作为参数调用openFileOutput()方法,该方法会返回一个
    FileOutputStream;
  • 使用 write()方法向文件中写入数据
  • 使用close()方法关闭流

示例代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.but);
editText= (EditText) findViewById(R.id.edt);
button.setOnClickListener(this);
//editText.setText(loadData());
}
//数据的存
public void onClick(View v) {
String conttin = editText.getText().toString();
FileOutputStream openFileOutput = null;
try {
openFileOutput = openFileOutput(“11”, MODE_PRIVATE);
byte[]buffer=conttin.getBytes();
openFileOutput.write(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (openFileOutput!=null) {
try {
openFileOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
openFileOutput=null;
}
}
}
//数据取
public String loadData() {
FileInputStream openFileInput = null;
StringBuffer stringBuffer=new StringBuffer();
try {
openFileInput= openFileInput(“11”);
byte []buff=new byte[1024];
int hasData=-1;
while ((hasData=openFileInput.read(buff))!=-1) {
stringBuffer.append(new String(buff,0,hasData));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (openFileInput!=null) {
try {
openFileInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
openFileInput=null;
}
}
return stringBuffer.toString();
}

External Storage使用

每个Android设备都支持共享的外部储存用来保存文件,这可以是SD卡等可以移除的存储介质,
也可以是手机内存等不可移除的存储介质,保存的名部存储文件都是全局可读的,而且在用户使
用USB连接电脑后,可以修改这些文件
Environment类
Environment 是一个提供访问环境变量的类。
Environment 包含常量:

  • MEDIA_BAD_REMOVAL
    解释:返回getExternalStorageState() ,表明SDCard 被卸载前己被移除

  • MEDIA_CHECKING
    解释:返回getExternalStorageState() ,表明对象正在磁盘检查。

  • MEDIA_MOUNTED
    解释:返回getExternalStorageState() ,表明对象是否存在并具有读/写权限

  • MEDIA_MOUNTED_READ_ONLY
    解释:返回getExternalStorageState() ,表明对象权限为只读

  • MEDIA_NOFS14.
    解释:返回getExternalStorageState() ,表明对象为空白或正在使用不受支持的文件系
    统。

  • MEDIA_REMOVED
    解释:返回getExternalStorageState() ,如果不存在 SDCard 返回

  • MEDIA_SHARED
    解释:返回getExternalStorageState() ,如果 SDCard 未安装 ,并通过 USB 大容量
    存储共享 返回

  • MEDIA_UNMOUNTABLE
    解释:返回getExternalStorageState() ,返回 SDCard 不可被安装 如果 SDCard 是
    存在但不可以被安装

  • MEDIA_UNMOUNTED
    解释:返回getExternalStorageState() ,返回 SDCard 已卸掉如果 SDCard 是存在
    但是没有被安装

Environment 常用方法:

  • 方法:getDataDirectory()
    解释:返回 File ,获取 Android 数据目录。

  • 方法:getDownloadCacheDirectory()
    解释:返回 File ,获取 Android 下载/缓存内容目录。

  • 方法:getExternalStorageDirectory()
    解释:返回 File ,获取外部存储目录即 SDCard

  • 方法:getExternalStoragePublicDirectory(String type)
    解释:返回 File ,取一个高端的公用的外部存储器目录来摆放某些类型的文件

  • 方法:getExternalStorageState()
    解释:返回 File ,获取外部存储设备的当前状态

  • 方法:getRootDirectory()
    解释:返回 File ,获取 Android 的根目录

示例代码:

Button button;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_main);
button = (Button) findViewById(R.id.but);
editText= (EditText) findViewById(R.id.edt);
button.setOnClickListener(this);
editText.setText(loadData());
}
//数据存
@Override
public void onClick(View v) {
String conttin = editText.getText().toString();
FileOutputStream openFileOutput = null;
try {
openFileOutput = new FileOutputStream(new File(Environment.getExternalStorageDirectory(),”hello”));
byte[]buffer=conttin.getBytes();
openFileOutput.write(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (openFileOutput!=null) {
try {
openFileOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
openFileOutput=null;
}
}
}
//数据取:
public String loadData() {
FileInputStream openFileInput = null;
StringBuffer stringBuffer=new StringBuffer();
try {
openFileInput=new FileInputStream(new File(Environment.getExternalStorageDirectory(),”hello”));
byte []buff=new byte[1024];
int hasData=-1;
while ((hasData=openFileInput.read(buff))!=-1) {
stringBuffer.append(new String(buff,0,hasData));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (openFileInput!=null) {
try {
openFileInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
openFileInput=null;
}
}
return stringBuffer.toString();
}

SQLite Databases使用

对于更加复杂的数据结构, android提供了内置的SQLite数据库来存储数据.SQLite使用SQL命
令提供了完整的关系型数据库能力,每个使用SQLite的应用程序都有一个该数据库的实例,并且在默认情况下公限当前应用使用,数据库存存储在android设置
的 /data/data//databases 文件夹中.使用SQLite数据库的步骤如下:

  • 创建数据库
  • 打开数据加
  • 创建表
  • 完成数据库的增删改查操作
  • 关闭数据库
    不在贴示例代码:网上有很多框架:

Android使用序列化接口

序列化原因
序列化的原因基本可以归纳为以下三种情况:

  • 永久性保存对象,保存对象的字节序列到本地文件中;
  • 对象在网络中传递;
  • 对象在IPC间传递。

序列化方法

在Android系统中关于序列化的方法一般有两种,分别是实现Serializable接口和Parcelable接
口,其中Serializable接口是来自Java中的序列化接口,而Parcelable是Android自带的序列化
接口。
上述的两种序列化接口都有各自不同的优缺点,我们在实际使用时需根据不同情况而定。
Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC,而相比之下
Parcelable的性能更高(毕竟是Android自带的),所以当在使用内存时(如:序列化对象在网
络中传递对象或序列化在进程间传递对象),更推荐使用Parcelable接口。
但Parcelable有个明显的缺点:不能能使用在要将数据存储在磁盘上的情况(如:永久性保
存对象,保存对象的字节序列到本地文件中),因为Parcel本质上为了更好的实现对象在
IPC间传递,并不是一个通用的序列化机制,当改变任何Parcel中数据的底层实现都可能导
致之前的数据不可读取,所以此时还是建议使用Serializable 。Serializable接口
Serializable的接口实现很简单,只需让需要序列化的类继承Serializable 即可,系统会自动将
其序列化。存储时使用FileOutputStream构造一个ObjectOutputStream,使用writeObject
存储对象。读取时使用FileInputStream构造一个ObjectInputStream,使用readObject读取
对象。

Parcelable接口

实现Parcelable接口主要可以分为一下几步:

  • 让Model实现Parcelable接口
  • 重写writeToParcel方法,将你的对象序列化为一个Parcel对象,即:将类的数据写入外部
    提供的Parcel中,打包需要传递的数据到Parcel容器保存,以便从Parcel容器获取数据。
  • 重写describeContents方法,内容接口描述,默认返回0即可。
    实例化静态内部对象CREATOR实现接口Parcelable.Creator,并重写读取的抽象方法。

注意:若将Parcel看成是一个流,则先通过writeToParcel把对象写到流里面,再通过
createFromParcel从流里读取对象,因此类实现的写入顺序和读出顺序必须一致。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值