編輯:關於 Android 程式設計
我們日常用的 App 幾乎都有這個行為:第一次輸入帳號密碼,之後再打開就直接進首頁。QQ 那種「記住帳號」「隱身登入」的勾選,也是同一類機制。這件事其實不需要動用資料庫,SharedPreferences 就綽綽有餘。
整個流程只有兩個動作:
帳號密碼本身仍留在 SQLite 裡,SharedPreferences 只負責「要不要跳過登入」這類輕量設定。
package com.example.account.login;
import java.util.HashMap;
import java.util.Map;
import com.android.dao.MySQLiteOpenHelper;
import com.example.account.MainActivity;
import com.example.account.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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;
public class LoginActivity extends Activity {
private EditText e1, e2;
private SQLiteOpenHelper helper;
private boolean flag, flag2, flag3;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
TextView textView = (TextView) findViewById(R.id.textView1);
e1 = (EditText) findViewById(R.id.editText1);
e2 = (EditText) findViewById(R.id.editText2);
// 先讀共享參數,判斷是否需要自動登入
Map<String, Object> map = getMsg("login");
if (map != null && !map.isEmpty()) {
if (Boolean.TRUE.equals(map.get("login2"))) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
}
helper = new MySQLiteOpenHelper(this);
textView.setText("登錄界面");
Button loginButton = (Button) findViewById(R.id.button2);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (e1.getText().toString().isEmpty() || e2.getText().toString().isEmpty()) {
Toast.makeText(LoginActivity.this, "請正確輸入您的帳號密碼",
Toast.LENGTH_SHORT).show();
return;
}
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor = database.query("user",
new String[] {"username", "password"},
null, null, null, null, null);
while (cursor.moveToNext()) {
flag = e1.getText().toString()
.equals(cursor.getString(cursor.getColumnIndex("username")));
flag2 = e2.getText().toString()
.equals(cursor.getString(cursor.getColumnIndex("password")));
if (flag && flag2) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
Toast.makeText(LoginActivity.this, "登錄成功",
Toast.LENGTH_SHORT).show();
flag3 = true;
// 登入成功,寫入共享參數
Map<String, Object> newMap = new HashMap<String, Object>();
newMap.put("login2", flag3);
saveMsg("login", newMap);
}
}
if (!flag3) {
Toast.makeText(LoginActivity.this, "您輸入的帳號或密碼有誤",
Toast.LENGTH_SHORT).show();
}
}
});
Button registerButton = (Button) findViewById(R.id.button1);
registerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
}
/** 寫入共享參數 */
public boolean saveMsg(String fileName, Map<String, Object> map) {
// 一般都用 MODE_PRIVATE,比較安全
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);
}
}
return editor.commit();
}
/** 讀取共享參數,這裡用不到 edit */
public Map<String, ?> getMsg(String fileName) {
SharedPreferences preferences = getSharedPreferences(fileName, Context.MODE_APPEND);
return preferences.getAll();
}
}
saveMsg() 之所以要寫得這麼囉嗦,是因為 SharedPreferences 沒有「一次塞進一個 Map」的 API,只能逐筆判型別呼叫對應的 putXxx()。用 entrySet() 搭配 Map.Entry 的 getKey()/getValue() 走訪,是這裡最乾淨的寫法。
另外,commit() 是同步寫入並回傳成敗,apply() 則是異步、不回傳。對登入標記這種小資料,兩者都行;若在主線程寫入大量資料,記得改用 apply() 或丟到背景執行緒。
最後提醒一句:SharedPreferences 是純文字檔,把密碼明文存進去並不安全。實務上應該只存「已登入」的布林旗標或 token,密碼交給伺服器端驗證。
Android Studio 系列:項目簽名與打包全流程
前言 這篇筆記記錄一下如何用 Android Studio 對項目進行簽名打包。整體流程和 Eclipse 差別不大,但菜單層級和幾個關鍵選項的位置不太一樣,這裡把每一步
微信小惱惱一次解決:小影片與全螢幕播放設定
微信小問題可用設定解決。Android版可到設定、通用,把朋友圈小影片設為關閉或僅Wi-Fi,避免浪費行動網路。 Windows Phone看影片無法全屏,可到設定、輔助
動態添加 RadioButton 並切換 Fragment 實戰
公司項目里有這樣一個需求:從網絡獲取 JSON 數據並解析後,動態添加按鈕,點擊時切換各按鈕下存儲的對應數據。 這里僅為演示動態添加 RadioButton,所以數據直
Android 學習筆記:Activity 狀態保存與主題皮膚設定
本篇筆記整理兩個重點:Activity 的狀態保存機制,以及如何透過 android:theme 為 Activity 設定主題皮膚。 一、Activity 狀態的保存