Android用SharePreference存取信息

在Android中,可以用SharePreference存取簡單的信息,例如登陸時用於記住登陸名稱與密碼等。

類的結構:android.content.SharedPreferences

下面用一個簡單的例子說明SharePreference的用法

新建一個Activity,名字是test

界面非常簡單:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:orientation="vertical" >

	<EditText
		android:id="@+id/name"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />

	<EditText
		android:id="@+id/age"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />

</LinearLayout>
兩個edittext控件

下面是MainActivity部分:

</pre><pre name="code" class="java">package com.example.test;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends Activity {
	private EditText nameTxt;
	private EditText ageTxt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		nameTxt = (EditText) findViewById(R.id.name);
		ageTxt = (EditText) findViewById(R.id.age);
		// 實例化SharePreference對象,數據要保存在xml文件中,getsharepreference的第
		// 一個參數是要保存的xml文件的名字,第二個是xml文件的讀寫權限
		SharedPreferences preferences = MainActivity.this.getSharedPreferences(
				"MyPreference", Activity.MODE_PRIVATE);
		// 實例化editor,用於編輯xml文件的內容
		SharedPreferences.Editor editor = preferences.edit();
		// 放入string類型數據
		editor.putString("name", "Bob");
		// 放入int類型數據
		editor.putInt("age", 23);
		// 必須提交後才能寫入
		editor.commit();
		// nameTxt.setText(preferences.getString("name", ""));
		// ageTxt.setText(preferences.getInt("age", 0) + "");
	}
}
通過以上代碼就能將string類型和int類型的數據寫入MyPreference這個xml文件中,那麼這個xml文件存儲在什麼位置呢?

通過file explorer我們發現,在/dada/dada/com.example.test下,多出了一個shared_prefs文件夾,這個文件夾就是用來保存xml文件的。裏面有我們保存的MyPreference.xml文件。打開這個文件可以看到裏面是以key-value的方式保存數據的。跟我們保存的時候相對應。

保存信息完成了,讀取信息則要更簡單些。在editor.commit();下面兩行:

<span style="background-color: rgb(249, 249, 249);"> nameTxt.setText(preferences.getString("name", ""));//從xml文件中讀取"name"的值,就是我們放入的"Bob",第二個參數是<span style="font-family:Roboto, sans-serif;">默認值</span></span><table class="jd-tagtable " style="background-color: rgb(249, 249, 249);"><tbody><tr><th>defValue</th><td>Value to return if this preference does not exist</td></tr></tbody></table>下面的讀取int類型的數據也就不難理解了。
這樣我們每次打開這個Activity就能看到兩個edittext不是空了。





SharePreference是以xml文件保存信息的,
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章