Android App中各种数据保存方式的使用实例总结
少量数据保存之SharedPreferences接口实例
SharedPreferences数据保存主要是通过键值的方式存储在xml文件中
xml文件在data/此程序的包名/XX.xml。
格式:
<?xmlversion='1.0'encoding='utf-8'standalone='yes'?> <map> <intname="count"value="3"/> <stringname="time">写入日期:2013年10月07日,时间:11:28:09</string> </map>
SharedPreferences读写的基本步骤:
读:
1.通过Context的getSharedPreferences获取SharedPreferences接口的对象share:SharedPreferencesshare=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访问类型
其余的就和上面的步骤差不多就不再概叙
实例
<LinearLayoutxmlns: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>
packagecom.android.xiong.sharepreferencestest;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importandroid.app.Activity;
importandroid.content.Context;
importandroid.content.SharedPreferences;
importandroid.content.SharedPreferences.Editor;
importandroid.os.Bundle;
importandroid.view.Menu;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.TextView;
publicclassMainActivityextendsActivity{
privateButtonwrite;
privateButtonread;
privateTextViewtxt1;
privateTextViewcountTxt;
SharedPreferencesshare;
Editoreditor;
intcountO=0;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
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+"次");
OnClickListenerwriteListener=newOnClickListener(){
@Override
publicvoidonClick(Viewv){
//TODOAuto-generatedmethodstub
SimpleDateFormatdata=newSimpleDateFormat(
"写入日期:yyyy年MM月dd日,时间:hh:mm:ss");
editor.putString("time",
data.format(newDate()));
editor.commit();
}
};
OnClickListenerreadListener=newOnClickListener(){
@Override
publicvoidonClick(Viewv){
//TODOAuto-generatedmethodstub
if(!share.contains("share")){
txt1.setText(share.getString("time",null));
}
}
};
write.setOnClickListener(writeListener);
read.setOnClickListener(readListener);
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}
机身内存数据读写(InternalStorage)
1.机身内存读取主要用个两个类文件输入流(FileInputStream)和文件输出流(FileOutputStream):FileInputStreamfileInput=this.openFileInput("test.txt")第一个参数为data/此程序包名/data/test.txt文件下的文件名;
FileOutputStreamfileOut=this.openFileOutput("test.txt",this.MODE_APPEND)第一个参数表示文件名第二个参数表示打开的方式
2.获取了文件输入输出流之后其后的文件的读写和基本的IO操作一样
机身内存数据读写实例
<LinearLayoutxmlns: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>
packagecom.android.xiong.fileiotest;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.InputStreamReader;
importjava.lang.reflect.Array;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.Menu;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.EditText;
publicclassMainActivityextendsActivity{
privateButtonread;
privateButtonwrite;
privateEditTexted1;
privateEditTexted2;
privateEditTexted3;
privateButtondelete;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
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(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Stringstr=ed1.getText().toString();
if(!str.equals("")){
write(str);
}
}
});
read.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
read();
}
});
delete.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
Stringstr=ed3.getText().toString();
if(!str.equals("")){
deleteFiles(str);
}else{
ed3.setText(str+":该文件输入错误或不存在!");
}
}
});
}
privatevoidwrite(Stringcontent){
try{
//以追加的方式打开文件输出流
FileOutputStreamfileOut=this.openFileOutput("test.txt",
this.MODE_APPEND);
//写入数据
fileOut.write(content.getBytes());
//关闭文件输出流
fileOut.close();
}catch(Exceptione){
e.printStackTrace();
}
}
privatevoidread(){
try{
ed2.setText("");
//打开文件输入流
FileInputStreamfileInput=this.openFileInput("test.txt");
BufferedReaderbr=newBufferedReader(newInputStreamReader(
fileInput));
Stringstr=null;
StringBuilderstb=newStringBuilder();
while((str=br.readLine())!=null){
stb.append(str);
}
ed2.setText(stb);
}catch(Exceptione){
e.printStackTrace();
}
}
//删除指定的文件
privatevoiddeleteFiles(StringfileName){
try{
//获取data文件中的所有文件列表
List<String>name=Arrays.asList(this.fileList());
if(name.contains(fileName)){
this.deleteFile(fileName);
ed3.setText(fileName+":该文件成功删除!");
}else
ed3.setText(fileName+":该文件输入错误或不存在!");
}catch(Exceptione){
e.printStackTrace();
}
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}
SDcard(ExternalStorage)读写数据实例
1.SDcard数据读写需要注定的先要在Androidmainfest.xml文件中注册新建删除和读写的权限:
<!--在SD卡上创建与删除权限--> <uses-permissionAndroid:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/> <!--向SD卡上写入权限--> <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.读写的基本流程就是:
2.1通过Environment类的getExternalStorageState()方法来判断手机是否有SDcard:
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
2.2最通过getExternalStorageDirectory()方法来获取文件目录:
Filefile=newFile(Environment.getExternalStorageDirectory().getCanonicalPath()+"/test.txt");