Android下的資料儲存方式,android儲存方式
安卓系統預設提供了一下幾種資料儲存的方式:
使用Shared Preferences
Shared Preferences類主要用於儲存索引值對的資料類型。我們可以使用它儲存一些簡單的資料類型。
獲得SharedPreferences對象有兩種方法:
上面兩種方法的分別主要是:
第一種方法可以建立多個檔案來儲存資料
第二種方法只能建立一個檔案儲存資料
我們先來建立一個這樣的布局:
<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" ><EditText android:id="@+id/username" android:layout_width="fill_parent" android:layout_height="wrap_content"/><EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="wrap_content"/><Button android:id="@+id/write" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="write to file"/> </LinearLayout>
布局準備好後就可以擷取SharedPreferences對象寫入資料:
package com.whathecode.storageoptinos;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final EditText namefield = (EditText) findViewById(R.id.username);final EditText agefield = (EditText) findViewById(R.id.age);Button btnWrite = (Button) findViewById(R.id.write);// 擷取SharedPreferences對象,檔案許可權為私人SharedPreferences spf = getSharedPreferences("record", MODE_PRIVATE);// 擷取編輯器final SharedPreferences.Editor editor = spf.edit();btnWrite.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){String username = namefield.getText().toString();String age = agefield.getText().toString();editor.putString("username", username);editor.putString("age", age);if (editor.commit()) // 當成功寫入資料返回true{Toast.makeText(getBaseContext(), "檔案已寫入",Toast.LENGTH_SHORT).show();}}});}}
上面的代碼中,我們主要使用SharedPreferences的內部類Editor類
我們主要使用這個類的幾個Put*方法
當調用完這些方法後我們就可以使用commit()或者apply()方法開始寫資料
需要注意的是,當多個Editor對同一個檔案進行寫資料的時候,後完成的一個Editor的結果將覆蓋前一個的結果
commit和apply方法的區別是:commit寫入成功返回true,而apply沒有傳回值。
當我們不在乎傳回值的時候可以調用apply()方法寫資料。
運行結果:
資料寫入後我們就可以在Eclipse的ddms試圖中查看是否有寫入成功
資料儲存在 /data/data/包名/shared_prefs目錄下