今天我们讲下SharedPreferences的使用,就是读取或写入数据到内存中,比较简单,我们直接看代码吧。
package com.example.sharedpreferences_01;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private SharedPreferences pref;
Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化一个SharedPreferences对象
pref = getSharedPreferences("myPref", MODE_PRIVATE);
//实例化editor对象的方法
editor = pref.edit();
//存放数据
editor.putString("name", "张三");
editor.putInt("age", 20);
editor.putBoolean("isMarry", false);
editor.putLong("time", System.currentTimeMillis());
editor.commit();
editor.remove("time");
editor.commit();
Log.i("main", pref.getString("name", "")); //获取数据
Log.i("main", "" + pref.getInt("age", 0));
}
}