Android App中各种数据保存方式的使用实例总结
少量数据保存之sharedpreferences接口实例
sharedpreferences数据保存主要是通过键值的方式存储在xml文件中
xml文件在data/此程序的包名/xx.xml。
格式:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <int name="count" value="3" /> <string name="time">写入日期:2013年10月07日,时间:11:28:09</string> </map>
sharedpreferences读写的基本步骤:
读:
1.通过context的getsharedpreferences获取sharedpreferences接口的对象share:sharedpreferences share = this.getsharedpreferences("share",context.mode_private);
"shre"保存的xml文件名 ,context.mode_private 保存的类型为只被本程序访问 (还有mode_world_readable表示其余的程序能够读不能写,mode
_world_writeble能读写 这两个都在api17的时候被废了)
2.通过share的getxxx的方法获取指定key的值 : share.getint("count", 0);
写:
1.通过sharedpreferences对象的edit()方法获取edit对象:edit editor = share.edit();
2.通过editor对象的putxxx方法来写入值 :editor.putint("count", 1);
3.调用editor的commit()方法提交修改值 :editor.commit();
访问其他程序的sharedpreferences
访问其他程序的sharedpreferences 的读写唯一不同的是先的获取该程序的context接口对象:this.createpackagecontext(packagename, flags)
packagename为要该目标程序的包名,flags访问类型
其余的就和上面的步骤差不多 就不再概叙
实例
<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:orientation="vertical" tools:context=".mainactivity" > <button android:id="@+id/write" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="写入数据" /> <button android:id="@+id/read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="读入数据" /> <textview android:id="@+id/txtcount" android:layout_width="match_parent" android:layout_height="wrap_content"/> <textview android:id="@+id/txt1" android:layout_width="match_parent" android:layout_height="wrap_content" /> </linearlayout>
package com.android.xiong.sharepreferencestest; import java.text.simpledateformat; import java.util.date; import android.app.activity; import android.content.context; import android.content.sharedpreferences; import android.content.sharedpreferences.editor; import android.os.bundle; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.textview; public class mainactivity extends activity { private button write; private button read; private textview txt1; private textview counttxt; sharedpreferences share ; editor editor; int counto=0; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //获取sharedpreferences对象 share = this.getsharedpreferences("share", context.mode_private); //获取editor对象 editor = share.edit(); write = (button) findviewbyid(r.id.write); read = (button) findviewbyid(r.id.read); txt1 = (textview) findviewbyid(r.id.txt1); counttxt=(textview)findviewbyid(r.id.txtcount); //获取share中key为count的值 counto=share.getint("count", 0); counto++; //修改share中key为count的值 editor.putint("count", counto); //提交修改 editor.commit(); system.out.println("该应用程序使用了:"+counto+"次"); counttxt.settext("该应用程序使用了:"+counto+"次"); onclicklistener writelistener = new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub simpledateformat data = new simpledateformat( "写入日期:yyyy年mm月dd日,时间:hh:mm:ss"); editor.putstring("time", data.format(new date())); editor.commit(); } }; onclicklistener readlistener=new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub if(!share.contains("share")){ txt1.settext(share.getstring("time", null)); } } }; write.setonclicklistener(writelistener); read.setonclicklistener(readlistener); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; } }
机身内存数据读写(internal storage)
1.机身内存读取主要用个两个类文件输入流(fileinputstream)和文件输出流(fileoutputstream): fileinputstream fileinput = this.openfileinput("test.txt") 第一个参数为 data/此程序包名/data/test.txt 文件下 的文件名 ;
fileoutputstream fileout = this.openfileoutput("test.txt",this.mode_append)第一个参数表示文件名 第二个参数表示打开的方式
2.获取了文件输入输出流之后 其后的文件的读写和基本的io操作一样
机身内存数据读写实例
<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:layout_gravity="center_horizontal" android:orientation="vertical" tools:context=".mainactivity" > <edittext android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/ed1" android:inputtype="textmultiline"/> <button android:id="@+id/write" android:text="写入" android:layout_width="match_parent" android:layout_height="wrap_content"/> <button android:id="@+id/read" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="读入"/> <edittext android:id="@+id/ed2" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputtype="textmultiline"/> <button android:id="@+id/delete" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="删除指定的文件" /> <edittext android:id="@+id/ed3" android:layout_width="match_parent" android:layout_height="wrap_content" /> </linearlayout>
package com.android.xiong.fileiotest; import java.io.bufferedreader; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.inputstreamreader; import java.lang.reflect.array; import java.util.arraylist; import java.util.arrays; import java.util.list; import android.app.activity; import android.os.bundle; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; public class mainactivity extends activity { private button read; private button write; private edittext ed1; private edittext ed2; private edittext ed3; private button delete; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); read = (button) findviewbyid(r.id.read); write = (button) findviewbyid(r.id.write); delete = (button) findviewbyid(r.id.delete); ed3 = (edittext) findviewbyid(r.id.ed3); ed2 = (edittext) findviewbyid(r.id.ed2); ed1 = (edittext) findviewbyid(r.id.ed1); write.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { string str = ed1.gettext().tostring(); if (!str.equals("")) { write(str); } } }); read.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { read(); } }); delete.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { string str = ed3.gettext().tostring(); if (!str.equals("")) { deletefiles(str); } else { ed3.settext(str + ":该文件输入错误或不存在!"); } } }); } private void write(string content) { try { // 以追加的方式打开文件输出流 fileoutputstream fileout = this.openfileoutput("test.txt", this.mode_append); // 写入数据 fileout.write(content.getbytes()); // 关闭文件输出流 fileout.close(); } catch (exception e) { e.printstacktrace(); } } private void read() { try { ed2.settext(""); // 打开文件输入流 fileinputstream fileinput = this.openfileinput("test.txt"); bufferedreader br = new bufferedreader(new inputstreamreader( fileinput)); string str = null; stringbuilder stb = new stringbuilder(); while ((str = br.readline()) !=null ) { stb.append(str); } ed2.settext(stb); } catch (exception e) { e.printstacktrace(); } } //删除指定的文件 private void deletefiles(string filename) { try { // 获取data文件中的所有文件列表 list<string> name = arrays.aslist(this.filelist()); if (name.contains(filename)) { this.deletefile(filename); ed3.settext(filename + ":该文件成功删除!"); } else ed3.settext(filename + ":该文件输入错误或不存在!"); } catch (exception e) { e.printstacktrace(); } } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; } }
sdcard(external storage)读写数据实例
1.sdcard数据读写需要注定的先要在androidmainfest.xml文件中注册新建删除和读写的权限 :
<!-- 在sd卡上创建与删除权限 --> <uses-permission android:name="android.permission.mount_format_filesystems" /> <!-- 向sd卡上写入权限 --> <uses-permission android:name="android.permission.write_external_storage" />
2.读写的基本流程就是:
2.1 通过environment类的getexternalstoragestate()方法来判断手机是否有sdcard:
environment.getexternalstoragestate().equals(environment.media_mounted)
2.2 最通过getexternalstoragedirectory()方法来获取文件目录:
file file = new file(environment.getexternalstoragedirectory().getcanonicalpath() + "/test.txt");
2.3 其后就和基本io操作相同了
2.4还有要注意一点的是 在运行的模拟器的时候要附带虚拟的sdcard时 要在run as->run configurations 中要关联一下 如下图
<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:gravity="center_horizontal" android:orientation="vertical" tools:context=".mainactivity" > <edittext android:id="@+id/ed1" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputtype="textmultiline"/> <button android:id="@+id/write" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="写入sd卡中"/> <button android:id="@+id/read" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="读取sd文件"/> <textview android:id="@+id/txt1" android:layout_width="match_parent" android:layout_height="wrap_content"/> </linearlayout>
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.xiong.sdcardtest" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="14" android:targetsdkversion="17" /> <!-- 在sd卡上创建与删除权限 --> <uses-permission android:name="android.permission.mount_format_filesystems" /> <!-- 向sd卡上写入权限 --> <uses-permission android:name="android.permission.write_external_storage" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="com.android.xiong.sdcardtest.mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest>
package com.android.xiong.sdcardtest; import java.io.bufferedreader; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.inputstreamreader; import android.app.activity; import android.os.bundle; import android.os.environment; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.textview; public class mainactivity extends activity { private button write; private button read; private edittext ed1; private textview txt1; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); write = (button) findviewbyid(r.id.write); read = (button) findviewbyid(r.id.read); ed1 = (edittext) findviewbyid(r.id.ed1); txt1 = (textview) findviewbyid(r.id.txt1); write.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub writesdcard(ed1.gettext().tostring()); } }); read.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub txt1.settext(readsdcard()); } }); } // 把数据写入sd卡 private void writesdcard(string str) { try { // 判断是否存在sd卡 if (environment.getexternalstoragestate().equals( environment.media_mounted)) { // 获取sd卡的目录 file file = environment.getexternalstoragedirectory(); fileoutputstream filew = new fileoutputstream(file.getcanonicalpath() + "/test.txt"); filew.write(str.getbytes()); filew.close(); } } catch (exception e) { e.printstacktrace(); } } // 从sd卡中读取数据 private string readsdcard() { stringbuffer str = new stringbuffer(); try { // 判断是否存在sd if (environment.getexternalstoragestate().equals( environment.media_mounted)) { file file = new file(environment.getexternalstoragedirectory() .getcanonicalpath() + "/test.txt"); // 判断是否存在该文件 if (file.exists()) { // 打开文件输入流 fileinputstream filer = new fileinputstream(file); bufferedreader reads = new bufferedreader( new inputstreamreader(filer)); string st = null; while ((st =reads.readline())!=null ) { str.append(st); } filer.close(); } else { txt1.settext("该目录下文件不存在"); } } } catch (exception e) { e.printstacktrace(); } return str.tostring(); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; } }
sqlite简介和简单的登录与注册源代码
1.获取sqlitedatabase对象db创建数据库或连接数据库:sqlitedatabasedb = sqlitedatabase.openorcreatedatabase(mainactivity.this.getfilesdir().tostring()+ "/test.dbs", null);如果目录下有test.dbs数据库则是连接没有就是创建
2.用对象db的方法来执行sql语句:db.execsql(string sql) 此方法木有返回值 所以查询不好弄。查询一般用db.rawquery返回一个cursor对象(相当与jdbc中的resultset),cursor有如下几个方法来查询数据:
2.1 move tofirst 将记录指针跳到第一行
2.2 movetolast将记录指针跳到最后一行
2.3 movenext将记录指针移到下一行
2.4movetoposition( int ss)将记录指针跳到指定的ss行
2.5movetoprevious将记录指针跳到上一行
将记录指针跳到指定的行之后就可以通过对象的getxxx方法来获取数据 :如 cursor cursor = db.rawquery("select na,pw from user where na=? and pw=?", new string []{name,pwd});
3.回收资源close
当然以sqlitedatabase对象还可以调用许多方法来操作数据库,不过俺是觉得这几个方法基本够了
简单的登录与注册源代码:
(仅此来练习sqlite的操作 一般注册的信息都样上传到服务器而不会是存储在手机数据库)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.xiong.sqlitelogin" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="14" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="com.android.xiong.sqlitelogin.mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name="com.android.xiong.sqlitelogin.registersactivity" android:label="@string/app_name" > </activity> </application> </manifest>
<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" tools:context=".mainactivity" > <textview android:id="@+id/login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="30dp" android:gravity="center_horizontal" android:textcolor="#8a2be2" android:textsize="35dp" android:text="登录界面" /> <textview android:id="@+id/txtname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/login" android:layout_marginright="5dp" android:layout_marginbottom="30dp" android:textsize="28dp" android:text="用户帐号:"/> <edittext android:id="@+id/edname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginbottom="30dp" android:layout_below="@id/login" android:layout_torightof="@id/txtname" android:layout_alignparentright="true" android:hint="请输入用户帐号"/> <textview android:id="@+id/txtpassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/txtname" android:layout_marginright="5dp" android:textsize="28dp" android:text="用户密码:"/> <edittext android:id="@+id/edpassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/edname" android:layout_torightof="@id/txtpassword" android:layout_alignparentright="true" android:inputtype="textpassword" android:hint="请输入用户密码"/> <linearlayout android:layout_below="@id/edpassword" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margintop="30dp" android:gravity="center_horizontal" > <button android:id="@+id/btregister" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginright="20dp" android:text="用户注册"/> <button android:id="@+id/btlogin" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="用户登录"/> </linearlayout> </relativelayout>
<?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <textview android:id="@+id/txt1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="30dp" android:gravity="center_horizontal" android:text="注册界面" android:textcolor="#8a2be2" android:textsize="35dp" /> <textview android:id="@+id/txtname1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/txt1" android:layout_marginbottom="30dp" android:layout_marginright="5dp" android:text="帐号:" android:textsize="28dp" /> <edittext android:id="@+id/edname1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_below="@id/txt1" android:layout_torightof="@id/txtname1" android:layout_marginbottom="30dp" /> <textview android:id="@+id/txtpassword1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/txtname1" android:layout_marginright="5dp" android:text="密码:" android:textsize="28dp" /> <edittext android:id="@+id/edpassword1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:layout_below="@id/edname1" android:layout_torightof="@id/txtpassword1" /> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/edpassword1" android:layout_margintop="30dp" android:gravity="center_horizontal" android:orientation="horizontal" > <button android:id="@+id/btregister1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginright="20dp" android:text="提交数据" /> </linearlayout> </relativelayout>
package com.android.xiong.sqlitelogin; import android.app.activity; import android.app.alertdialog; import android.content.intent; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqliteexception; import android.os.bundle; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; public class mainactivity extends activity { // 帐号和密码 private edittext edname; private edittext edpassword; private button btregister; private button btlogin; // 创建sqlite数据库 public static sqlitedatabase db; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); edname = (edittext) findviewbyid(r.id.edname); edpassword = (edittext) findviewbyid(r.id.edpassword); btregister = (button) findviewbyid(r.id.btregister); btlogin = (button) findviewbyid(r.id.btlogin); db = sqlitedatabase.openorcreatedatabase(mainactivity.this.getfilesdir().tostring() + "/test.dbs", null); // 跳转到注册界面 btregister.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub intent intent = new intent(); intent.setclass(mainactivity.this, registersactivity.class); startactivity(intent); } }); btlogin.setonclicklistener(new loginlistener()); } @override protected void ondestroy() { // todo auto-generated method stub super.ondestroy(); db.close(); } class loginlistener implements onclicklistener { @override public void onclick(view v) { // todo auto-generated method stub string name = edname.gettext().tostring(); string password = edpassword.gettext().tostring(); if (name.equals("") || password.equals("")) { // 弹出消息框 new alertdialog.builder(mainactivity.this).settitle("错误") .setmessage("帐号或密码不能空").setpositivebutton("确定", null) .show(); } else { isuserinfo(name, password); } } // 判断输入的用户是否正确 public boolean isuserinfo(string name, string pwd) { try{ string str="select * from tb_user where name=? and password=?"; cursor cursor = db.rawquery(str, new string []{name,pwd}); if(cursor.getcount()<=0){ new alertdialog.builder(mainactivity.this).settitle("错误") .setmessage("帐号或密码错误!").setpositivebutton("确定", null) .show(); return false; }else{ new alertdialog.builder(mainactivity.this).settitle("正确") .setmessage("成功登录").setpositivebutton("确定", null) .show(); return true; } }catch(sqliteexception e){ createdb(); } return false; } } // 创建数据库和用户表 public void createdb() { db.execsql("create table tb_user( name varchar(30) primary key,password varchar(30))"); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; } }
package com.android.xiong.sqlitelogin; import android.app.activity; import android.app.alertdialog; import android.content.dialoginterface; import android.content.intent; import android.database.sqlite.sqlitedatabase; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; public class registersactivity extends activity { private edittext edname1; private edittext edpassword1; private button btregister1; sqlitedatabase db; @override protected void ondestroy() { // todo auto-generated method stub super.ondestroy(); db.close(); } @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.register); edname1 = (edittext) findviewbyid(r.id.edname1); edpassword1 = (edittext) findviewbyid(r.id.edpassword1); btregister1 = (button) findviewbyid(r.id.btregister1); btregister1.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub string name = edname1.gettext().tostring(); string password = edpassword1.gettext().tostring(); if (!(name.equals("") && password.equals(""))) { if (adduser(name, password)) { dialoginterface.onclicklistener ss = new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { // todo auto-generated method stub // 跳转到登录界面 intent in = new intent(); in.setclass(registersactivity.this, mainactivity.class); startactivity(in); // 销毁当前activity registersactivity.this.ondestroy(); } }; new alertdialog.builder(registersactivity.this) .settitle("注册成功").setmessage("注册成功") .setpositivebutton("确定", ss).show(); } else { new alertdialog.builder(registersactivity.this) .settitle("注册失败").setmessage("注册失败") .setpositivebutton("确定", null); } } else { new alertdialog.builder(registersactivity.this) .settitle("帐号密码不能为空").setmessage("帐号密码不能为空") .setpositivebutton("确定", null); } } }); } // 添加用户 public boolean adduser(string name, string password) { string str = "insert into tb_user values(?,?) "; mainactivity main = new mainactivity(); db = sqlitedatabase.openorcreatedatabase(this.getfilesdir().tostring() + "/test.dbs", null); main.db = db; try { db.execsql(str, new string[] { name, password }); return true; } catch (exception e) { main.createdb(); } return false; } }