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");

读写的文件都在sdcrad文件夹中 通过File Explorer可以导出来
2.3 其后就和基本IO操作相同了
2.4还有要注意一点的是 在运行的模拟器的时候要附带虚拟的SDcard时  要在Run as->Run Configurations 中要关联一下 如下图
SDcard数据读写实例
<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中的查询规划器

c#操作Sqlite实现数据的增删改查

python之sqlalchemy创建表的实例详解

androidstudio数据存储建立Sqlite数据库实现增删查改

android开发中的数据库事务用法分析

Sqlite教程(五):索引和数据分析清理

python执行数据库的查询操作实例讲解

python 操作Sqlite数据库的示例

Sqlite5-使用python来读写数据库

python使用sqlalchemy操作mysql

更多相关阅读请进入《Sqlite》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...