Android学习笔记<20140112> SharedPreferences的使用

  Android为应用程序的存储提供了五种方式:1.Shared Preferences; 2.Internal Storage; 3. External Storage; 4. SQLite Database; 5.Network Connection。
  SharedPreferences的实现原理是基于XML文件以(key-value)键值对的方式保存基本类型的私有数据,主要用来保存用户配置信息。
  使用SharedPreferences存储数据的优点是使用简单,缺点是只能保存boolean, float, int, long, String五种基本数据类型的数据, 且不能进行条件查询。
  数据以XML文件的形式保存在应用程序的私有目录/data/data/<package name>/shared_prefs/name.xml中,在name.xml文件中,以map为根元素,以<string>、<int>等为子元素。
  读取应用程序的Preferences数据使用SharedPreferences接口提供的getXxx(String name, xxx defValue)方法。SharedPreferences是接口,不能直接获取实例,调用Context的实例的getSharedPreferences(String name, int mode)方法可以获得SharedPreferences接口的实例,mode表示应用程序私有的Preferences数据的读取权限,可为MODE_PRIVATE,MODE_WORLD_READABLE,MODE_WORLD_WRITABLE。
  写入应用程序的Preferences数据使用SharedPreferences接口的内部接口Editor实例的putXxx(String name, xxx value)方法。调用SharedPreferences接口的实例的edit()方法可获得Editor接口的实例。editor对Preferences数据写入/删除完毕后,须调用commit()方法进行提交。
  读写其它应用程序的Preferences,首先要求其它应用程序在创建Preferences时设定为可读/可写,其次要调用Context的createPackageContext(String <package name> , Context.CONTEXT_IGNORE_SECURITY)方法获得其它应用程序的context.最后调用其它应用程序的context的getSharedPreferences(String, int)方法获得SharedPreferences实例和Editor实例,进而进行读或写。
  目前SharedPreferences不支持多线程。
  对本应用程序的Preferences进行写入并读取的实例:

<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" >

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="@string/name"/>
        <EditText 
            android:id="@+id/edit_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/input_name"/>
    </LinearLayout>
    
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="@string/age"/>
        <EditText 
            android:id="@+id/edit_age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:hint="@string/input_age"/>
    </LinearLayout>
    
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button 
            android:id="@+id/button_read"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/read"/>
        <Button 
            android:id="@+id/button_write"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/write"/>
    </LinearLayout>

</LinearLayout>

package com.example.demo0112androidio1sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * 1. 应用程序的Preferences保存在路径:/data/data/<package name>/shared_prefs/*.xml。在xml文件中,以map为根元素
 *     ,以键值对为子元素。
 * 2. 原理是基于XML文件存储key-value键值对数据,主要用来存储简单的配置信息。
 * 3. 读取应用程序的Preferences数据使用SharedPreferences接口提供的getXxx(String key, xxx defValue)方法。调用Context实例的
 *     getSharedPreferences(String name, int mode)方法可获得SharedPreferences接口的实例, name代表的Preferences若不存在,会自动创建,
 *     mode表示name对应的Preferences的读写权限。
 * 4. 向应用程序的Preferences中写入数据使用SharedPreferences接口的内部接口Editor的putXxx(String key, xxx value)方法
 *     , 调用SharedPreferences对象的editor()方法可获取SharedPreferences接口的内部接口Editor的实例,Editor的对象对SharedPreferences
 *     添加/删除完毕后需要调用commit()方法进行提交。
 * 5. 读写其它应用程序的Preferences,首先要求其它应用程序在创建Preferences时设定为可读/可写,其次要调用Context的createPackageContext(String <package name>
 *     , Context.CONTEXT_IGNORE_SECURITY)方法获得其它应用程序的context.最后调用其它应用程序的context的getSharedPreferences()方法获得
 *     SharedPreferences实例和Editor实例,进而进行读或写。
 * 6. 优点:简单。缺点:只能存储boolean,float,int,long,String五种基本数据类型的数据。无法进行条件查询。
 * 7. 目前SharedPreferences不支持多线程。
 * */
public class MainActivity extends Activity {
	
	private EditText editName, editAge;
	private Button buttonRead, buttonWrite;
	
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor editor;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		sharedPreferences = getSharedPreferences("my_shared_preferences", Context.MODE_WORLD_READABLE);
		editor = sharedPreferences.edit();
		
		editName = (EditText) findViewById(R.id.edit_name);
		editAge = (EditText) findViewById(R.id.edit_age);
		buttonRead = (Button) findViewById(R.id.button_read);
		buttonWrite = (Button) findViewById(R.id.button_write);
		
		buttonRead.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String name = sharedPreferences.getString("name", "");
				int age = sharedPreferences.getInt("age", 0);
				
				editName.setText(name);
				editAge.setText(age + "");
			}
		});
		
		buttonWrite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String name = editName.getText().toString();
				int age = Integer.parseInt(editAge.getText().toString());
				
				editor.putString("name", name);
				editor.putInt("age", age);
				editor.commit();
				
				editName.setText("");
				editAge.setText("");
			}
		});
	}

}

  点击写入后,在FileExplore面板中查看应用程序私有文件夹,里面新添加一个shared_pref目录,且目录下有一个名为my_shared_preferences.xml的文件,如下图所示:





读取其它应用程序的Preferences的实例

<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" >

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="@string/name"/>
        <EditText 
            android:id="@+id/edit_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:hint="@string/input_name"/>
    </LinearLayout>
    
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="@string/age"/>
        <EditText 
            android:id="@+id/edit_age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:hint="@string/input_age"/>
    </LinearLayout>
    
    <Button 
        android:id="@+id/button_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/read"/>

</LinearLayout>
package com.example.demo0112androidio1sharedpreferences2;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	
	private EditText editName, editAge;
	private Button buttonRead;
	
	private SharedPreferences sharedPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		editName = (EditText) findViewById(R.id.edit_name);
		editAge = (EditText) findViewById(R.id.edit_age);
		buttonRead = (Button) findViewById(R.id.button_read);
		
		Context context = null;
		try {
			context = createPackageContext("com.example.demo0112androidio1sharedpreferences"
					, CONTEXT_IGNORE_SECURITY);
			sharedPreferences = context.getSharedPreferences("my_shared_preferences", Context.MODE_WORLD_READABLE);
			
			buttonRead.setOnClickListener(new MyOnClickListener());
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private class MyOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			String name = sharedPreferences.getString("name", "");
			int age = sharedPreferences.getInt("age", 0);
			
			editName.setText(name);
			editAge.setText(age + "");
		}
	}

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值