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文件保存信息的,
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章