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

news2024/10/6 18:33:33

 

要求:每种错误信息采用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",null,null,null,null,null,"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);
    }
}

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/776652.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

JQuery 实现点击按钮添加及删除 input 框

前言 用于记录开发中常用到的&#xff0c;快捷开发 需求新增功能 比如说&#xff0c;我台设备可以设置一个或多个秘钥&#xff0c;有时候我配置一个秘钥时&#xff0c;就不需要多个输入框&#xff0c;当我想配置多个秘钥时&#xff0c;就需要添加多个输入框。 实现 HTML …

Adobe打印机另存pdf出错生成log文件,打印失败

目录预览 一、问题描述二、原因分析三、解决方案四、参考链接 一、问题描述 用adobe打印机转pdf出错生成log文件,打印失败&#xff0c;log文件内容如下&#xff1a; %%[ ProductName: Distiller ]%% FZXBSJW--GB1-0 not found, using Courier. %%[ Error: typecheck; Offendi…

Mac安装MySQL详细教程

1、MySQL安装包下载 还没下载的话请前往官网下载 我们可以看到这里有两个不同架构的dmg的安装包&#xff0c;如果不知道自己电脑是ARM还是X86的话可以打开终端输入&#xff1a;uname -a 或者 uname -a | awk -F " " {print $(NF-1)} 来查看如下图&#xff1a; 这里显…

v-cloak和v-once和v-pre指令

v-cloak指令&#xff08;没有值&#xff09;&#xff1a; 1.本质是一个特殊属性&#xff0c;Vue实例创建完毕并接管容器后&#xff0c;会删掉v-cloak属性。 2.使用css配合v-cloak可以解决网速慢时页面展示出{{xxx}}的问题 v-once: v-once指令&#xff1a; 1.v-once所在节点在初…

基于linux下的高并发服务器开发(第一章)- Linux开发环境搭建

​​​​​​基于linux下的高并发服务器开发&#xff08;第一章&#xff09;-Linux环境开发搭建1.1_呵呵哒(&#xffe3;▽&#xffe3;)"的博客-CSDN博客https://blog.csdn.net/weixin_41987016/article/details/131681333?spm1001.2014.3001.5501 解决Ubuntu 虚拟机没…

高数笔记01:函数、极限、连续

图源&#xff1a;文心一言 本文是我学习高等数学第一章的一些笔记和心得&#xff0c;主要介绍了函数、极限、连续这三个基本概念&#xff0c;以及它们的性质和很基础的计算技巧。希望可以与考研路上的小伙伴一起努力上岸~~&#x1f95d;&#x1f95d; 第1版&#xff1a;查资料…

Python自动化测试之cookie绕过登录(保持登录状态)

前言 在编写接口自动化测试用例或其他脚本的过程中&#xff0c;经常会遇到需要绕过用户名/密码或验证码登录&#xff0c;去请求接口的情况&#xff0c;一是因为有时验证码会比较复杂&#xff0c;比如有些图形验证码&#xff0c;难以通过接口的方式去处理&#xff1b;再者&…

系统学习Halcon视觉软件指南

要系统学习Halcon视觉软件&#xff0c;您可以按照以下步骤进行&#xff1a; 我这里刚好有嵌入式、单片机、plc的资料需要可以私我或在评论区扣个6 学习基本概念&#xff1a;了解Halcon的基本概念和术语&#xff0c;例如图像处理、特征提取、图像匹配等。可以查阅Halcon的官方…

Web开发的富文本编辑器CKEditor介绍,Django有库ckeditor_uploader对它进行支持,django-ckeditor安装方法及使用注意事项

当需要在网页应用程序中提供富文本编辑功能时&#xff0c;CKEditor是一个流行的选择。CKEditor是一个开源的JavaScript富文本编辑器&#xff0c;它提供了强大的功能和用户友好的界面&#xff0c;使用户可以轻松创建和编辑格式化的文本内容。 以下是CKEditor的一些主要特性&…

MySQL进阶:函数

​ 在MySQL中&#xff0c;为了提高代码重用性和隐藏实现细节&#xff0c;MySQL提供了很多函数。函数可以理解为别人封装好的模板代码。 一、聚合函数 ​ 在MySQL中&#xff0c;聚合函数主要由&#xff1a;count、sum、min、max、avg组成&#xff0c;这些函数前面已经提过&…

std::stox类型

std::stod 函数原型 double stod (const string& str, size_t* idx 0); double stod (const wstring& str, size_t* idx 0);函数功能 将std::string字符串转化为双精度类型 函数参数 str 待转换的字符串 idx 如果idx的指针不为空&#xff0c;则该函数会将idx的…

为什么计算ORB特征点的时候还要取圆形而不是方形像素区域呢?

ORB (Oriented FAST and Rotated BRIEF)是一种在计算机视觉中广泛应用的特征检测和描述符算法。它的设计目的是为了快速、有效地提取图像中的关键点和描述符。在ORB的过程中&#xff0c;确实会涉及到提取圆形区域的操作&#xff0c;这主要出于以下的原因&#xff1a; 旋转不变性…

C++ VS 链接第三方库

C VS 链接第三方库 include lib dll 需要把动态库考到可执行程序的目录之下

客户异常数据清洗详细教程——pandas

前言 在不同行业中&#xff0c;我们经常会遇到一个麻烦的问题&#xff1a;数据清洗。尤其是当我们需要处理客户编码异常数据时&#xff0c;这个问题变得尤为重要。想象一下&#xff0c;许多银行都是以客户为单位管理数据的&#xff0c;因此每个客户都有一个独特的编码。在处理…

浅谈医院综合电气管理与节能措施

摘要&#xff1a;随着我国经济建设的不断加快&#xff0c;我国能源消耗也越来越大&#xff0c;如何通过电气能源管理实现节能是各行各业都在研究的课题。医院作为我国重要的医疗服务机构&#xff0c;能源管理是医院管理中的重要组成部分。本文将针对医院电气能源管理与节能措施…

关于Qt For android第一次编译时出现的问题

搞了三四天&#xff0c;搞的快崩溃了&#xff0c;问题提示为 FAILURE: Build failed with an exception.* What went wrong: A problem occurred configuring root project android-build. > Could not resolve all artifacts for configuration :classpath.> Could not…

53从零开始学Java之Integer底层原理探究

作者&#xff1a;孙玉昌&#xff0c;昵称【一一哥】&#xff0c;另外【壹壹哥】也是我哦 千锋教育高级教研员、CSDN博客专家、万粉博主、阿里云专家博主、掘金优质作者 前言 在之前的两篇文章中&#xff0c;壹哥给大家介绍了Java中的包装类及其特点、用法&#xff0c;但是这些…

正则表达式——Java

1、简介 正则表达式&#xff08;Regular Expression&#xff09;又称正规表示法、常规表示法&#xff0c;在代码中常简写为 regex、regexp 或 RE&#xff0c;它是计算机科学的一个概念。 String 类里也提供了如下几个特殊的方法。 boolean matches(String regex)&#xff1a…

小研究 - 面向 Java 的高对抗内存型 Webshell 检测技术(四)

由于 Web 应用程序的复杂性和重要性, 导致其成为网络攻击的主要目标之一。攻击者在入侵一个网站后, 通常会植入一个 Webshell, 来持久化控制网站。但随着攻防双方的博弈, 各种检测技术、终端安全产品被广泛应用, 使得传统的以文件形式驻留的 Webshell 越来越容易被检测到, 内存…

视频做成GIF动图怎么做?分享超简单的制作方法

将视频制作GIF动图的好处在于它可以将原本较长的视频压缩成一个简短、易于分享的图像文件。这使得它们非常适合用于社交媒体、博客、电子邮件等场景&#xff0c;可以当做表情包来使用&#xff0c;尤其是看到一段搞笑的视频&#xff0c;想要把它做成GIF动图该怎么做呢&#xff1…