Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

使用 SharedPreferences 實現 QQ 登入的選項記憶功能

編輯:關於 Android 程式設計

本文承接上一篇關於 SharedPreferences 基礎用法的介紹,透過一個貼近實際的登入案例,展示如何用來實現用戶名自動帶出,以及「記住密碼」與「隱身登入」等勾選選項的記憶功能。

相關程式碼如下:

package com.example.f15_sharedpreferences01;

import android.content.SharedPreferences;

import android.content.Context;

import java.util.HashMap;

import java.util.Map;

public class MainActivity extends Activity {

private Button button;

private CheckBox checkBox, checkBox2;

private EditText editText;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

button = (Button) findViewById(R.id.button1);

checkBox = (CheckBox) findViewById(R.id.checkBox1);

checkBox2 = (CheckBox) findViewById(R.id.checkBox2);

editText = (EditText) findViewById(R.id.editText1);

Map<String, ?> map = getMsg("login");

if (map != null && !map.isEmpty()) {

if (map.get("username").toString() != null && !map.get("username").toString().equals("")) {

editText.setText(map.get("username").toString());

}

checkBox.setChecked((Boolean) map.get("isname"));

checkBox2.setChecked((Boolean) map.get("ispwd"));

}

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

HashMap<String, Object> map = new HashMap<String, Object>();

if (editText.getText().toString().trim().equals("admin")) {

if (checkBox.isChecked()) {

map.put("username", editText.getText().toString().trim());

} else {

map.put("username", "");

}

map.put("isname", checkBox.isChecked());

map.put("ispwd", checkBox2.isChecked());

saveMsg("login", map);

}

}

});

}

寫入資料的方法

寫入時通常使用 MODE_PRIVATE 模式,較為安全。透過遍歷 Map 的 entrySet,並依據值的類型(Boolean、Integer、Float、Long、String)呼叫對應的 put 方法,最後以 commit() 提交:

public boolean saveMsg(String fileName, Map<String, Object> map) {

boolean flag = false;

SharedPreferences preferences = getSharedPreferences(fileName, Context.MODE_PRIVATE);

SharedPreferences.Editor editor = preferences.edit();

for (Map.Entry<String, Object> entry : map.entrySet()) {

String key = entry.getKey();

Object object = entry.getValue();

if (object instanceof Boolean) {

editor.putBoolean(key, (Boolean) object);

} else if (object instanceof Integer) {

editor.putInt(key, (Integer) object);

} else if (object instanceof Float) {

editor.putFloat(key, (Float) object);

} else if (object instanceof Long) {

editor.putLong(key, (Long) object);

} else if (object instanceof String) {

editor.putString(key, (String) object);

}

}

flag = editor.commit();

return flag;

}

讀取資料的方法

讀取時不需要 Editor,直接以 getAll() 取得全部鍵值即可:

public Map<String, ?> getMsg(String fileName) {

SharedPreferences preferences = getSharedPreferences(fileName, Context.MODE_PRIVATE);

return preferences.getAll();

}

透過以上實作,再次開啟應用時,用戶名與各勾選狀態都能被正確還原,充分體現了 SharedPreferences 作為輕量級持久化解決方案的實用價值。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved