package com.changcheng.sharedpreferences;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AndroidSharedPreferences extends Activity {
private static final String TAG = "AndroidSharedPreferences";
private EditText etName;
private EditText etAge;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取按钮
Button btSet = (Button) this.findViewById(R.id.bt_set);
Button btRead = (Button) this.findViewById(R.id.bt_read);
// 获取编辑框
etName = (EditText) this.findViewById(R.id.et_name);
etAge = (EditText) this.findViewById(R.id.et_age);
// 添加事件
btSet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 获取名称和年龄
String name = etName.getText().toString();
String age = etAge.getText().toString();
// 创建SharedPreferences
SharedPreferences sp = getSharedPreferences("preferences",
Context.MODE_PRIVATE);
// 添加数据
Editor editor = sp.edit();
editor.putString("name", name);
editor.putInt("age", Integer.parseInt(age));
// 保存数据
if (editor.commit())
Toast.makeText(AndroidSharedPreferences.this,
R.string.save_success, 1).show();
else
Toast.makeText(AndroidSharedPreferences.this,
R.string.save_failed, 1).show();
}
});
btRead.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 创建SharedPreferences
SharedPreferences sp = getSharedPreferences("preferences",
Context.MODE_PRIVATE);
// 获取数据
String name = sp.getString("name", "defName");
String age = sp.getInt("age", 0) + "";
// 显示数据
etName.setText(name);
etAge.setText(age);
}
});
}
}
|