Android软件开发之数据的操作详解

来源:互联网 发布:node 高手训练营 编辑:程序博客网 时间:2024/06/06 16:57

Android软件开发之数据的新建 储存 读取 删除

1.使用SharedPreferences处理数据的 新建 储存 读取 删除

SharedPreferences保存后生成的是XML文件,内容是以节点的形势保存在文件中,SharedPreferences类提供了非常丰富的处理数据的方法下面我向大家介绍一下如何使用SharedPreferences来处理数据。

输入须要保存的内容

输入姓名:雨松MOMO
输入号码:15810463139

点击保存成功

保存成功以后,数据被保存到了data路径下 /当前包名 (红框内的包名是我的程序包名) /shared_prefs/main.xml中 , 使用EditPlus 打开保存的内容,我们可以清晰的看到内容是以一个节点一个节点的形式存在XML中。

SharedPreferences类中提供了非常方便方法去保存数据与读取数据大家请看下面的代码片段,一个程序中可以存在多个SharedPreferences保存的XML文件 ,代码中只须要根据不同的XML名称就可以通过方法拿到相应的对象,由于它的批量遍历查找,当然这样的作法肯定没有数据库更方便快捷,所以在开发中处理一些比较小的零碎的数据就可以保存在这里,比如说记录软件中用户设置的音量大小,用户输入的查找信息等等都可以存在SharedPreferences中。

  1. public class SPActivity extends Activity {
  2.     /**使用SharedPreferences 来储存与读取数据**/
  3.     SharedPreferences mShared = null;
  4.     /**程序中可以同时存在多个SharedPreferences数据, 根据SharedPreferences的名称就可以拿到对象**/
  5.     public final static String SHARED_MAIN = “main”;
  6.     /**SharedPreferences中储存数据的Key名称**/
  7.     public final static String KEY_NAME = “name”;
  8.     public final static String KEY_NUMBER = “number”;
  9.     /**SharedPreferences中储存数据的路径**/
  10.     public final static String DATA_URL = “/data/data/”;
  11.     public final static String SHARED_MAIN_XML = “main.xml”;
  12.     @Override
  13.     protected void onCreate(Bundle savedInstanceState) {
  14.         setContentView(R.layout.sharedpreferences);
  15.         /**拿到名称是SHARED_MAIN 的SharedPreferences对象**/
  16.         mShared = getSharedPreferences(SHARED_MAIN, Context.MODE_PRIVATE);
  17.         /**拿到SharedPreferences中保存的数值 第二个参数为如果SharedPreferences中没有保存就赋一个默认值**/
  18.         String name = mShared.getString(KEY_NAME, “数据库中没有储存姓名”);
  19.         String number = mShared.getString(KEY_NUMBER, “数据库中没有储存号码”);
  20.         final EditText editName = (EditText)findViewById(R.id.sp_et0);
  21.         final EditText editNumber = (EditText)findViewById(R.id.sp_et1);
  22.         editName.setHint(“上次输入的姓名为【 ” +name+”】”);
  23.         editNumber.setHint(“上次输入的号码为【 ” +number+”】”);
  24.         Button button0 = (Button)findViewById(R.id.sp_button0);
  25.         /**监听按钮点击后保存用户输入信息到SharedPreferences中**/
  26.         button0.setOnClickListener(new  OnClickListener() {
  27.             @Override
  28.             public void onClick(View arg0) {
  29.                 /**拿到用户输入的信息**/
  30.                 String name = editName.getText().toString();
  31.                 String number = editNumber.getText().toString();
  32.                 /**开始保存入SharedPreferences**/
  33.                 Editor editor = mShared.edit();
  34.                 editor.putString(KEY_NAME, name);
  35.                 editor.putString(KEY_NUMBER, number);
  36.                 /**put完毕必需要commit()否则无法保存**/
  37.                 editor.commit();
  38.                 ShowDialog(“保存SharedPreferences成功”);
  39.             }
  40.         });
  41.         Button button1 = (Button)findViewById(R.id.sp_button1);
  42.         button1.setOnClickListener(new  OnClickListener() {
  43.             @Override
  44.             public void onClick(View arg0) {
  45.                 /**开始清除SharedPreferences中保存的内容**/
  46.                 Editor editor = mShared.edit();
  47.                 editor.remove(KEY_NAME);
  48.                 editor.remove(KEY_NUMBER);
  49.                 //editor.clear();
  50.                 editor.commit();
  51.                 ShowDialog(“清除SharedPreferences数据成功”);
  52.             }
  53.         });
  54.         Button button2 = (Button)findViewById(R.id.sp_button2);
  55.         button2.setOnClickListener(new OnClickListener() {
  56.             @Override
  57.             public void onClick(View arg0) {
  58.                 /** 删除SharedPreferences文件 **/
  59.                 File file = new File(DATA_URL + getPackageName().toString()
  60.                         + “/shared_prefs”, SHARED_MAIN_XML);
  61.                 if (file.exists()) {
  62.                     file.delete();
  63.                 }
  64.                 ShowDialog(“删除SharedPreferences文件成功”);
  65.             }
  66.         });
  67.         super.onCreate(savedInstanceState);
  68.     }
  69.     public void ShowDialog(String string) {
  70.         AlertDialog.Builder builder = new AlertDialog.Builder(SPActivity.this);
  71.         builder.setIcon(R.drawable.icon);
  72.         builder.setTitle(string);
  73.         builder.setPositiveButton(“确定”, new DialogInterface.OnClickListener() {
  74.             public void onClick(DialogInterface dialog, int whichButton) {
  75.                 finish();
  76.             }
  77.         });
  78.         builder.show();
  79.     }
  80. }

复制代码

  1. <?xml version=”1.0″ encoding=”utf-8″?>
  2. <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
  3.         android:layout_width=”fill_parent”
  4.         android:layout_height=”fill_parent”
  5.         android:orientation=”vertical”
  6.         >
  7.         <ImageView android:id=”@+id/sp_image”
  8.                 android:layout_width=”wrap_content”
  9.                  android:layout_height=”wrap_content”
  10.                 android:src=”@drawable/image”
  11.                 android:layout_gravity=”center”
  12.                 />
  13.         <EditText android:id=”@+id/sp_et0″
  14.                           android:layout_width=”fill_parent”
  15.                       android:layout_height=”wrap_content”
  16.                       android:hint=”请输入你的姓名”>
  17.         </EditText>
  18.         <EditText android:id=”@+id/sp_et1″
  19.                           android:layout_width=”fill_parent”
  20.                       android:layout_height=”wrap_content”
  21.                       android:hint=”请输入你的号码”>
  22.         </EditText>
  23.         <Button   android:id=”@+id/sp_button0″
  24.                   android:layout_width=”wrap_content”
  25.                       android:layout_height=”wrap_content”
  26.                       android:text=”保存输入内容shared”>
  27.         </Button>
  28.         <Button   android:id=”@+id/sp_button1″
  29.                   android:layout_width=”wrap_content”
  30.                       android:layout_height=”wrap_content”
  31.                       android:text=”清除shared保存内容”>
  32.         </Button>
  33.         <Button   android:id=”@+id/sp_button2″
  34.                   android:layout_width=”wrap_content”
  35.                       android:layout_height=”wrap_content”
  36.                       android:text=”删除shared文件”>
  37.         </Button>
  38. </LinearLayout>

复制代码

2.在本地data文件下使用自己生成的文件处理数据的 新建 储存 读取 删除

如果说不想把内容存在SharedPreferences中的话,我们可以自己写一个文件保存须要的数据,在这里我将文件保存在系统中的工程路径下。

输入需要保存的内容

保存完毕后红框内呈现之前保存的数据

保存文件以后,文件被保存在了当前工程下 files 文件夹的路径下,这里说一下data文件夹 如果手机没有root 权限 用户是访问不到的,这种储存方式有一个麻烦的地方就是文件中保存的数据须要程序员自己去处理 , 好比文件中保存了很多字符串数据 但是我们只须要其中的一部分数据,这样就须要自己去写代码去从文件中拿需要的数据。

  1. public class FileActivity extends Activity {
  2.     public final static String FILE_NAME = “a.txt”;
  3.     /**File中储存数据的路径**/
  4.     public final static String DATA_URL = “/data/data/”;
  5.     @Override
  6.     protected void onCreate(Bundle savedInstanceState) {
  7.         setContentView(R.layout.file);
  8.         /**读取内容**/
  9.         String content = loadFile();
  10.         if(content == null) {
  11.             content =”上次没有输入内容请输入”;
  12.         }
  13.          String str  = “上次输入保存的内容的姓名为【 ” +content + “】”;
  14.         final EditText editContent = ((EditText)findViewById(R.id.file_et0));
  15.         editContent.setHint(str);
  16.         Button button0 = (Button)findViewById(R.id.file_button0);
  17.         /**监听按钮点击后保存用户输入信息到file中**/
  18.         button0.setOnClickListener(new  OnClickListener() {
  19.             @Override
  20.             public void onClick(View arg0) {
  21.                 /**拿到用户输入的信息**/
  22.                 String content = editContent.getText().toString();
  23.                 /**开始保存入file**/
  24.                 saveFile(content);
  25.                 ShowDialog(“保存File文件成功”);
  26.             }
  27.         });
  28.         Button button1 = (Button)findViewById(R.id.file_button1);
  29.         /**监听按钮点击后清空file中内容**/
  30.         button1.setOnClickListener(new  OnClickListener() {
  31.             @Override
  32.             public void onClick(View arg0) {
  33.                 cleanFile();
  34.                 ShowDialog(“清空File文件成功”);
  35.             }
  36.         });
  37.         Button button2 = (Button)findViewById(R.id.file_button2);
  38.         /**监听按钮点击后删除file文件**/
  39.         button2.setOnClickListener(new  OnClickListener() {
  40.             @Override
  41.             public void onClick(View arg0) {
  42.                 File file = new File(DATA_URL + getPackageName().toString()
  43.                         + “/files”, FILE_NAME);
  44.                 if (file.exists()) {
  45.                     file.delete();
  46.                 }
  47.                 ShowDialog(“删除file文件成功”);
  48.             }
  49.         });
  50.         super.onCreate(savedInstanceState);
  51.     }
  52.     /**
  53.      * 保存内容
  54.      * @param str
  55.      */
  56.     public void saveFile(String str) {
  57.         try {
  58.             FileOutputStream outStream = this.openFileOutput(FILE_NAME,
  59.                     Context.MODE_WORLD_READABLE);
  60.             outStream.write(str.getBytes());
  61.             outStream.close();
  62.         } catch (FileNotFoundException e) {
  63.         } catch (IOException e) {
  64.         }
  65.     }
  66.     /**
  67.      * 因为java删除文件内容只有一种实现方法,就是把整个文件重写,只是把须要删除的那一条记录去除掉
  68.      */
  69.     public void cleanFile() {
  70.         //如果只须要删除文件中的一部分内容则须要在这里对字符串做一些操作
  71.         String cleanStr = “”;
  72.         try {
  73.             FileOutputStream outStream = this.openFileOutput(FILE_NAME,
  74.                     Context.MODE_WORLD_READABLE);
  75.             outStream.write(cleanStr.getBytes());
  76.             outStream.close();
  77.         } catch (FileNotFoundException e) {
  78.         } catch (IOException e) {
  79.         }
  80.     }
  81.     public String loadFile() {
  82.         try {
  83.             FileInputStream inStream = this.openFileInput(FILE_NAME);
  84.             ByteArrayOutputStream stream = new ByteArrayOutputStream();
  85.             byte[] buffer = new byte[1024];
  86.             int length = -1;
  87.             while ((length = inStream.read(buffer)) != -1) {
  88.                 stream.write(buffer, 0, length);
  89.             }
  90.             stream.close();
  91.             inStream.close();
  92.             return stream.toString();
  93.         } catch (FileNotFoundException e) {
  94.             e.printStackTrace();
  95.         } catch (IOException e) {
  96.         }
  97.         return null;
  98.     }
  99.     public void ShowDialog(String str) {
  100.         AlertDialog.Builder builder = new AlertDialog.Builder(FileActivity.this);
  101.         builder.setIcon(R.drawable.icon);
  102.         builder.setTitle(str);
  103.         builder.setPositiveButton(“确定”, new DialogInterface.OnClickListener() {
  104.             public void onClick(DialogInterface dialog, int whichButton) {
  105.                 finish();
  106.             }
  107.         });
  108.         builder.show();
  109.     }
  110. }

复制代码

  1. <?xml version=”1.0″ encoding=”utf-8″?>
  2. <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
  3.         android:layout_width=”fill_parent”
  4.         android:layout_height=”fill_parent”
  5.         android:orientation=”vertical”
  6.         >
  7.         <ImageView android:id=”@+id/file_image”
  8.                 android:layout_width=”wrap_content”
  9.                  android:layout_height=”wrap_content”
  10.                 android:src=”@drawable/jay”
  11.                 android:layout_gravity=”center”
  12.                 />
  13.         <EditText android:id=”@+id/file_et0″
  14.                           android:layout_width=”fill_parent”
  15.                       android:layout_height=”wrap_content”
  16.                       android:hint=”请输入需要保存的内容”>
  17.         </EditText>
  18.         <Button   android:id=”@+id/file_button0″
  19.                   android:layout_width=”wrap_content”
  20.                       android:layout_height=”wrap_content”
  21.                       android:text=”保存入file”>
  22.         </Button>
  23.         <Button   android:id=”@+id/file_button1″
  24.                   android:layout_width=”wrap_content”
  25.                       android:layout_height=”wrap_content”
  26.                       android:text=”清除file保存内容”>
  27.         </Button>
  28.         <Button   android:id=”@+id/file_button2″
  29.                   android:layout_width=”wrap_content”
  30.                       android:layout_height=”wrap_content”
  31.                       android:text=”删除file文件”>
  32.         </Button>
  33. </LinearLayout>

复制代码

3.在本地程序res/raw中读取数据操作

Android 下提供了专门读取程序res/raw路径下资源的方法,但是没有提供写入raw内容的方法,也就是说只能读不能写,在做软件的时候有时须要读取大量的文字资源,由于这些资源文字在软件中不会改变所以无需去对它的内容重写修改,就可以使用raw来操作数据。

如图所示:在列表中读取.bin文件中的内容分别显示在listView中


如图所示在raw路径下存了一个文件date0.bin ,下面是bin文件中保存的内容,程序中须要对这个.bin文件的内容进行读取并显示在屏幕中。

下面给出代码的实现

  1. public class loadRawActivity extends ListActivity {
  2.     private class MyListAdapter extends BaseAdapter {
  3.         private int[] colors = new int[] { 0xff626569, 0xff4f5257 };
  4.         public MyListAdapter(Context context) {
  5.             mContext = context;
  6.         }
  7.         public int getCount() {
  8.             return inpormation.length;
  9.         }
  10.         @Override
  11.         public boolean areAllItemsEnabled() {
  12.             return false;
  13.         }
  14.         public Object getItem(int position) {
  15.             return position;
  16.         }
  17.         public long getItemId(int position) {
  18.             return position;
  19.         }
  20.         public View getView(int position, View convertView, ViewGroup parent) {
  21.             TextView tv;
  22.             if (convertView == null) {
  23.                 tv = (TextView) LayoutInflater.from(mContext).inflate(
  24.                         android.R.layout.simple_list_item_1, parent, false);
  25.             } else {
  26.                 tv = (TextView) convertView;
  27.             }
  28.             int colorPos = position % colors.length;
  29.             tv.setBackgroundColor(colors[colorPos]);
  30.             tv.setText(String.valueOf(position + 1) + “:”
  31.                     + inpormation[position]);
  32.             return tv;
  33.         }
  34.         private Context mContext;
  35.     }
  36.     String[] inpormation = null;
  37.     ListView listView;
  38.     @Override
  39.     protected void onCreate(Bundle savedInstanceState) {
  40.         readFile(R.raw.date0);
  41.         setListAdapter(new MyListAdapter(this));
  42.         listView = getListView();
  43.         int[] colors = { 0, 0xFF505259, 0 };
  44.         listView
  45.                 .setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
  46.         listView.setDividerHeight(10);
  47.         super.onCreate(savedInstanceState);
  48.     }
  49.     /**
  50.      * 从raw中读取数据
  51.      * @param ID
  52.      */
  53.     public void readFile(int ID) {
  54.         InputStream in = null;
  55.         String temp = “”;
  56.         try {
  57.             in = this.getResources().openRawResource(ID);
  58.             byte[] buff = new byte[1024];// 缓存
  59.             int rd = 0;
  60.             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  61.             while ((rd = in.read(buff)) != -1) {
  62.                 baos.write(buff, 0, rd);
  63.                 temp = new String(baos.toByteArray(), “UTF-8″);
  64.             }
  65.             baos.close();
  66.             in.close();
  67.             inpormation = temp.split(“\r\n”);
  68.         } catch (Exception e) {
  69.             Toast.makeText(this, “文件没有找到”, 2000).show();
  70.         }
  71.     }
  72. }

复制代码

3.在SD卡中处理新建 写入 读取 删除 的操作

可以把数据保存在SD卡中,在SD卡中建立一个文件去保存数据,这里说一下 ,SD卡 用户是可以访问的,也就是说可以把一些可有可无的数据存在SD卡中,即使用户删除了卡中的内容也不会影像软件的使用。

将文件在SD卡中删除

  1. public class loadSDActivity extends Activity {
  2.     public final static String FILE_NAME = “b.txt”;
  3.     @Override
  4.     protected void onCreate(Bundle savedInstanceState) {
  5.         setContentView(R.layout.sdfile);
  6.         /**读取内容**/
  7.         String content = loadFile();
  8.         if(content == null) {
  9.             content =”上次没有输入内容请输入”;
  10.         }
  11.         final EditText editContent = (EditText)findViewById(R.id.sdfile_et0);
  12.         editContent.setHint(“上次输入SD卡的内容的为【 ” +content + “】”);
  13.         Button button0 = (Button)findViewById(R.id.sdfile_button0);
  14.         /**监听按钮点击后保存用户输入信息到SD卡中**/
  15.         button0.setOnClickListener(new  OnClickListener() {
  16.             @Override
  17.             public void onClick(View arg0) {
  18.                 /**拿到用户输入的信息**/
  19.                 String content = editContent.getText().toString();
  20.                 /**开始保存入SD卡**/
  21.                 saveFile(content);
  22.                 ShowDialog(“保存SD卡文件成功”);
  23.             }
  24.         });
  25.         Button button1 = (Button)findViewById(R.id.sdfile_button1);
  26.         /**去清除SD卡保存的内容**/
  27.         button1.setOnClickListener(new  OnClickListener() {
  28.             @Override
  29.             public void onClick(View arg0) {
  30.                 cleanFile();
  31.                 ShowDialog(“清除SD卡文件中的内容成功”);
  32.             }
  33.         });
  34.         Button button2 = (Button)findViewById(R.id.sdfile_button2);
  35.         /**删除SD卡保存的文件**/
  36.         button2.setOnClickListener(new  OnClickListener() {
  37.             @Override
  38.             public void onClick(View arg0) {
  39.                 DeleteSDFile();
  40.             }
  41.         });
  42.         super.onCreate(savedInstanceState);
  43.     }
  44.     /**
  45.      * 保存入SD卡中
  46.      * @param str
  47.      */
  48.     public void saveFile(String str) {
  49.         FileOutputStream fileOutputStream = null;
  50.         File file = new File(Environment.getExternalStorageDirectory(),
  51.                 FILE_NAME);
  52.         try {
  53.             fileOutputStream = new FileOutputStream(file);
  54.             fileOutputStream.write(str.getBytes());
  55.             fileOutputStream.close();
  56.         } catch (FileNotFoundException e) {
  57.             e.printStackTrace();
  58.         }catch (IOException e) {
  59.             e.printStackTrace();
  60.         }
  61.     }
  62.     /**
  63.      * 读取SD卡的内容
  64.      * @return
  65.      */
  66.     public String loadFile() {
  67.         String path = Environment.getExternalStorageDirectory() +”/” + FILE_NAME;
  68.         try {
  69.             FileInputStream fi = new FileInputStream(path);
  70.             BufferedReader br = new BufferedReader(new InputStreamReader(
  71.                     fi));
  72.             String readString = new String();
  73.             while ((readString = br.readLine()) != null) {
  74.                 //数据多的话须要在这里处理 readString
  75.                 return readString;
  76.             }
  77.             fi.close();
  78.         } catch (FileNotFoundException e) {
  79.             e.printStackTrace();
  80.         } catch (IOException e) {
  81.             e.printStackTrace();
  82.         }
  83.         return null;
  84.     }
  85.     /**
  86.      * 删除SD卡
  87.      */
  88.     public void DeleteSDFile() {
  89.         String path = Environment.getExternalStorageDirectory() + “/”
  90.                 + FILE_NAME;
  91.         File file1 = new File(path);
  92.         boolean isdelte = file1.delete();
  93.         if(isdelte) {
  94.             ShowDialog(“删除SD卡成功”);
  95.         }else {
  96.             finish();
  97.         }
  98.     }
  99.     /**
  100.      * 因为java删除文件内容只有一种实现方法,就是把整个文件重写,只是把须要删除的那一条记录去除掉
  101.      */
  102.     public void cleanFile() {
  103.         //如果只须要删除文件中的一部分内容则须要在这里对字符串做一些操作
  104.         String cleanStr = “”;
  105.         FileOutputStream fileOutputStream = null;
  106.         File file = new File(Environment.getExternalStorageDirectory(),
  107.                 FILE_NAME);
  108.         try {
  109.             fileOutputStream = new FileOutputStream(file);
  110.             fileOutputStream.write(cleanStr.getBytes());
  111.             fileOutputStream.close();
  112.         } catch (FileNotFoundException e) {
  113.             e.printStackTrace();
  114.         }catch (IOException e) {
  115.             e.printStackTrace();
  116.         }
  117.     }
  118.     public void ShowDialog(String str) {
  119.         AlertDialog.Builder builder = new AlertDialog.Builder(loadSDActivity.this);
  120.         builder.setIcon(R.drawable.icon);
  121.         builder.setTitle(str);
  122.         builder.setPositiveButton(“确定”, new DialogInterface.OnClickListener() {
  123.             public void onClick(DialogInterface dialog, int whichButton) {
  124.                 finish();
  125.             }
  126.         });
  127.         builder.show();
  128.     }
  129. }

复制代码

  1. <?xml version=”1.0″ encoding=”utf-8″?>
  2. <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
  3.         android:layout_width=”fill_parent”
  4.         android:layout_height=”fill_parent”
  5.         android:orientation=”vertical”
  6.         >
  7.         <ImageView android:id=”@+id/sdfile_image”
  8.                 android:layout_width=”wrap_content”
  9.                  android:layout_height=”wrap_content”
  10.                 android:src=”@drawable/g”
  11.                 android:layout_gravity=”center”
  12.                 />
  13.         <EditText android:id=”@+id/sdfile_et0″
  14.                           android:layout_width=”fill_parent”
  15.                       android:layout_height=”wrap_content”
  16.                       android:hint=”请输入需要保存到SD卡的内容”>
  17.         </EditText>
  18.         <Button   android:id=”@+id/sdfile_button0″
  19.                   android:layout_width=”wrap_content”
  20.                       android:layout_height=”wrap_content”
  21.                       android:text=”保存输入内容到SD卡”>
  22.         </Button>
  23.         <Button   android:id=”@+id/sdfile_button1″
  24.                   android:layout_width=”wrap_content”
  25.                       android:layout_height=”wrap_content”
  26.                       android:text=”清除SD卡保存文件的内容”>
  27.         </Button>
  28.         <Button   android:id=”@+id/sdfile_button2″
  29.                   android:layout_width=”wrap_content”
  30.                       android:layout_height=”wrap_content”
  31.                       android:text=”删除SD卡中保存的文件”>
  32.         </Button>
  33. </LinearLayout>
阅读全文
0 0