Android SharedPreferences一般的读写

  1. 云栖社区>
  2. 博客>
  3. 正文

Android SharedPreferences一般的读写

开开心心过 2015-11-20 09:05:38 浏览229
展开阅读全文
package com.example.sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

	private final String SharedPreferences_Name = "SharedPreferences_name";

	private final String USER_NAME = "user_name";
	private final String USER_PASSWORD = "user_password";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		wrtieSharedPreferences();
		readSharedPreferences();
	}

	// 读出记录
	private void readSharedPreferences() {
		SharedPreferences sp = this.getSharedPreferences(
				SharedPreferences_Name, Context.MODE_PRIVATE);
		String username = sp.getString(USER_NAME, "无值");
		Log.d("存储到本地的用户名", username);
	}

	// 写入记录到本地
	private void wrtieSharedPreferences() {
		SharedPreferences shared = this.getSharedPreferences(
				SharedPreferences_Name, Context.MODE_PRIVATE);

		Editor edit = shared.edit();
		edit.putString(USER_NAME, "zhangphil");
		edit.putString(USER_PASSWORD, "12345678");

		// 提交
		edit.commit();
	}
}

网友评论

登录后评论
0/500
评论
开开心心过
+ 关注