10天學通Android開發(7)-數據存儲

Android中,可使用幾種方式實現數據持久化:html

  • Shared Preferences:共享參數形式,一種以Key-Value的鍵值對形式保存數據的方式,Android內置的,通常應用的配置信息,推薦使用此種方式保存。android

  • Internal Storage:使用Android設備自帶的內存存儲數據。數據庫

  • External Storage:使用外部存儲設備存儲數據,通常是指Sdcardide

  • SQLite Databases:以SQLite數據庫存儲結構化的數據。函數

 

 

  1. SharedPreferences測試

也是一種輕型的數據存儲方式,它的本質是基於XML文件存儲key-value鍵值對數據,一般用來存儲一些簡單的配置信息。其存儲位置在/data/data/<包名>/shared_prefs目錄下。SharedPreferences對象自己只能獲取數據而不支持存儲和修改,存儲修改是經過Editor對象實現。實現SharedPreferences存儲的步驟以下:ui

  1、根據Context獲取SharedPreferences對象this

  2、利用edit()方法獲取Editor對象。spa

  3、經過Editor對象存儲key-value鍵值對數據。orm

4、經過commit()方法提交數據。

 

 

賦值:

putBoolean(KEY_SHOW_DIALOG_AT_START, false)

取值:

getBoolean(KEY_SHOW_DIALOG_AT_START,false);

 

SharedPreferences案例分析:

  1. 加進一檢查框

 

<CheckBox

       android:id="@+id/cbSent"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_alignLeft="@+id/textView1"

       android:layout_below="@+id/textView1"

       android:layout_marginTop="60dp"

        android:text="測試語句"/>

 

 

  1. 定義三變量

 

private CheckBox cbSent;

   private SharedPreferences sp;

   privatestaticfinal String KEY_SHOW_DIALOG_AT_START = "showDialog";

  

  1. onCreate中添加

 

 

      sp = getSharedPreferences("mysp", Context.MODE_PRIVATE);

     

      cb = (CheckBox) findViewById(R.id.cb);

      cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

         

          @Override

          publicvoid onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

             Editor e = sp.edit();

             e.putBoolean(KEY_SHOW_DIALOG_AT_START, isChecked);

             e.commit();

          }

      });

     

      cb.setChecked(sp.getBoolean(KEY_SHOW_DIALOG_AT_START, false));

     

      if (cb.isChecked()) {

             new AlertDialog.Builder(this).setTitle("標題").setMessage("顯示語句麼?").setPositiveButton("關閉", null).show();

  

      }

 

  1. 內部存儲

Internal Storage

  內部存儲,在Android中,開發者能夠直接使用設備的內部存儲器中保存文件,默認狀況下,以這種方式保存的和數據是隻能被當前程序訪問,在其餘程序中是沒法訪問到的,而當用戶卸載該程序的時候,這些文件也會隨之被刪除。

  使用內部存儲保存數據的方式,基本上也是先得到一個文件的輸出流,而後以write()的方式把待寫入的信息寫入到這個輸出流中,最後關閉流便可,這些都是JavaIO流的操做。具體步驟以下:

  • 使用Context.openFileOutput()方法獲取到一個FileOutputStream對象。

  • 把待寫入的內容經過write()方法寫入到FileOutputStream對象中。

  • 最後使用close()關閉流。

      上面介紹的Context.openFileOutput()方法有兩個重載函數,它們的簽名分別是:

  • FileOutputStream openFileOutput(Stringname):以MODE_PRIVATE的模式打開name文件。

  • FileOutputStream openFileOutput(Stringname,int mode):以mode的模式打開name文件。

      上面第二個重載函數中,mode爲一個int類型的數據,這個通常使用Context對象中設置好的常量參數,有以下幾個:

  • MODE_APPEND:以追加的方式打開一個文件,使用此模式寫入的內容均追加在本來內容的後面。

  • MODE_PRIVATE:私有模式(默認),若是文件已經存在會從新建立並替換原文件,若是不存在直接建立。

  • MODE_WORLD_READABLE:以只讀的方式打開文件。

  • MODE_WORLD_WRITEABLE:以只寫的方式打開文件。

      還有幾個方法須要特別注意一下,這幾個方法對於文件關係提供了更好的支持,配合上面介紹的方式,就能夠對文件的數據進行常規的CRUD操做(增刪改查),方法以下:

  • File getFIlesDir():獲取文件系統的絕對路徑。

  • boolean deleteFile(String name):刪除一個指定文件名爲name的文件。

  • String[] fileList():當前應用內部存儲路徑下的全部文件名。

 

Internal Storage案例分析:

1)加進編輯和命令按鈕

 

<EditText

       android:gravity="top"

       android:id="@+id/et"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:layout_weight="1"/>

 

    <Button

       android:id="@+id/btnSave"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

        android:text="保存" />

 

2)讀取數據

 

   privatevoid readSavedText(){

     

      try {

          InputStream is = openFileInput("data");

          byte[] bytes = newbyte[is.available()];

          is.read(bytes);

          is.close();

         

          String str = new String(bytes,"utf-8");

          et.setText(str);

      } catch (FileNotFoundException e) {

          e.printStackTrace();

      } catch (IOException e) {

          e.printStackTrace();

      }

     

   }

 

 

3保存數據

 

privatevoid saveCurrentText(){

     

      try {

          OutputStream os = openFileOutput("data", Context.MODE_PRIVATE);

          os.write(et.getText().toString().getBytes("utf-8"));

          os.flush();

          os.close();

         

          Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();

          return;

      } catch (FileNotFoundException e) {

          e.printStackTrace();

      } catch (UnsupportedEncodingException e) {

          e.printStackTrace();

      } catch (IOException e) {

          e.printStackTrace();

      }

     

      Toast.makeText(this, "保存失敗", Toast.LENGTH_SHORT).show();

     

   }

 

4)開始讀取數據和定義保存

et = (EditText) findViewById(R.id.et);

      btnSave = (Button) findViewById(R.id.btnSave);

     

        readSavedText();

     

      btnSave.setOnClickListener(new View.OnClickListener() {

         

          @Override

          publicvoid onClick(View v) {

            

             saveCurrentText();

          }

      });

       

 

 

參考:

http://www.cnblogs.com/weixing/p/3243115.html

相關文章
相關標籤/搜索