Android 数据库(SharedPreferences运用)
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);
}
});
}
}
补充:移动开发 , Android ,