【073】Android 資料存放區(SQLite)

來源:互聯網
上載者:User
目錄:

I. 使用 SharedPreferences 來儲存應用程式的資料

II. 將應用程式的資料存放區到內部儲存空間中

III. 將應用程式的資料存放區到外部儲存空間中

IV. 通過 SQLite 資料庫來實現資料存放區

  • SQLiteDatabase 類
  • Cursor 介面
  • SQLiteOpenHelper 類
  • 具體操作步驟

V. Content Provider 簡介

I. 使用 SharedPreferences 來儲存應用程式的資料:

參考:Beginning Android 4 Application Development - Page 252

  • 將資料存放區到 SharedPreferences 對象中去,這個時候要用到 SharedPreferences.Editor 中的方法。
  • 上面的過程會將資料存放區在一個 xml 檔案中。
      在 DDMS 視圖中找到 File Explore, 選擇 data/data/<PackageName>/shared_prefs/*.xml
      如所示:
      
  • 通過 getSharedPreferences() 方法擷取 SharedPreferences 對象,並將裡面的資料取出。

舉例效果:

代碼功能:通過"修改文本"按鈕可以將常值內容儲存, 然後點擊"顯示文本"按鈕就可以顯示出剛才修改了的文本.

另外:在其他的 activity 中也可以直接的調用, 調用方法與下面的一樣~

 1 public class MainActivity extends Activity { 2  3     @Override 4     public void onCreate(Bundle savedInstanceState) { 5         super.onCreate(savedInstanceState); 6         setContentView(R.layout.activity_main); 7          8         Button displayButton = (Button)findViewById(R.id.button1); 9         displayButton.setOnClickListener(new OnClickListener() {10             11             public void onClick(View v) {12                 // TODO Auto-generated method stub13                 SharedPreferences appPreferences = getSharedPreferences(14                         "com.example.preferenceexer_preferences", MODE_PRIVATE);15                 Toast.makeText(MainActivity.this, appPreferences.getString("editTextPref", ""), Toast.LENGTH_SHORT).show();16             }17         });18         19         Button modifyButton = (Button)findViewById(R.id.button2);20         modifyButton.setOnClickListener(new OnClickListener() {21             22             public void onClick(View v) {23                 // TODO Auto-generated method stub24                 SharedPreferences appPreferences = getSharedPreferences(25                         "com.example.preferenceexer_preferences", MODE_PRIVATE);26                 SharedPreferences.Editor prefsEditor = appPreferences.edit();27                 prefsEditor.putString("editTextPref", ((EditText)findViewById(R.id.editText1)).getText().toString());28                 prefsEditor.commit();29             }30         });31     }32 }
SharedPreferences 介面:

1. Interface for accessing and modifying preference data returned by getSharedPreferences(String, int).

  getSharedPreferences(String, int):傳回值:SharedPreferences
    第一個參數:就是隱藏檔的名稱, 一般以 <PackageName>_preferences 的格式, 其他應該也是可以的
    第二個參數:0 代表 MODE_PRIVATE, 只允許此程式使用. 還有其他的常量.

2. SharedPreferences Methods:

  • edit():傳回值:SharedPreferences.Editor. 進入編輯模式.
  • contains(String key):檢查是否存在指定的鍵.
  • getAll():傳回值:Map<String, ?>. 從 preferences 中取回所有的值.
  • getBoolean(String key, boolean defValue):取回布爾值, 第二個為參數預設值.
  • getFloat(String key, float defValue):
  • getInt(String key, int defValue):
  • getLong(String key, long defValue):
  • getString(String key, String defValue):取回字串, 第二個參數為預設值.
  • getStringSet(String key, Set<String> defValues):
SharedPreferences.Editor 介面:

1. 用來修改 SharedPreferences 對象的值。

2. SharedPreferences.Editor Methods:

  • commit():提交修改的內容.
  • apply():同上.
  • remove(String key):刪除指定的鍵.
  • clear():全部清空.
  • putBoolean(String key, boolean value):加入布爾值.
  • putFloat(String key, float value):
  • putInt(String key, int value):
  • putLong(String key, long value):
  • putString(String key, String value):加入字串.
  • putStringSet(String key, Set<String> values):
 II. 將應用程式的資料存放區到內部儲存空間中:

參考:Beginning Android 4 Application Development - Page 263

:

 

在 DDMS 視圖中找到 File Explore, 選擇 data/data/<PackageName>/files/textfile.txt
  如所示: 

public class FilesActivity extends Activity {    EditText textBox;    static final int READ_BLOCK_SIZE = 100;  //字元數組    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        textBox = (EditText) findViewById(R.id.txtText1);    }    public void onClickSave(View view) {        String str = textBox.getText().toString();        try        {              FileOutputStream fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);  //檔案輸出資料流            OutputStreamWriter osw = new OutputStreamWriter(fOut);            osw.write(str);            osw.close();            Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_SHORT).show();            textBox.setText("");        }        catch (IOException ioe)        {            ioe.printStackTrace();        }    }    public void onClickLoad(View view) {        try        {            FileInputStream fIn = openFileInput("textfile.txt");  //檔案寫入流            InputStreamReader isr = new InputStreamReader(fIn);                        char[] inputBuffer = new char[READ_BLOCK_SIZE];            String s = "";            int charRead;            while ((charRead = isr.read(inputBuffer))>0)            {                String readString = String.copyValueOf(inputBuffer, 0, charRead);                s += readString;                inputBuffer = new char[READ_BLOCK_SIZE];            }            textBox.setText(s);            Toast.makeText(getBaseContext(), "File loaded successfully!", Toast.LENGTH_SHORT).show();        }        catch (IOException ioe) {            ioe.printStackTrace();        }    }}

源檔案下載:Files.zip

 III. 將應用程式的資料存放區到外部儲存空間中:

參考:Beginning Android 4 Application Development - Page 268

:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.