Android开发之SharedPreferences的使用

如果程序中需要保存用户设置的信息,我们可以选择保存到数据库或文件中,但如果是少量的配置信息,Android为我们提供了更加方便的保存方法:SharedPreferences,使用SharedPreferences保存的文件在对应的的应用程序安装目录下生成.xml文件,读取也很方便,通过键值对的方式读取。如我们需要把下面的登录界面保存起来,下次启动就显示退出前的配置。



保存文件

package com.example.login.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.widget.Toast;

public class LoginService {

	public static boolean saveFile(Context context, String userName,
			String password) {
		try {
			// 把数据写入到文件
			File file = new File(context.getFilesDir() + File.separator
					+ "info.txt");
			FileOutputStream fos = new FileOutputStream(file, true);
			fos.write((userName + "--" + password).getBytes());
			fos.close();
			Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	public static Map<String, String> getUseInfo(Context context) {
		try {
			// 把数据写入到文件
			File file = new File(context.getFilesDir() + File.separator
					+ "info.txt");
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line = br.readLine();
			Map<String, String> map = new HashMap<String, String>();
			while (line != null) {
				String arr[] = line.split("--");
				map.put("userName", arr[0]);
				map.put("password", arr[1]);
				line = br.readLine();
				System.out.println(arr[0] + "--" + arr[1]);
			}
			br.close();
			Toast.makeText(context, "读取文件成功", Toast.LENGTH_SHORT).show();
			return map;
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(context, "读取文件失败", Toast.LENGTH_SHORT).show();
			return null;
		}
	}

	/**
	 * 保存数据
	 * @param context
	 * @param userName
	 * @param password
	 */
	public static void saveFileEx(Context context, String userName,
			String password) {
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		//得到一个编辑器
		Editor editor = sp.edit();
		editor.putString("username", userName);
		editor.putString("password", password);
		editor.commit();  //提交事务,保证数据同时提交
	}
	
	/**
	 * 保存用户配置信息
	 * @param context
	 * @param index
	 * @param flag
	 */
	public static void SaveChage(Context context, int index, boolean flag){
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		//得到一个编辑器
		Editor editor = sp.edit();
		editor.putInt("index", index);
		editor.putBoolean("flag", flag);
		editor.commit();  //提交事务,保证数据同时提交
	}
}

主Activity

package com.example.login;

import com.example.login.service.LoginService;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

/**
 * 使用SharedPreferences保存用户的配置信息
 * 
 * @author Administrator
 * 
 */
public class MainActivity extends Activity implements OnClickListener {

	private EditText userName;
	private EditText password;
	private RadioGroup permission;
	private CheckBox cbSave;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		userName = (EditText) findViewById(R.id.etUserName);
		password = (EditText) findViewById(R.id.etPassword);
		permission = (RadioGroup) findViewById(R.id.rgPermission);
		cbSave = (CheckBox) findViewById(R.id.cbRemberPwd);
		Button login = (Button) findViewById(R.id.btnLogin);
		login.setOnClickListener(this);
		// LoginService.getUseInfo(this);
		InitLogin();
	}

	/**
	 * 按钮响应函数
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnLogin:
			Login();
			break;

		default:
			break;
		}
	}

	/**
	 * 登录
	 */
	private void Login() {
		if ((!TextUtils.isEmpty(userName.getText().toString()))
				|| (!TextUtils.isEmpty(password.getText().toString()))) {
			if (cbSave.isChecked()) {
				System.out.println("checkBox is check");
				LoginService.saveFileEx(MainActivity.this, userName.getText()
						.toString(), password.getText().toString());
				Toast.makeText(this, "保存用户信息成功", Toast.LENGTH_SHORT).show();
			}
			int index = 0;
			for (int i = 0; i < permission.getChildCount(); i++) {
				RadioButton r = (RadioButton) permission.getChildAt(i);
				if (r.isChecked()) {
					index = i;
					break;
				}
			}
			LoginService.SaveChage(this, index, cbSave.isChecked());

		} else {
			Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 回显用户之前的配置信息
	 */
	private void InitLogin() {
		SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
		String strName = sp.getString("username", "");
		userName.setText(strName);
		String strPassword = sp.getString("password", "");
		password.setText(strPassword);
		boolean flag = sp.getBoolean("flag", false);
		cbSave.setChecked(flag);
		int index = sp.getInt("index", 0);
		System.out.println(index + "---" + permission.getChildCount());
		if (index < permission.getChildCount()) {
			RadioButton r = (RadioButton) permission.getChildAt(index);
			r.setChecked(true);
		}
	}
}

布局文件

<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"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/user_name" />

    <EditText
        android:id="@+id/etUserName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/password" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <RadioGroup
            android:id="@+id/rgPermission"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/rbPrivate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/rb_private" />

            <RadioButton
                android:id="@+id/rbReadable"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/rb_read" />

            <RadioButton
                android:id="@+id/rbWritable"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/rb_write" />

            <RadioButton
                android:id="@+id/rbPublic"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/rb_public" />
        </RadioGroup>

        <CheckBox
            android:id="@+id/cbRemberPwd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/rgPermission"
            android:text="@string/rember_pwd" />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@id/rgPermission"
            android:text="@string/login" />
    </RelativeLayout>

</LinearLayout>

关键代码

Editor.putString(String key,String value) 保存数据
Editor.commit() 提交数据
SharedPreferences.getString(String key,String defValue) 获取数据

生成的文件保存到安装目录下



保存的文件格式


Demo代码

点击打开链接


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值