android SharedPreferences简单应用 插入数据 读取数据

package com.sharedpreference;  
  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import android.os.Bundle;  
import android.app.Activity;  
import android.content.SharedPreferences;  
import android.view.Menu;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.Toast;  
  
public class SharedPreferenceActivity extends Activity {  
  
    SharedPreferences preferences;  
      
    //Editor放入值  
    SharedPreferences.Editor editor;  
    private Button btnWrite;  
    private Button btnRead;  
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        btnRead = (Button)findViewById(R.id.read);  
        btnWrite = (Button)findViewById(R.id.write);  
        //context提供的getSharedPreferences获得sharedPreferences实例  
        preferences = getSharedPreferences("bang", MODE_PRIVATE);  
        editor = preferences.edit();  
        btnRead.setOnClickListener(new OnClickListener() {  
              
            @Override  
            public void onClick(View arg0) {  
                //读取字符串数据类型  
                String time = preferences.getString("time",null);  
                  
                //读取int数据类型  
                int randNum = preferences.getInt("randrom", 0);  
                  
                String result = time == null ? "您暂时还没写入数据" : "写入时间为:"+time+"\n上次生成的随机数为:"+randNum;  
                  
                Toast.makeText(SharedPreferenceActivity.this, result,5000).show();  
            }  
        });  
          
        btnWrite.setOnClickListener(new OnClickListener() {  
              
            @Override  
            public void onClick(View arg0) {  
                  
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"+"hh:mm:ss");  
                  
                editor.putString("time", sdf.format(new Date()));  
                  
                editor.putInt("randrom", (int)(Math.random()*100));  
                //提交保存的数据  
                editor.commit();  
            }  
        });  
          
    }  
  
  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.main, menu);  
        return true;  
    }  
      
}  

生成的shared_prefs下的xml文件为

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>  
<map>  
    <string name="time">2014年04月14日01:10:21</string>  
    <int name="randrom" value="20" />  
</map>  

SharedPreferences 存储简单数据 保存键值对类型数据

你可能感兴趣的:(android SharedPreferences简单应用 插入数据 读取数据)