package com.example.sharedemo01;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 { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 存数据到SharedPreferences, // 第一个参数是文件名,可自定义,取数据时要以这个名来取 // 第二参数是存储的方式 SharedPreferences share = this.getSharedPreferences("share", Context.MODE_PRIVATE); // 获取编辑器 Editor editor = share.edit(); // 通过编辑器来存,是map,用键值对存 editor.putString("username", "admin"); editor.putString("password", "123456"); // 执行任务 editor.commit(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); // 取数据 SharedPreferences share = this.getSharedPreferences("share", Context.MODE_PRIVATE); // 用键来取,第二个值为默认值 String user = share.getString("username", ""); String pwd = share.getString("password", ""); }}
share.xml