package com.uppowerstudio.chapter5.preferences;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Preference示例
* @author UPPower Studio
*
*/
public class MainActivity extends Activity {
// 定義保存的Preferences名稱
private static final String PREF_NAME = "pref_sample";
// 定義保存在Preferences中數據的key
private static final String PREF_KEY = "pref_input_data";
// 聲明控件變量
private Button saveButton;
private Button loadButton;
private EditText txtPrefInput;
private TextView displayTextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 載入布局文件main.xml
setContentView(R.layout.main);
// 初始化控件
saveButton = (Button) findViewById(R.id.button_save_pref);
loadButton = (Button) findViewById(R.id.button_load_pref);
txtPrefInput = (EditText) findViewById(R.id.edit_pref_input_data);
displayTextView = (TextView) findViewById(R.id.pref_content);
// 注冊事件監聽器
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
// 獲取用戶輸入的數據
String inputData = txtPrefInput.getText().toString();
// 獲取SharedPreferences對象
SharedPreferences sp = getSharedPreferences(PREF_NAME,
Context.MODE_WORLD_WRITEABLE);
// 獲取SharedPreferences.Editor對象,對Preferences進行修改操作
SharedPreferences.Editor editor = sp.edit();
// 設置數據
editor.putString(PREF_KEY, inputData);
// 調用commit方法保存數據
editor.commit();
// 提示保存成功
Toast.makeText(MainActivity.this,
getString(R.string.msg_save_success),
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
ex.printStackTrace();
// 提示保存失敗
Toast.makeText(MainActivity.this,
getString(R.string.msg_save_failure),
Toast.LENGTH_LONG).show();
}
}
});
loadButton.setOnClickListener(new OnClickListener() {
@SuppressLint("WorldWriteableFiles")
public void onClick(View v) {
// 獲取SharedPreferences對象
SharedPreferences sp = getSharedPreferences(PREF_NAME,
Context.MODE_WORLD_WRITEABLE);
// 讀取之前保存的數據
String content = sp.getString(PREF_KEY, "");
// 顯示讀取的數據
displayTextView.setText(content);
}
});
}
}