Android 使用SharedPreferences进行数据存储和读取数据

很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存,如果是j2se应用,我们会采用properties属性文件或者xml进行保存。如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下。

下面用默认路径的设置,举例说明其用法,首先是布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
   
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="@string/hello"
	    />
    <EditText
    	android:layout_width="fill_parent" 
	    android:layout_height="wrap_content"
	    android:id="@+id/pathName"
	    />
	<Button
		android:layout_width="wrap_content" 
	    android:layout_height="wrap_content"
	    android:text="@string/button"
	   	android:id="@+id/btn_savePath"
	    />

	<TextView
	    android:id="@+id/explaition"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="@string/pathset_explation" />

</LinearLayout>


下面是PreferencesService类:

package lhjd.cnc.dispenser.setting;

import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class PreferencesService
{
	private Context context;
	public PreferencesService(Context context)
	{
		this.context = context;
	}
	/**
	 * 实现应用参数保存
	 * @param name
	 * @param age
	 * @throws Exception
	 */
	public void save(String name) throws Exception
	{
		SharedPreferences preferences=context.getSharedPreferences("pathSet", Context.MODE_WORLD_READABLE);
		Editor editor=preferences.edit();
		editor.putString("name", name);
		editor.commit();
	}
	
	/**
	 * 实现应用参数提取
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> getPreferences() throws Exception
	{
		SharedPreferences preferences=context.getSharedPreferences("pathSet", Context.MODE_WORLD_READABLE);
		Map<String, String> result=new HashMap<String, String>();
		result.put("name", preferences.getString("name", ""));
		return result;
	}
}

下面是activity

public class PathSet extends Activity{
	
	private EditText pathNameText;
	private PreferencesService service;
	public PathSet(final Context context) {
		super(context);
		LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.pathset, this);
		service=new PreferencesService(context);
		pathNameText=(EditText)this.findViewById(R.id.pathName);
	    Map<String, String> params = null;
		try {
			params = service.getPreferences();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		pathNameText.setText(params.get("name"));
        Button button=(Button)findViewById(R.id.btn_savePath);
        button.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				String name=pathNameText.getText().toString().trim();
				if("".equals(name)||name==null){
					Toast.makeText(context, "路径不能为空", 1).show();
				}else{
					try
					{
						service.save(name);
						Toast.makeText(context, R.string.succss, 1).show();
					} catch (Exception e)
					{
						Toast.makeText(context, R.string.fail, 1).show();
						e.printStackTrace();
					}
				}
			
			}
		});
    }
}


下面是截图效果:



  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SharedPreferencesAndroid中轻量级的数据存储方式之一,用于存储一些简单的键值对数据进行读取。以下是在Android Studio中使用SharedPreferences进行数据存储读取的步骤: 1. 创建SharedPreferences对象 在Activity中,我们可以通过以下代码创建SharedPreferences对象: ```java SharedPreferences preferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE); ``` 其中,第一个参数是SharedPreferences的名称,第二个参数是访问模式,MODE_PRIVATE表示只有当前应用程序可以访问该SharedPreferences。 2. 存储数据 使用SharedPreferences存储数据可以使用其Editor对象,示例代码如下: ```java SharedPreferences preferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("key", "value"); editor.apply(); ``` 其中,putString()方法用于存储字符串类型的数据,第一个参数是键,第二个参数是值。apply()方法用于提交修改。 3. 读取数据 使用SharedPreferences读取数据可以通过以下代码: ```java SharedPreferences preferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE); String value = preferences.getString("key", ""); ``` 其中,getString()方法用于读取字符串类型的数据,第一个参数是键,第二个参数是默认值。 以上就是在Android Studio中使用SharedPreferences进行数据存储读取的基本步骤。需要注意的是,SharedPreferences适合存储一些简单的键值对数据,对于复杂数据建议使用SQLite数据库等其他数据存储方式

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值