Android 養成記-1--1.1 登入註冊
阿新 • • 發佈:2018-12-04
首先,上圖看效果:
接下來是看如何實現。
1,loginActivity
/** * 登入介面 */ public class LoginActivity extends Activity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { //佈局內的控制元件 private EditText et_name; private EditText et_password; private Button mLoginBtn; private Button mRegisterBtn; private CheckBox checkBox_password; private CheckBox checkBox_login; private ImageView iv_see_password; static String currentLoginCount = ""; static String currentpassword = ""; private LoadingDialog mLoadingDialog; //顯示正在載入的對話方塊 private UserDataManager mUserDataManager; //使用者資料管理類 /* private static final String DATABASE_NAME = "Mydb"; private static final String TABLE_NAME = "MyLoginDB"; private SQLiteDatabase sqlDB; public static final String ID = "_id"; public static final String USERID = "customName"; public static final String PASSWORD = "password";*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initViews(); setupEvents(); initData(); if (mUserDataManager == null) { mUserDataManager = new UserDataManager(this); mUserDataManager.openDataBase(); //建立本地資料庫 } // sqlDB = openOrCreateDatabase(DATABASE_NAME,SQLiteDatabase.CREATE_IF_NECESSARY,null); /* * 初始化資料庫 */ // sqlDB.execSQL("drop table if exists "+TABLE_NAME );//刪除資料庫中的表 //sqlDB.execSQL("DELETE FROM " + TABLE_NAME);//刪除表中所有資料但保留表 // Toast.makeText(getApplicationContext(),"資料庫建立成功",Toast.LENGTH_SHORT).show(); /* try { sqlDB.execSQL("create table " + TABLE_NAME + " ( "+ ID + " integer primary key,"+ USERID + " varchar,"+ PASSWORD+ " varchar "+ ")"); }catch(Exception e){ //Toast.makeText(getApplicationContext(),"表格已經存在",Toast.LENGTH_SHORT).show(); }*/ } private void initData() { //判斷使用者第一次登陸 if (firstLogin()) { checkBox_password.setChecked(false);//取消記住密碼的複選框 checkBox_login.setChecked(false);//取消自動登入的複選框 } //判斷是否記住密碼 if (remenberPassword()) { checkBox_password.setChecked(true);//勾選記住密碼 setTextNameAndPassword();//把密碼和賬號輸入到輸入框中 } else { setTextName();//把使用者賬號放到輸入賬號的輸入框中 } //判斷是否自動登入 if (autoLogin()) { checkBox_login.setChecked(true); login();//去登入就可以 } } /** * 把本地儲存的資料設定資料到輸入框中 */ public void setTextNameAndPassword() { et_name.setText("" + getLocalName()); et_password.setText("" + getLocalPassword()); } /** * 設定資料到輸入框中 */ public void setTextName() { et_name.setText("" + getLocalName()); } /** * 獲得儲存在本地的使用者名稱 */ public String getLocalName() { //獲取SharedPreferences物件,使用自定義類的方法來獲取物件 SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting"); String name = helper.getString("name"); return name; } /** * 獲得儲存在本地的密碼 */ public String getLocalPassword() { //獲取SharedPreferences物件,使用自定義類的方法來獲取物件 SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting"); String password = helper.getString("password"); return Base64Utils.decryptBASE64(password); //解碼一下 // return password; //解碼一下 } /** * 判斷是否自動登入 */ private boolean autoLogin() { //獲取SharedPreferences物件,使用自定義類的方法來獲取物件 SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting"); boolean autoLogin = helper.getBoolean("autoLogin", false); return autoLogin; } /** * 判斷是否記住密碼 */ private boolean remenberPassword() { //獲取SharedPreferences物件,使用自定義類的方法來獲取物件 SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting"); boolean remenberPassword = helper.getBoolean("remenberPassword", false); return remenberPassword; } private void initViews() { mLoginBtn = (Button) findViewById(R.id.btn_login); mRegisterBtn = (Button) findViewById(R.id.btn_register); et_name = (EditText) findViewById(R.id.et_account); et_password = (EditText) findViewById(R.id.et_password); checkBox_password = (CheckBox) findViewById(R.id.checkBox_password); checkBox_login = (CheckBox) findViewById(R.id.checkBox_login); iv_see_password = (ImageView) findViewById(R.id.iv_see_password); } private void setupEvents() { mLoginBtn.setOnClickListener(this); mRegisterBtn.setOnClickListener(this); checkBox_password.setOnCheckedChangeListener(this); checkBox_login.setOnCheckedChangeListener(this); iv_see_password.setOnClickListener(this); } /** * 判斷是否是第一次登陸 */ private boolean firstLogin() { //獲取SharedPreferences物件,使用自定義類的方法來獲取物件 SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting"); boolean first = helper.getBoolean("first", true); if (first) { //建立一個ContentVa物件(自定義的)設定不是第一次登入,,並建立記住密碼和自動登入是預設不選,建立賬號和密碼為空 helper.putValues(new SharedPreferencesUtils.ContentValue("first", false), new SharedPreferencesUtils.ContentValue("remenberPassword", false), new SharedPreferencesUtils.ContentValue("autoLogin", false), new SharedPreferencesUtils.ContentValue("name", ""), new SharedPreferencesUtils.ContentValue("password", "")); return true; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_login: loadUserName(); //無論如何儲存一下使用者名稱 login(); //登陸 break; case R.id.iv_see_password: setPasswordVisibility(); //改變圖片並設定輸入框的文字可見或不可見 break; case R.id.btn_register: startActivity(new Intent(this,RegisterActivity.class)); finish(); break; } } private void login() { //先做一些基本的判斷,比如輸入的使用者命為空,密碼為空,網路不可用多大情況,都不需要去連結伺服器了,而是直接返回提示錯誤 if (getAccount().isEmpty()){ showToast("你輸入的賬號為空!"); return; } if (getPassword().isEmpty()){ showToast("你輸入的密碼為空!"); return; } //showToast(getAccount()); /* if (!user(getAccount())){ showToast("賬戶不存在"); return; }*/ //登入一般都是請求伺服器來判斷密碼是否正確,要請求網路,要子執行緒 showLoading();//顯示載入框 Thread loginRunnable = new Thread() { @Override public void run() { super.run(); setLoginBtnClickable(false);//點選登入後,設定登入按鈕不可點選狀態 if (!isUserNameAndPwdValid()){ return ; } currentLoginCount = getAccount(); int result=mUserDataManager.findUserByNameAndPwd(getAccount(), getPassword()); if(result==1){ //返回1說明使用者名稱和密碼均正確 startActivity(new Intent(LoginActivity.this, MainActivity.class)); finish(); showToast(getString(R.string.login_success));//登入成功提示 }else if(result==0){ showToast(getString(R.string.login_fail)); //登入失敗提示 } setLoginBtnClickable(true); //這裡解放登入按鈕,設定為可以點選 hideLoading();//隱藏載入框 } }; loginRunnable.start(); } private boolean isUserNameAndPwdValid() { //showToast(userName.getText().toString().trim()); if (getAccount().equals("")) { showToast(getString(R.string.account_empty)); return false; } else if (getPassword().equals("")) { showToast(getString(R.string.pwd_empty)); return false; } return true; } /* * 查詢資料庫看賬號是否已經註冊過了 */ /* private boolean user(String username) { Cursor cur = sqlDB.query(TABLE_NAME, null, USERID+"=?", new String[] { username }, null, null, null); while (cur.moveToNext()) { String user = cur.getString(1); Log.v("db_query", user); if (user.equals(username)) { return true; } else return false; } return false; }*/ /** * 儲存使用者賬號 */ public void loadUserName() { if (!getAccount().equals("") || !getAccount().equals("請輸入登入賬號")) { SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting"); helper.putValues(new SharedPreferencesUtils.ContentValue("name", getAccount())); } } /** * 設定密碼可見和不可見的相互轉換 */ private void setPasswordVisibility() { if (iv_see_password.isSelected()) { iv_see_password.setSelected(false); //密碼不可見 et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } else { iv_see_password.setSelected(true); //密碼可見 et_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } } /** * 獲取賬號 */ public String getAccount() { return et_name.getText().toString().trim();//去掉空格 } /** * 獲取密碼 */ public String getPassword() { return et_password.getText().toString().trim();//去掉空格 } /** * 儲存使用者選擇“記住密碼”和“自動登陸”的狀態 */ private void loadCheckBoxState() { loadCheckBoxState(checkBox_password, checkBox_login); } /** * 儲存按鈕的狀態值 */ public void loadCheckBoxState(CheckBox checkBox_password, CheckBox checkBox_login) { //獲取SharedPreferences物件,使用自定義類的方法來獲取物件 SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting"); //如果設定自動登入 if (checkBox_login.isChecked()) { //建立記住密碼和自動登入是都選擇,儲存密碼資料 helper.putValues( new SharedPreferencesUtils.ContentValue("remenberPassword", true), new SharedPreferencesUtils.ContentValue("autoLogin", true), new SharedPreferencesUtils.ContentValue("password", Base64Utils.encryptBASE64(getPassword()))); } else if (!checkBox_password.isChecked()) { //如果沒有儲存密碼,那麼自動登入也是不選的 //建立記住密碼和自動登入是預設不選,密碼為空 helper.putValues( new SharedPreferencesUtils.ContentValue("remenberPassword", false), new SharedPreferencesUtils.ContentValue("autoLogin", false), new SharedPreferencesUtils.ContentValue("password", "")); } else if (checkBox_password.isChecked()) { //如果儲存密碼,沒有自動登入 //建立記住密碼為選中和自動登入是預設不選,儲存密碼資料 helper.putValues( new SharedPreferencesUtils.ContentValue("remenberPassword", true), new SharedPreferencesUtils.ContentValue("autoLogin", false), new SharedPreferencesUtils.ContentValue("password", Base64Utils.encryptBASE64(getPassword()))); } } /** * 是否可以點選登入按鈕 * * @param clickable */ public void setLoginBtnClickable(boolean clickable) { mLoginBtn.setClickable(clickable); } /** * 顯示載入的進度款 */ public void showLoading() { if (mLoadingDialog == null) { mLoadingDialog = new LoadingDialog(this, getString(R.string.loading), false); } mLoadingDialog.show(); } /** * 隱藏載入的進度框 */ public void hideLoading() { if (mLoadingDialog != null) { runOnUiThread(new Runnable() { @Override public void run() { mLoadingDialog.hide(); } }); } } /** * CheckBox點選時的回撥方法 ,不管是勾選還是取消勾選都會得到回撥 * * @param buttonView 按鈕物件 * @param isChecked 按鈕的狀態 */ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView == checkBox_password) { //記住密碼選框發生改變時 if (!isChecked) { //如果取消“記住密碼”,那麼同樣取消自動登陸 checkBox_login.setChecked(false); } } else if (buttonView == checkBox_login) { //自動登陸選框發生改變時 if (isChecked) { //如果選擇“自動登入”,那麼同樣選中“記住密碼” checkBox_password.setChecked(true); } } } /** * 監聽回退鍵 */ @Override public void onBackPressed() { if (mLoadingDialog != null) { if (mLoadingDialog.isShowing()) { mLoadingDialog.cancel(); } else { finish(); } } else { finish(); } } /** * 頁面銷燬前回調的方法 */ @Override protected void onDestroy() { if (mLoadingDialog != null) { mLoadingDialog.cancel(); mLoadingDialog = null; } super.onDestroy(); } public void showToast(final String msg) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); } }
2, registerActivity的實現:
/* *註冊介面 */ public class RegisterActivity extends Activity { EditText userName; EditText userPwd; EditText repeat; Button register; Button login; private UserDataManager mUserDataManager; //使用者資料管理類 /** * 正則匹配: * [a-zA-Z]:字母開頭 * \\w :可包含大小寫字母,數字,下劃線,@ * {5,17} 5到17位,加上開頭字母 字串長度6到18 */ private String userIdFromat = "[a-zA-Z](@?+\\w){4,16}+"; //加入正則匹配 /** * 正則匹配 * \\w{6,18}匹配所有字母、數字、下劃線 字串長度6到18(不含空格) */ private String userPwdFormat = "\\w{6,18}+"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); userName = (EditText)findViewById(R.id.editText3); userPwd = (EditText)findViewById(R.id.editText4); repeat = (EditText)findViewById(R.id.editText5); register = (Button)findViewById(R.id.button3); login = (Button)findViewById(R.id.button4); if (mUserDataManager == null) { mUserDataManager = new UserDataManager(this); mUserDataManager.openDataBase(); //建立本地資料庫 } register.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { if (!isUserNameAndPwdValid()){ return ; } //檢查使用者是否存在 int count=mUserDataManager.findUserByName(userName.getText().toString()); //使用者已經存在時返回,給出提示文字 if(count>0){ showToast(getString(R.string.name_already_exist)); return ; } if (!userName.getText().toString().matches(userPwdFormat)){ showToast(getString(R.string.wrong_usename_format)); return ; } if (!userPwd.getText().toString().matches(userPwdFormat)){ showToast(getString(R.string.wrong_pwd_format)); return ; } if(userPwd.getText().toString().equals(repeat.getText().toString())==false){ //兩次密碼輸入不一樣 showToast(getString(R.string.pwd_not_the_same)); return ; } else { UserData mUser = new UserData(userName.getText().toString(), userPwd.getText().toString()); mUserDataManager.openDataBase(); long flag = mUserDataManager.insertUserData(mUser); //新建使用者資訊 if (flag == -1) { showToast(getString(R.string.register_fail)); }else{ showToast(getString(R.string.register_success)); Intent intent_Register_to_Login = new Intent(getApplicationContext(),LoginActivity.class) ; //切換User Activity至Login Activity startActivity(intent_Register_to_Login); finish(); } } } /*boolean isNameExist =user(userName.getText().toString()); if(!isNameExist && !userName.getText().toString().equals("") && !userPwd.getText().toString().equals("") && !repeat.getText().toString().equals("")) { if (userName.getText().toString().matches(userIdFromat)) { if(repeat.getText().toString().equals(userPwd.getText().toString())){ Log.v("register", userPwd.getText().toString().matches(userPwdFormat) +""); if (userPwd.getText().toString().matches(userPwdFormat)){ ContentValues cv = new ContentValues(); cv.put(USERID, userName.getText().toString()); cv.put(userPwd, userPwd.getText().toString()); sqlDB.insertOrThrow(TABLE_NAME,null,cv); Intent i = new Intent(getApplicationContext(),LoginActivity.class); startActivity(i); Toast.makeText(getApplicationContext(),"註冊成功,請登入",Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(getApplicationContext(),"請輸入6-18位密碼,可包含數字,字母下劃線",Toast.LENGTH_SHORT).show(); } } else { //Toast.makeText(getApplicationContext(),id.getText().toString() +" " + userPwd.getText().toString() +" "+ repeat.getText().toString(),Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(),"兩次輸入的密碼不一致 ",Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(),"請輸入5-18位字母開頭使用者名稱,可包括數字,字母下劃線",Toast.LENGTH_SHORT).show(); } }else if (isNameExist){ Toast.makeText(getApplicationContext(),"賬戶已存在,請返回登入 ",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"輸入不能為空",Toast.LENGTH_SHORT).show(); // Toast.makeText(getApplicationContext(),id.getText().toString() +" " + userPwd.getText().toString() +" "+ repeat.getText().toString(),Toast.LENGTH_SHORT).show(); } }*/ }); login.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(getApplicationContext(),LoginActivity.class); startActivity(i); finish(); } }); } private boolean isUserNameAndPwdValid() { //showToast(userName.getText().toString().trim()); if (userName.getText().toString().trim().equals("")) { showToast(getString(R.string.account_empty)); return false; } else if (userPwd.getText().toString().trim().equals("")) { showToast(getString(R.string.pwd_empty)); return false; }else if(repeat.getText().toString().trim().equals("")) { showToast(getString(R.string.pwd_check_empty)); return false; } return true; } public void showToast(final String msg) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); } /** * 監聽回退鍵 */ @Override public void onBackPressed() { finish(); } }
3,資料庫管理
採用SQLite ,以及sharePrefermance “
public class UserDataManager { //使用者資料管理類 //一些巨集定義和宣告 private static final String TAG = "UserDataManager"; private static final String DB_NAME = "user_data"; private static final String TABLE_NAME = "users"; public static final String ID = "_id"; public static final String USER_NAME = "user_name"; public static final String USER_PWD = "user_pwd"; // public static final String SILENT = "silent"; // public static final String VIBRATE = "vibrate"; private static final int DB_VERSION = 2; private Context mContext = null; //建立使用者book表 private static final String DB_CREATE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " integer primary key," + USER_NAME + " varchar," + USER_PWD + " varchar" + ");"; private SQLiteDatabase mSQLiteDatabase = null; private DataBaseManagementHelper mDatabaseHelper = null; //DataBaseManagementHelper繼承自SQLiteOpenHelper private static class DataBaseManagementHelper extends SQLiteOpenHelper { DataBaseManagementHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.v(TAG,"db.getVersion()="+db.getVersion()); db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + ";"); db.execSQL(DB_CREATE); Log.v(TAG, "db.execSQL(DB_CREATE)"); Log.e(TAG, DB_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.v(TAG, "DataBaseManagementHelper onUpgrade"); onCreate(db); } } public UserDataManager(Context context) { mContext = context; Log.v(TAG, "UserDataManager construction!"); } //開啟資料庫 public void openDataBase() throws SQLException { mDatabaseHelper = new DataBaseManagementHelper(mContext); mSQLiteDatabase = mDatabaseHelper.getWritableDatabase(); } //關閉資料庫 public void closeDataBase() throws SQLException { mDatabaseHelper.close(); } //新增新使用者,即註冊 public long insertUserData(UserData userData) { String userName=userData.getUserName(); String userPwd=userData.getUserPwd(); ContentValues values = new ContentValues(); values.put(USER_NAME, userName); values.put(USER_PWD, userPwd); return mSQLiteDatabase.insert(TABLE_NAME, ID, values); } //更新使用者資訊,如修改密碼 public boolean updateUserData(UserData userData) { //int id = userData.getUserId(); String userName = userData.getUserName(); String userPwd = userData.getUserPwd(); ContentValues values = new ContentValues(); values.put(USER_NAME, userName); values.put(USER_PWD, userPwd); return mSQLiteDatabase.update(TABLE_NAME, values,null, null) > 0; //return mSQLiteDatabase.update(TABLE_NAME, values, ID + "=" + id, null) > 0; } // public Cursor fetchUserData(int id) throws SQLException { Cursor mCursor = mSQLiteDatabase.query(false, TABLE_NAME, null, ID + "=" + id, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } // public Cursor fetchAllUserDatas() { return mSQLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null); } //根據id刪除使用者 public boolean deleteUserData(int id) { return mSQLiteDatabase.delete(TABLE_NAME, ID + "=" + id, null) > 0; } //根據使用者名稱登出 public boolean deleteUserDatabyname(String name) { return mSQLiteDatabase.delete(TABLE_NAME, USER_NAME + "=" + name, null) > 0; } //刪除所有使用者 public boolean deleteAllUserDatas() { return mSQLiteDatabase.delete(TABLE_NAME, null, null) > 0; } // public String getStringByColumnName(String columnName, int id) { Cursor mCursor = fetchUserData(id); int columnIndex = mCursor.getColumnIndex(columnName); String columnValue = mCursor.getString(columnIndex); mCursor.close(); return columnValue; } // public boolean updateUserDataById(String columnName, int id, String columnValue) { ContentValues values = new ContentValues(); values.put(columnName, columnValue); return mSQLiteDatabase.update(TABLE_NAME, values, ID + "=" + id, null) > 0; } //根據使用者名稱找使用者,可以判斷註冊時使用者名稱是否已經存在 public int findUserByName(String userName){ Log.v(TAG,"findUserByName , userName="+userName); int result=0; Cursor cur = mSQLiteDatabase.query(TABLE_NAME, null, USER_NAME+"=?", new String[] { userName },null, null, null); while (cur.moveToNext()) { String user = cur.getString(1); Log.v("db_query", user); if (user.equals(userName)) { cur.close(); return 1; } else cur.close(); return 0; } Log.v(TAG,"findUserByName , result="+result); return result; } //根據使用者名稱和密碼找使用者,用於登入 public int findUserByNameAndPwd(String userName, String pwd){ Log.v(TAG,"findUserByNameAndPwd"); int result=0; Cursor cur = mSQLiteDatabase.query(TABLE_NAME, null, USER_NAME+"=?", new String[] { userName },null, null, null); while (cur.moveToNext()) { String user = cur.getString(2); Log.v("db_query", user); if (pwd.equals(user)) { cur.close(); return 1; } else { cur.close(); return 0; } } return result; }
最後的效果gif 圖如下:
其他資原始檔等在下面的demo裡,我就不貼出來了。歡迎下載
https://download.csdn.net/download/linzihahaha/10763892
ps:這個是我根據網上資源自己修改的,資料庫有分開dataManager 和userData,這樣方便管理,侵刪。