Android SharedPreferences一般的读写

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();
	}
}

阅读更多
版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/49942685
文章标签: android
个人分类: Android
上一篇Android Activity加载Fragment的一般简易方法
下一篇Android Fragment生命周期图以及Activity与Fragment生命周期对照图
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭