AndroidStudio-实现登录界面数据存储在SQLite

 

要求:每种错误信息采用Toast进行提示

(1)未注册的用户不能进行登录;

(2)用户名和密码不能为空;

(3)用户名不能重复;

一、创建新工程

 点击next

修改名字 ,language看自己情况修改,sdk最好选21,这样21之后的都可以用,location自己改,点击finish

点击左上角的Android,切换成project

创建新的activity 

 修改名字,点击finish,同样的,再创建一个注册Activity

在AndroidMainfest.xml文件中将登录界面设为主界面

<application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyLogin"
        tools:targetApi="31">
        <activity
            android:name=".Register"
            android:exported="false" />
        <activity
            android:name=".Login"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="false"/>
    </application>

二、UI界面设计

插入图片,名字只能是小写

Login:ps:复制的时候得把注释去掉

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout//线性布局
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/img"//界面背景图
    android:orientation="vertical">//布局方式,vertical为垂直布局,horizontal为水平布局
    <LinearLayout
        android:layout_marginLeft="30dp"//容器中的左边距
        android:layout_marginRight="30dp"//容器中的右边距
        android:layout_width="match_parent"//和父容器一样大小
        android:layout_height="0dp"//按比例分配大小
        android:layout_weight="1"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"//大小包裹内容
            android:orientation="horizontal">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="用户名:"
                android:layout_marginTop="30dp"//容器中的上边距
                android:textSize="25sp"//sp主要是字体大小
                android:textColor="#000000"
                android:layout_weight="1"/>
            <EditText
                android:id="@+id/userName"//如果要调用,就得加id
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:hint="请输入用户名"
                android:layout_marginTop="30dp"
                android:textSize="20sp"
                android:textColor="#2196F3"
                android:layout_weight="2"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="密码:"
                android:textSize="25sp"
                android:layout_marginTop="30dp"
                android:textColor="#000000"
                android:layout_weight="1"/>
            <EditText
                android:id="@+id/userpassword"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:hint="请输入密码"
                android:textSize="20sp"
                android:textColor="#2196F3"
                android:layout_weight="2"
                android:inputType="textWebPassword"/>
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:orientation="vertical">
        <Button
            android:id="@+id/login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="登录"
            android:textAllCaps="false"//按钮上的英文可以展现大小写,默认为true,即显示的都是大写
            android:textColor="#FFFFFF"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginTop="30dp"
            android:textSize="25sp" />
        <Button
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginTop="30dp"
            android:textSize="25sp"
            android:textColor="#FFFFFF"
            android:textAllCaps="false"
            android:text="注册"
            android:id="@+id/register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>

Register:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/img">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="用户名:"
            android:layout_marginTop="30dp"
            android:textSize="25sp"
            android:textColor="#000000"
            android:layout_weight="1"/>
        <EditText
            android:id="@+id/userName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="请输入用户名"
            android:layout_marginTop="30dp"
            android:textSize="20sp"
            android:textColor="#2196F3"
            android:layout_weight="2"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="密码:"
            android:textSize="25sp"
            android:layout_marginTop="30dp"
            android:textColor="#000000"
            android:layout_weight="1"/>
        <EditText
            android:id="@+id/userpassword"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:hint="请输入密码"
            android:textSize="20sp"
            android:textColor="#2196F3"
            android:layout_weight="2"
            android:inputType="textWebPassword"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:textColor="#000000"
            android:layout_marginTop="40dp"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:textSize="25sp"
            android:textAllCaps="false"
            android:text="确认"
            android:id="@+id/reday"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:textColor="#000000"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:textSize="25sp"
            android:textAllCaps="false"
            android:text="取消"
            android:id="@+id/back"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</LinearLayout>

三、逻辑设计

先建立数据类,建立一个只包含用户名和密码的user类。

同样,创建一个DatabaseHelper类,包含对数据库的一些基本操作(仅有创建数据库、更新数据库和数据的的插入和查询) 

User:

package com.example.mylogin;

public class User {
    private  int id;
    private  String name;
    private  String password;
    public User(String name,String password){
        super();
        this.name = name;
        this.password = password;
    }
    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;
    }
    @Override
    public String toString() {
        return "User{id ="+ id + ",name = "+ name +",password ="+password +"}";
    }
}

DatabaseHelper:

package com.example.mylogin;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {
    //创建一个数据库
    private SQLiteDatabase db;

    public DatabaseHelper(@Nullable Context context) {
        super(context,"db_test",null,1);
        db = getReadableDatabase();
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        //在第一次创建数据库的时候,创建一些字段
        String sql = "create table user(_id integer,name varchar(50),password varchar(40))";
        db.execSQL(sql);//sql语句的执行函数
    }
    @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {
        //如果这个表中存在user,我们可以先把他去掉,然后重新创建
        String sql = "DROP TABLE IF EXISTS user";
        db.execSQL(sql);
        onCreate(db);
    }
    //为使项目结构更加紧凑,我们在此类中编写增删改查的函数,因为只有登录和注册界面,因此只涉及到写入数据库insert和query的操作
    public void insert(String name,String password ){
        db.execSQL("insert into user(name,password)VALUES(?,?)",new Object[]{name,password});
    }

    public ArrayList<User> getAllDATA(){//查询数据库
        ArrayList<User> list = new ArrayList<User>();
        //查询数据库中的数据,并将这些数据按照降序的情况排列
        Cursor cursor = db.query("user","name DESC");
        while(cursor.moveToNext()){
            int index_name = cursor.getColumnIndex("name");
            int index_password = cursor.getColumnIndex("password");
            String name = cursor.getString(index_name);
            String password = cursor.getString(index_password);
            list.add(new User(name,password));
        }
        return list;
    }
}

Register部分的逻辑代码:

package com.example.mylogin;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class Register extends AppCompatActivity {

    private DatabaseHelper mSQLite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        //找到各个控件
        Button btn_ready = findViewById(R.id.reday);
        Button btn_back = findViewById(R.id.back);
        EditText ed_name = findViewById(R.id.userName);
        EditText ed_password = findViewById(R.id.userpassword);

        //注册监听事件
        btn_ready.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取输入的用户名和密码
                String name = ed_name.getText().toString().trim();
                String password = ed_password.getText().toString().trim();

                //获取数据库数据,判断用户名是否已存在
                ArrayList<User> data = mSQLite.getAllDATA();
                boolean flag = false;
                for(int i = 0; i < data.size(); i++){
                    User userdata = data.get(i);
                    if(name.equals(userdata.getName())){
                        flag = true;
                        break;
                    }else{
                        flag = false;
                    }
                }
                //判断用户名和密码是否为空
                if(!TextUtils.isEmpty(name)&&!TextUtils.isEmpty(password)){
                    if(!flag){
                        mSQLite.insert(name,password);
                        Intent intent1 = new Intent(Register.this,login.class);
                        startActivity(intent1);
                        finish();
                        Toast.makeText(Register.this,"注册成功",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        Toast.makeText(Register.this,"用户名已被注册",Toast.LENGTH_SHORT).show();
                    }
                }
                else{
                    Toast.makeText(Register.this,"用户名与密码不能为空",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //监听返回按钮
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent2 = new Intent(Register.this,login.class);
                startActivity(intent2);
                finish();
            }
        });

        mSQLite = new DatabaseHelper(Register.this);
    }
}

Login部分逻辑代码:

package com.example.mylogin;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class Login extends AppCompatActivity {

    private DatabaseHelper mSQLite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Button btn_login = findViewById(R.id.login);
        Button btn_register = findViewById(R.id.register);
        EditText ed_name = findViewById(R.id.userName);
        EditText ed_password = findViewById(R.id.userpassword);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = ed_name.getText().toString().trim();
                String password = ed_password.getText().toString().trim();

                ArrayList<User> data = mSQLite.getAllDATA();
                boolean flag = false;
                for(int i = 0; i < data.size(); i++){
                    User userdata = data.get(i);
                    if(name.equals(userdata.getName())&&password.equals(userdata.getPassword())){
                        flag = true;
                        break;
                    }else{
                        flag = false;
                    }
                }

                if(!TextUtils.isEmpty(name)&&!TextUtils.isEmpty(password)){
                    if(flag){
                        Intent intent1 = new Intent(Login.this,MainActivity.class);
                        startActivity(intent1);
                        finish();
                        Toast.makeText(Login.this,"登录成功",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        Toast.makeText(Login.this,"用户名或密码不正确",Toast.LENGTH_SHORT).show();
                    }
                }
                else{
                    Toast.makeText(Login.this,Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent2 = new Intent(Login.this,Register.class);
                startActivity(intent2);
                finish();
            }
        });
        mSQLite = new DatabaseHelper(Login.this);
    }
}

到这里就基本实现了一个登陆界面

原文地址:https://blog.csdn.net/Qmingwt

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


SQLite架构简单,又有Json计算能力,有时会承担Json文件/RESTful的计算功能,但SQLite不能直接解析Json文件/RESTful,需要用Java代码硬写,或借助第三方类库,最后再拼成insert语句插入数据表,代码非常繁琐,这里就不展示了。参考前面的代码可知,入库的过程比较麻烦,不能只用SQL,还要借助Java或命令行。SPL是现代的数据计算语言,属于简化的面向对象的语言风格,有对象的概念,可以用点号访问属性并进行多步骤计算,但没有继承重载这些内容,不算彻底的面向对象语言。...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。SQLite 源代码不受版权限制。本教程将告诉您如何使用 SQLite 编程,并让你迅速上手。.................................
安卓开发,利用SQLite实现登陆注册功能
相比大多数数据库而言,具有等优势,广泛应用于、等领域。
有时候,一个项目只有一个数据库,比如只有SQLite,或者MySQL数据库,那么我们只需要使用一个固定的数据库即可。但是一个项目如果写好了,有多个用户使用,但是多个用户使用不同的数据库,这个时候,我们就需要把软件设计成可以连接多个数据库的模式,用什么数据库,就配置什么数据库即可。4.Users实体类,这个实体类要和数据库一样的,形成一一对应的关系。11.Sqlite数据库,需要在代码里面创建数据库,建立表,再建立数据。8.我们开启MySQL数据库,然后进行调试,看程序的结果。2.安装SqlSugar。
基于Android的背单词软件,功能强大完整。
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统。说白了就是使用起来轻便简单,
Android的简单购物车案例
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库...
Qt设计较为美观好看的登录注册界面(包含SQLite数据库以及TCP通信的应用)
SQLite是用C语言开发的跨平台小型数据库,可嵌入其他开发语言,也可在单机执行。SPL是用Java开发的跨平台的数据计算语言,可嵌入Java,可在单机执行,可以数据计算服务的形式被远程调用。两者的代码都是解释执行的。...
新建库.openDATA_BASE;新建表createtableLIST_NAME(DATA);语法:NAME关键字...<用逗号分割>删除表droptableNAME;查看表.schema查看表信息新建数据insertintoLIST_NAMEvalues();语法:CLASS,PARAMETER...,CLASS是类别,PARAMETER是参数<用逗号分割新建的
importsqlite3classDemo01:def__init__(self):self.conn=sqlite3.connect("sql_demo_001.db")self.cursor1=self.conn.cursor()self.cursor1.execute("select*fromtable_001wherename=?andid=?",('ssss&#0
 在客户端配置文件<configuration>节点下,添加:<connectionStrings>      <add name="localdb" connectionString="Data Source=config/local.db;Version=3;UseUTF16Encoding=True;" providerName="System.Data.SQLite.SQLiteFactory"/&g
提到锁就不得不说到死锁的问题,而SQLite也可能出现死锁。下面举个例子:连接1:BEGIN(UNLOCKED)连接1:SELECT...(SHARED)连接1:INSERT...(RESERVED)连接2:BEGIN(UNLOCKED)连接2:SELECT...(SHARED)连接1:COMMIT(PENDING,尝试获取EXCLUSIVE锁,但还有SHARED锁未释放,返回SQLITE_BUSY)连接2:INSERT...
SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。在使用SQLite前,我们先要搞清楚几个概念:表
设计思想————首先要确定有几个页面、和每个页面的大致布局由于是入门,我也是学习了不是很长的时间,所以项目比较low。。。。第一个页面,也就是打开APP的首页面:今天这个博客,先实现添加功能!:首先对主界面进行布局:其中activity_main.xml的代码为<?xmlversion="1.0"encoding="