当前位置: 移动技术网 > IT编程>移动开发>Android > Android开发笔记之Android中数据的存储方式(一)

Android开发笔记之Android中数据的存储方式(一)

2019年07月24日  | 移动技术网IT编程  | 我要评论

沙皇情夫,江苏靖江新港城大学城,关于文明的手抄报

  对于开发平台来讲,如果对数据的存储有良好的支持,那么对应用程序的开发将会有很大的促进作用。

  总体的来讲,数据存储方式有三种:一个是文件,一个是数据库,另一个则是网络。其中文件和数据库可能用的稍多一些,文件用起来较为方便,程序可以自己定义格式;数据库用起稍烦锁一些,但它有它的优点,比如在海量数据时性能优越,有查询功能,可以加密,可以加锁,可以跨应用,跨平台等等;网络,则用于比较重要的事情,比如科研,勘探,航空等实时采集到的数据需要马上通过网络传输到数据处理中心进行存储并进行处理,有实时性的需求等。

  对于android平台来讲,它的存储方式也不外乎这几种,按方式总体来分,也是文件,数据库和网络。但我认为从储存标的来讲它可以细分为以下五种方式:

1.1 方式

1.shared preferences:主要用于保存程序的系统配置信息。用来存储“key-values paires”。一般用于保存程序启动时设定的信息,以便在程序下一次启动时继续保留前一次设定的信息。
2.xml:保存复杂数据,比如短信备份。

3.files:用文件的形式保存信息。可以通过对文件的读写来获取或保存相关信息。

4.sqlite:用数据库的形式保存信息。sqlite是一个开源的数据库 系统。

5.network:将数据保存于网络。

1.2 区别

  1. shared preferences:

  android提供用来存储一些简单的配置信息的一种机制,例如,一些默认欢迎语、登录的用户名和密码等。其以键值对的方式存储。

  sharedpreferences是以xml的格式以文件的方式自动保存的,在ddms中的file explorer中展开到/data/data/<packagename>/shared_prefs下,以自己的项目为例,可以看到一个叫做setting_infos.xml的文件

  2. files

  在android中,其提供了openfileinput 和 openfileouput 方法读取设备上的文件,下面看个例子代码,具体如下所示:

string file_name = "tempfile.tmp"; //确定要操作文件的文件名
fileoutputstream fos = openfileoutput(file_name, context.mode_private); //初始化
fileinputstream fis = openfileinput(file_name); //创建写入流 

  上述代码中两个方法只支持读取该应用目录下的文件,读取非其自身目录下的文件将会抛出异常。需要提醒的是,如果调用fileoutputstream 时指定的文件不存在,android 会自动创建它,所以不需要判断文件是否存在。另外,在默认情况下,写入的时候会覆盖原文件内容,如果想把新写入的内容附加到原文件内容后,则可以指定其模式为context.mode_append,这里涉及到openfileoutput()的四种模式,下文我会详细解释和案例。

  3. sqlite

  sqlite是android所带的一个标准的数据库,它支持sql语句,它是一个轻量级的嵌入式数据库

  4. network:

  将数据上传到网络

补充:

1.shared preferences底层使用xml,xml也可以保存数据,但是shared preferences只能保存键值对方式,xml能保存复杂数据

2.content provider底部还是使用了sqlite数据库,也是算一种方式。

1.3 例子

1. shared preferences:

小案例:用户输入账号密码,点击登录按钮,登录的同时持久化保存账号和密码

用sharedpreference存储账号密码

•往sharedpreference里写数据

//拿到一个sharedpreference对象
sharedpreferences sp = getsharedpreferences("config", mode_private);
//拿到编辑器
editor ed = sp.edit();
//写数据
ed.putstring("name", name);
ed.commit(); 

注:这里记住put完后,必须commit一下。

•从sharedpreference里取数据

sharedpreferences sp = getsharedpreferences("config", mode_private);
//从sharedpreference里取数据
string name = sp.getboolean("name", ""); 

•代码:

•布局文件

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingbottom="@dimen/activity_vertical_margin"
android:paddingleft="@dimen/activity_horizontal_margin"
android:paddingright="@dimen/activity_horizontal_margin"
android:paddingtop="@dimen/activity_vertical_margin"
tools:context=".mainactivity" 
android:orientation="vertical"
>
<edittext
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名" 
/>
<edittext
android:id="@+id/et_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码" 
android:inputtype="textpassword" 
/>
<relativelayout 
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<checkbox 
android:id="@+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住用户名和密码"
android:layout_centervertical="true"
/>
<button 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:layout_alignparentright="true"
android:onclick="login"
/>
</relativelayout>
</linearlayout> 

•java代码  

package com.bokeyuan.sharedpreference;
import android.os.bundle;
import android.app.activity;
import android.content.sharedpreferences;
import android.content.sharedpreferences.editor;
import android.view.menu;
import android.view.view;
import android.widget.edittext;
public class mainactivity extends activity {
private edittext et_name;
private edittext et_pass;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
et_name = (edittext) findviewbyid(r.id.et_name);
et_pass = (edittext) findviewbyid(r.id.et_pass);
//拿到sharedpreferences对象
sharedpreferences sp = getsharedpreferences("info", mode_private);
//从sharedpreferences中取出数据
string name = sp.getstring("name", "");
string pass = sp.getstring("pass", "");
et_name.settext(name);
et_pass.settext(pass);
}
public void login(view v){
string name = et_name.gettext().tostring();
string pass = et_pass.gettext().tostring();
//拿到sharedpreferences对象
sharedpreferences sp = getsharedpreferences("info", mode_private);
//把数据存入sharedpreferences
editor ed = sp.edit();
ed.putstring("name", name);
ed.putstring("pass", pass);
//提交
ed.commit();
}
} 

 2. files  

 小案例:用户输入账号密码,勾选“记住账号密码”,点击登录按钮,登录的同时持久化保存账号和密码

•在内部存储空间中读写文件(ram)

•布局文件:同上面的布局

•java代码:  

package com.bokeyuan.rwinrom;
import java.io.bufferedreader;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.inputstreamreader;
import android.os.bundle;
import android.annotation.suppresslint;
import android.app.activity;
import android.content.context;
import android.view.menu;
import android.view.view;
import android.widget.checkbox;
import android.widget.edittext;
import android.widget.toast;
public class mainactivity extends activity {
private edittext et_name;
private edittext et_pass;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
et_name = (edittext) findviewbyid(r.id.et_name);
et_pass = (edittext) findviewbyid(r.id.et_pass);
readaccount();
}
@suppresslint("showtoast") public void login(view v){
string name = et_name.gettext().tostring();
string pass = et_pass.gettext().tostring();
checkbox cb = (checkbox) findviewbyid(r.id.cb);
if(cb.ischecked()){
//指定android的内部存储空间的路径
// file file = new file("data/data/com.bokeyuan.rwinrom/info.txt");
//返回一个file对象,它的路径是:data/data/com.bokeyuan.rwinrom/files/
// file file = new file(getfilesdir(), "info.txt");
//返回一个file对象,它的路径是:data/data/com.bokeyuan.rwinrom/cache/
file file = new file(getcachedir(), "info.txt");
try {
fileoutputstream fos = new fileoutputstream(file);
fos.write((name + "##" + pass).getbytes());
fos.close();
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
//弹出提示框,提示用户登录成功
toast.maketext(this, "登陆成功", 0).show();
}
public void readaccount(){
//指定android的内部存储空间的路径
// file file = new file("data/data/com.bokeyuan.rwinrom/info.txt");
// file file = new file(getfilesdir(), "info.txt");
file file = new file(getcachedir(), "info.txt");
if(file.exists()){
try {
fileinputstream fis = new fileinputstream(file);
//把字节流转换成字符流
bufferedreader br = new bufferedreader(new inputstreamreader(fis));
string text = br.readline();
string[] s = text.split("##");
et_name.settext(s[0]);
et_pass.settext(s[1]);
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
}

•在外部存储空间中读写文件(sd卡)

•布局文件:同上面的布局

•java代码:

package com.bokeyuan.rwinsd;
import java.io.bufferedreader;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.inputstreamreader;
import com.bokeyuan.rwinsd.r;
import android.os.bundle;
import android.os.environment;
import android.annotation.suppresslint;
import android.app.activity;
import android.content.context;
import android.view.menu;
import android.view.view;
import android.widget.checkbox;
import android.widget.edittext;
import android.widget.toast;
public class mainactivity extends activity {
private edittext et_name;
private edittext et_pass;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
et_name = (edittext) findviewbyid(r.id.et_name);
et_pass = (edittext) findviewbyid(r.id.et_pass);
readaccount();
}
public void login(view v){
string name = et_name.gettext().tostring();
string pass = et_pass.gettext().tostring();
checkbox cb = (checkbox) findviewbyid(r.id.cb);
if(cb.ischecked()){
//检测sd卡当前是否可用
if(environment.getexternalstoragestate().equals(environment.media_mounted)){
// file file = new file("sdcard/info.txt");
//返回一个file对象,包含的路径就是sd卡的真实路径
file file = new file(environment.getexternalstoragedirectory(), "info.txt");
try {
fileoutputstream fos = new fileoutputstream(file);
fos.write((name + "##" + pass).getbytes());
fos.close();
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
else{
toast.maketext(this, "sd卡不可用哟亲", 0).show();
}
}
//弹出提示框,提示用户登录成功
toast.maketext(this, "登陆成功", 0).show();
}
public void readaccount(){
// file file = new file("sdcard/info.txt");
file file = new file(environment.getexternalstoragedirectory(), "info.txt");
if(file.exists()){
try {
fileinputstream fis = new fileinputstream(file);
//把字节流转换成字符流
bufferedreader br = new bufferedreader(new inputstreamreader(fis));
string text = br.readline();
string[] s = text.split("##");
et_name.settext(s[0]);
et_pass.settext(s[1]);
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
} 

注:

•//此api会把文件写到data/data/com.itheima.permission/files/文件夹下
•fileoutputstream fos = openfileoutput("info1.txt", mode_private) ;
•//此api会把文件读到data/data/com.itheima.permission/files/文件夹下
•fileoutputstream fos = openfileoutput("info1.txt", mode_private) ;

•所以,以后用android 自带的api。可以看下面openfileoutput四种模式的小例子:

•openfileoutput的四种模式

•mode_private = 0:       -rw-rw----
•mode_append = 32768:    -rw-rw----
•modeworldreadable = 1: -rw-rw-r--
•modeworldwriteable = 2: -rw-rw--w-

context.mode_private:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中,可以使用context.mode_append。

context.mode_append:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
context.mode_world_readable和context.mode_world_writeable用来控制其他应用是否有权限读写该文件。
mode_world_readable:表示当前文件可以被其他应用读取;mode_world_writeable:表示当前文件可以被其他应用写入。

• 注:

•在android中,每一个应用是一个独立的用户
•drwxrwxrwx
•第1位:d表示文件夹,-表示文件
•第2-4位:rwx,表示这个文件的拥有者用户(owner)对该文件的权限 •r:读
•w:写
•x:执行
•第5-7位:rwx,表示跟文件拥有者用户同组的用户(grouper)对该文件的权限
•第8-10位:rwx,表示其他用户组的用户(other)对该文件的权限

•布局文件:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingbottom="@dimen/activity_vertical_margin"
android:paddingleft="@dimen/activity_horizontal_margin"
android:paddingright="@dimen/activity_horizontal_margin"
android:paddingtop="@dimen/activity_vertical_margin"
tools:context=".mainactivity" 
android:orientation="vertical"
>
<button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="创建文件1" 
android:onclick="click1"
/>
<button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="创建文件2" 
android:onclick="click2"
/>
<button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="创建文件3" 
android:onclick="click3"
/>
</linearlayout> 

•代码:

package com.bokeyuan.permission;
import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import android.os.bundle;
import android.annotation.suppresslint;
import android.app.activity;
import android.view.menu;
import android.view.view;
@suppresslint("worldreadablefiles")
public class mainactivity extends activity {
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
}
public void click1(view v){
//此api会把文件写到data/data/com.bokeyuan.permission/files/文件夹下
try {
fileoutputstream fos = openfileoutput("info1.txt", mode_private) ;
fos.write("该文件是私有数据,只能被应用本身访问".getbytes());
fos.close();
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
public void click2(view v){
//此api会把文件写到data/data/com.bokeyuan.permission/files/文件夹下
try {
@suppresswarnings("deprecation")
fileoutputstream fos = openfileoutput("info2.txt", mode_world_readable | mode_world_writeable) ;
fos.write("当前文件可以被其他应用读取或写入".getbytes());
fos.close();
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
public void click3(view v){
//此api会把文件写到data/data/com.bokeyuan.permission/files/文件夹下
try {
@suppresswarnings("deprecation")
fileoutputstream fos = openfileoutput("info3.txt", mode_world_writeable) ;
fos.write("当前文件可以被其他应用写入".getbytes());
fos.close();
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
} 

•获取sd卡剩余容量:

•有时候读写文件的时候,需要判断sd卡的剩余容量,再进行写入操作。下面小例子,引用android系统底层的api,获取sd卡的剩余容量。

•布局文件:

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingbottom="@dimen/activity_vertical_margin"
android:paddingleft="@dimen/activity_horizontal_margin"
android:paddingright="@dimen/activity_horizontal_margin"
android:paddingtop="@dimen/activity_vertical_margin"
tools:context=".mainactivity" >
<textview
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</relativelayout> 

•java代码:

package com.bokeyuan.getsdavail;
import java.io.file;
import android.os.build;
import android.os.bundle;
import android.os.environment;
import android.os.statfs;
import android.app.activity;
import android.text.format.formatter;
import android.view.menu;
import android.widget.textview;
public class mainactivity extends activity {
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
file path = environment.getexternalstoragedirectory();
statfs stat = new statfs(path.getpath());
long blocksize;
long totalblocks;
long availableblocks; 
//检测系统当前版本号
if(build.version.sdk_int >= build.version_codes.jelly_bean_mr2){
blocksize = stat.getblocksizelong();
totalblocks = stat.getblockcountlong();
availableblocks = stat.getavailableblockslong();
}
else{
blocksize = stat.getblocksize();
totalblocks = stat.getblockcount();
availableblocks = stat.getavailableblocks();
} 
textview tv = (textview) findviewbyid(r.id.tv);
tv.settext(formatsize(availableblocks * blocksize));
}
private string formatsize(long size) {
return formatter.formatfilesize(this, size);
}
}

以上所述给大家介绍了android开发笔记之android中数据的存储方式(一)的相关知识,希望本文分享能够帮助到大家。下篇给感兴趣的朋友点击了解详情。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网