Android+SQLiteOpenHelper實現登錄記住密碼小案例

實現自動登錄,在數據庫中存?注冊的賬號信息

package com.example.databases_text;import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.List;import com.example.databases_text.LoginUse.LoginDBHelper;
import com.example.databases_text.LoginUse.LoginUser;public class MainActivity extends AppCompatActivity implements View.OnClickListener ,View.OnFocusChangeListener{private EditText edit_name;private  EditText edit_password;private CheckBox cb_password;private LoginDBHelper loginDBHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);edit_password=findViewById(R.id.et_pws);edit_name=findViewById(R.id.et_name);cb_password=findViewById(R.id.cb_password);findViewById(R.id.btn_register).setOnClickListener(this);findViewById(R.id.btn_login).setOnClickListener(this);edit_password.setOnFocusChangeListener(this);}@Overrideprotected void onStart() {super.onStart();//獲得數據庫幫助器實例loginDBHelper = LoginDBHelper.getInstance(this);loginDBHelper.openWriteLink();//打開數據庫loginDBHelper.openReadLink();reload();}@Overrideprotected void onStop() {super.onStop();loginDBHelper.closeLink();}@Overrideprotected void onDestroy() {super.onDestroy();}@Overridepublic void onClick(View view) {LoginUser user = new LoginUser();String name=edit_name.getText().toString();String psw=edit_password.getText().toString();boolean cb_check=cb_password.isChecked();user.setName(name);user.setPassword(psw);user.setRemeber(cb_check);switch (view.getId()){case R.id.btn_register:if(TextUtils.isEmpty(name)|| TextUtils.isEmpty(psw)){Toast.makeText(MainActivity.this,"密碼或用戶名為空",Toast.LENGTH_SHORT).show();} else {if (user.getName().equals(loginDBHelper.queryName(name))) {Toast.makeText(this, "賬號已存在", Toast.LENGTH_SHORT).show();}else{if (loginDBHelper.registerData(user) > 0)Toast.makeText(this, "注冊成功", Toast.LENGTH_SHORT).show();}}break;case R.id.btn_login:user.setName(name);user.setPassword(psw);if(TextUtils.isEmpty(name)|| TextUtils.isEmpty(psw)){Toast.makeText(MainActivity.this,"密碼或用戶名為空",Toast.LENGTH_SHORT).show();}else {List<LoginUser> userList = loginDBHelper.queryData(user);if (userList != null &&userList.size() > 0){String username = userList.get(0).getName();String userPassword =userList.get(0).getPassword();if (user.getName().equals(username) && user.getPassword().equals(userPassword)){//注意,這里雖然都是String類型,不能直接用==來比較,因為是兩個對象,比較的是地址值,Toast.makeText(this, "登錄成功", Toast.LENGTH_SHORT).show();loginDBHelper.saveDate(user);}else{Toast.makeText(this,"用戶名或密碼錯誤",Toast.LENGTH_SHORT).show();edit_password.setText("");}}else{Toast.makeText(this,"用戶名或密碼錯誤",Toast.LENGTH_SHORT).show();}}break;}}public void reload(){LoginUser loginreload=loginDBHelper.reloadDate();if(loginreload!=null && loginreload.isRemeber()){edit_name.setText(loginreload.getName());edit_password.setText(loginreload.getPassword());cb_password.setChecked(loginreload.isRemeber());}else {edit_name.setText("");edit_password.setText("");cb_password.setChecked(false);}}@Overridepublic void onFocusChange(View view, boolean b) {if(view.getId()==R.id.et_pws && b){String x=loginDBHelper.queryPassword(edit_name.getText().toString());edit_password.setText(x);}}
}
package com.example.databases_text.LoginUse;import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;import java.util.ArrayList;
import java.util.List;import com.example.databases_text.User.User;public class LoginDBHelper extends SQLiteOpenHelper {// 數據庫版本號public static final int DATABASE_VERSION = 2;// 數據庫名稱public static final String DATABASE_NAME = "text.db";// 用戶表名public static final String TABLE_NAME = "login";// 用戶名public static final String COLUMN_NAME = "name";public static final String COLUMN_ID = "id";// 用戶密碼public static final String COLUMN_PASSWORD = "password";private static LoginDBHelper instance=null;private SQLiteDatabase mRDB=null;private SQLiteDatabase mWDB=null;public LoginDBHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}//利用單例模式,獲取數據庫的唯一實例,當數據庫不存在的時候,經行創建,如果已存在就直接返回public static LoginDBHelper getInstance(Context context){if(instance==null){instance=new LoginDBHelper(context);}return  instance;}//打開數據庫的讀連接public SQLiteDatabase openReadLink(){if(mRDB==null || !mRDB.isOpen()) {mRDB = instance.getReadableDatabase();}return mRDB;}//打開數據庫的寫連接public SQLiteDatabase openWriteLink(){if(mWDB==null || !mWDB.isOpen()) {mWDB = instance.getReadableDatabase();}return mWDB;}//數據庫的關閉操作public void closeLink() {if (mRDB != null && mRDB.isOpen()) {mRDB.close();mRDB = null;}if (mWDB != null && mWDB.isOpen()) {mWDB.close();mWDB = null;//置為空為了回收}}//創建數據庫,執行sql語句@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {String sql = "create table if not exists " + TABLE_NAME+ " ("+"id integer primary Key AUTOINCREMENT not null ," +"name VARCHAR not null,"+"password VARCHAR not null,"+"remeber INTEGER not null);";sqLiteDatabase.execSQL(sql);}@Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}//添加數據到數據庫public long registerData(LoginUser user){ContentValues values = new ContentValues();values.put("name", user.getName());values.put("pasword", user.getPassword());values.put("remeber", user.isRemeber());return   mWDB.insert(TABLE_NAME,null,values);}public long deleteData(LoginUser user){//刪除所有的return mWDB.delete(TABLE_NAME,"name=? and pasword=?",new String[]{user.getName(),user.getPassword()});}public long updateData(LoginUser user){ContentValues values = new ContentValues();values.put("name", user.getName());values.put("password", user.getPassword());values.put("remeber", user.isRemeber());//更改所有符合條件的數據return mWDB.update(TABLE_NAME,values,"name=? ",new String[]{user.getName()});}public List<LoginUser> queryData(LoginUser user){List<LoginUser> list = new ArrayList<>();//查詢所有數據,得到游標Cursor cursor =mWDB.query(TABLE_NAME,null,"name=? and pasword=?",new String[]{user.getName(),user.getPassword()},null,null,null);//逐個取出游標指向的數據while (cursor.moveToNext()){LoginUser user1=new LoginUser();user1.setName(cursor.getString(1));user1.setPassword(cursor.getString(2));list.add(user1);}return list;}public String queryPassword(String name){String cursor_password=null;//查詢所有數據,得到游標Cursor cursor =mWDB.query(TABLE_NAME,null,"name=? and remeber=1 ",new String[]{name},null,null,null);//逐個取出游標指向的數據while (cursor.moveToNext()){cursor_password=cursor.getString(2);}//取出游標指向的數據return cursor_password;}public String queryName(String name){String cuesor_name=null;//查詢所有數據,得到游標Cursor cursor =mWDB.query(TABLE_NAME,null,"name=? ",new String[]{name},null,null,null);//逐個取出游標指向的數據while (cursor.moveToNext()){cuesor_name=cursor.getString(1);}//取出游標指向的數據return cuesor_name;}//獲取追后的數據public  LoginUser reloadDate(){LoginUser loginreload=new LoginUser();String sql="select * FROM "+TABLE_NAME+" ORDER BY id DESC limit 1";Cursor cursor= mRDB.rawQuery(sql,null);if(cursor.moveToNext()) {loginreload.setId(cursor.getInt(0));loginreload.setName(cursor.getString(1));loginreload.setPassword(cursor.getString(2));boolean result = cursor.getInt(3) != 0;Log.d("TAG", "reloadDate: "+result);loginreload.setRemeber(result);}return loginreload;}public void saveDate(LoginUser loginUser){/*** 事物:若事件沒有按照正確的邏輯進行,則整件事情直接失敗*/try{mWDB.beginTransaction();//事物開始時的標志性
//進行一系列操作deleteData(loginUser);registerData(loginUser);mWDB.setTransactionSuccessful();//若一切正常,則設置事物成功的標準嗎,若不正常,則不提交}catch (Exception e){e.printStackTrace();}finally {mWDB.endTransaction();//無論是否成功,結束事物}}
}
package com.example.databases_text.LoginUse;public class LoginUser {private int id;private  String name;private String password;private  boolean remeber=false;public LoginUser() {}public LoginUser(String name, String password, boolean remeber) {this.name = name;this.password = password;this.remeber = remeber;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public boolean isRemeber() {return remeber;}public void setRemeber(boolean remeber) {this.remeber = remeber;}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"android:orientation="vertical"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="用戶名"/><EditTextandroid:id="@+id/et_name"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="密碼"/><EditTextandroid:id="@+id/et_pws"android:layout_width="match_parent"android:layout_height="wrap_content"/><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><CheckBoxandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="記住密碼"android:id="@+id/cb_password"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:text="注冊"android:id="@+id/btn_register"/><Buttonandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:text="登錄"android:id="@+id/btn_login"/></LinearLayout>
</LinearLayout>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/15200.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/15200.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/15200.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

運維行業中的堆疊交換機監控與配置管理策略

隨著信息技術的迅猛發展&#xff0c;企業網絡架構日趨復雜&#xff0c;交換機作為網絡基礎設施的核心設備&#xff0c;其穩定性和安全性對于企業業務的運行至關重要。在運維實踐中&#xff0c;堆疊交換機&#xff08;Stacked Switches&#xff09;因其高可靠性、靈活擴展性等特…

SM2258G專用SSD開卡工具(三星閃存),后附工具下載

工具下載&#xff1a; https://download.csdn.net/download/weixin_43097956/89354302

「貪心算法」檸檬水找零

力扣原題鏈接&#xff0c;點擊跳轉。 假設你的手里沒有錢。你要賣檸檬水&#xff0c;每杯5塊錢。每個顧客有可能會給你5塊錢、10塊錢或20塊錢&#xff0c;你要拿手中的錢找零。如何判斷你能否成功找零呢&#xff1f; 如果一上來就有顧客花10塊錢或20塊錢&#xff0c;你手中沒…

python中特殊的靜態方法__new__

一、關于new方法 在Python中&#xff0c;__new__方法是一個特殊的靜態方法&#xff0c;用于實例化對象。通常不需要直接調用__new__方法&#xff0c;Python會自動調用它來分配內存空間并返回一個新對象&#xff08;或者更具體地說&#xff0c;是對象的引用&#xff09;。然而&…

視頻怎么轉換成二維碼圖片?視頻做成二維碼播放的方法

怎樣在電腦上制作可以播放視頻的二維碼呢&#xff1f;很多日常生活中&#xff0c;很多的場景或者物品都會有自己的二維碼&#xff0c;其他人通過掃碼就可以獲取對應的內容。有很多場景下會把視頻轉換二維碼&#xff0c;通過掃碼在手機上查看視頻內容&#xff0c;比如產品介紹、…

水表電表遠程抄表是什么?

1.簡述&#xff1a;水表電表遠程抄表技術性 隨著時代的發展&#xff0c;傳統式手動抄表方法早已被更為高效、智能化的遠程抄表系統所替代。水表電表遠程抄表&#xff0c;說白了&#xff0c;就是利用互聯網技術完成對水表和電表讀數的遠程數據采集管理方法&#xff0c;大大提升…

效果炸裂!使用 GPT-4o 快速實現LLM OS

▼最近直播超級多&#xff0c;預約保你有收獲 —1— 什么是 LLM OS&#xff1f; 關于 LLM OS 的最初構想源自karpathy 在2023年11月11日發布的一條Twitter 動態&#xff0c;這是 LLM OS 概念的最早出處&#xff0c;如下圖所示&#xff1a; LLM OS 主要有以下5個部分組成&#x…

基于SA模擬退火優化算法的TSP問題求解matlab仿真,并對比ACO蟻群優化算法

目錄 1.程序功能描述 2.測試軟件版本以及運行結果展示 3.核心程序 4.本算法原理 5.完整程序 1.程序功能描述 基于SA模擬退火優化算法的TSP問題求解matlab仿真,并對比ACO蟻群優化算法,對比兩個算法的仿真時間&#xff0c;收斂曲線&#xff0c;以及路徑規劃的結果&#xff0…

中間件的概念及示例

什么是中間件&#xff1f; 中間件是一種軟件技術&#xff0c;它在分布式系統中起著至關重要的作用。以下是關于中間件的詳細解釋&#xff1a; 定義與位置&#xff1a; 中間件是位于應用系統和系統軟件之間的一類軟件。它使用系統軟件提供的基礎服務&#xff08;功能&#xff0…

Flask+Vue+MySQL天水麻辣燙管理系統設計與實現(附源碼 配置 文檔)

背景&#xff1a; 同學找到我期望做一個天水麻辣燙的網頁&#xff0c;想復用以前做過的課設&#xff0c;結合他的實際需求&#xff0c;讓我們來看看這個系統吧~ 項目功能與使用技術概述&#xff1a; 里面嵌入了6個子系統&#xff0c;其中餐飲系統可以進行餐館信息添加、修改…

TypeScript體操類型練習

歷史小劇場 這個世界上&#xff0c;有兩種人最痛苦&#xff0c;第一種是身居高位者&#xff0c;第二種是身居底層者&#xff0c;第一種人很少&#xff0c;第二種人很多。第一種人叫崇禎&#xff0c;第二種人叫百姓。 而最幸福的&#xff0c;就是中間那撥人&#xff0c;主要工作…

Influence blocking maximization on networks: Models, methods and applications

abstract 由于各種社會和貿易網絡的不斷出現&#xff0c;網絡影響力分析引起了研究者的極大興趣。基于不同的影響力傳播模型&#xff0c;人們提出了許多網絡影響力最大化的新模型和方法。作為傳統影響力最大化問題的延伸和擴展&#xff0c;影響力封鎖最大化問題已成為研究熱點&…

借助 CloudFlare 增強站點內容保護防采集

今天在一位站長的幫助下實測了 CloudFlare 增強站點內容保護實現防采集的功能,效果那是杠杠的,如果您的站點原創內容比較多的話,明月強烈建議試試 CloudFlare 這個內容保護,無論是 WordPress 、Typecho 都有非常好的效果,并且幾乎沒有任何誤傷,搜索引擎爬蟲蜘蛛更是不會影…

【圖論】單源最短路

前言 今天&#xff0c;我們來講最短路&#xff0c;首先看只有一個起點&#xff08;單源&#xff09;的情況。 為了書寫方便&#xff0c;我們約定以下內容&#xff1a; template<class W> using Graph vector<vector<pair<int, W>>>; // 鄰接表(ve…

集中抄表電表是什么?

1.集中抄表電表&#xff1a;簡述 集中抄表電表&#xff0c;又稱為遠程抄表系統&#xff0c;是一種現代化電力計量技術&#xff0c;為提升電力行業的經營效率和客戶服務質量。它通過自動化的形式&#xff0c;取代了傳統人工抄水表&#xff0c;完成了數據信息實時、精確、高效率…

進制轉換【野路子改造】

非科班&#xff0c;一直都是自己的野路子&#xff0c;現在要回爐重造 十進制->二進制 基本思想&#xff1a; 開始寫的&#xff08;80%&#xff09;&#xff1a; #include<stdio.h> using namespace std; int main(){ int n; scanf("%d",&n); int a[1…

Spring -- DI

文章目錄 一、什么是DI二、注入的三種方式2.1 屬性注入 Autowired使用方法Autowired存在的問題以及解決方法Autowired問題的解決方法 2.2 構造方法注入2.3 setter方法注入2.4 三種注入方式優缺點分析 一、什么是DI 概念&#xff1a;DI(依賴注入)就是當我們把依賴對象取出來(創…

以太坊錢包

以太坊錢包是你通往以太坊系統的門戶。它擁有你的密鑰&#xff0c;并且可以代表你創建和廣播交易。選擇一個以太坊錢包可能很困難&#xff0c;因為有很多不同功能和設計選擇。有些更適合初學者&#xff0c;有些更適合專家。即使你現在選擇一個你喜歡的&#xff0c;你可能會決定…

mac m1 pcre.h 找不到

安裝suricata報錯&#xff1a; configure: error: pcre.h not found ... 解決&#xff1a; brew install pcre 找到這個文件的地址 brew list pcre | grep pcre.h$ /opt/homebrew/Cellar/pcre/8.45/include/pcre.h 程序搜索的地址 cpp -v /Library/Developer/CommandLineT…

5.26 基于UDP的網絡聊天室

需求&#xff1a; 如果有人發送消息&#xff0c;其他用戶可以收到這個人的群聊信息 如果有人下線&#xff0c;其他用戶可以收到這個人的下線信息 服務器可以發送系統信息實現模型 模型&#xff1a; 代碼&#xff1a; //chatser.c -- 服務器端實現 #include <stdio.h>…