Android 資料庫(SharedPreferences運用)

來源:互聯網
上載者:User

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);
}
});
 
 
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.