当前位置: 移动技术网 > 移动技术>移动开发>Android > Android Studio连接SQLite数据库的登录注册实现

Android Studio连接SQLite数据库的登录注册实现

2020年06月23日  | 移动技术网移动技术  | 我要评论

1、先看一下项目目录:


2、新建一个as项目,创建如上图所示的目录结构,然后添加内容:

(1)修改添加布局文件:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.constraintlayout 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=".loginactivity">

<linearlayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <textview
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="欢迎进入登录界面!"
    android:textsize="30dp"
    android:textstyle="bold" />

  <tablelayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchcolumns="1" >

    <tablerow>

      <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="用户名:" />

      <edittext
        android:id="@+id/username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名!!!" />
    </tablerow>

    <tablerow>

      <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="密码:" />

      <edittext
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码!!!" />
    </tablerow>

    <tablerow>

      <textview />

      <linearlayout>

        <button
          android:id="@+id/login"
          android:layout_width="100dp"
          android:layout_height="wrap_content"
          android:text="登录" />

        <button
          android:id="@+id/register"
          android:layout_width="100dp"
          android:layout_height="wrap_content"
          android:text="注册" />
      </linearlayout>
    </tablerow>
  </tablelayout>
</linearlayout>
</android.support.constraint.constraintlayout>

activity_register.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.constraintlayout 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=".registeractivity">
<linearlayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <textview
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="欢迎进入注册界面!"
    android:textsize="30dp"
    android:textstyle="bold" />

  <tablelayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchcolumns="1" >

    <tablerow >

      <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="用户名:" />

      <edittext
        android:id="@+id/usernameregister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名!!!" />
    </tablerow>

    <tablerow >

      <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="密码:" />

      <edittext
        android:id="@+id/passwordregister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码!!!" />
    </tablerow>

    <tablerow >

      <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="年龄:" />

      <edittext
        android:id="@+id/ageregister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入年龄!!!" />
    </tablerow>

    <tablerow >

      <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="性别:"
        android:textsize="20dp" />

      <radiogroup
        android:id="@+id/sexregister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:checkedbutton="@+id/woman"
        android:orientation="horizontal" >

        <radiobutton
          android:id="@+id/nan"
          android:text="男"
          android:layout_height="wrap_content"
          android:layout_width="wrap_content" />

        <radiobutton
          android:id="@id/woman"
          android:text="女"
          android:layout_height="wrap_content"
          android:layout_width="wrap_content"/>
      </radiogroup>
    </tablerow>

    <tablerow >

      <textview />

      <linearlayout >
        <button
          android:id="@+id/register"
          android:layout_width="150dp"
          android:layout_height="wrap_content"
          android:text="注册" />
      </linearlayout>
    </tablerow>
  </tablelayout>

</linearlayout>
</android.support.constraint.constraintlayout>

(2)在service包databasehelper中添加链接as自带数据库以及创建表的语句:

package com.example.sqlitelogin.service;

import android.content.context;
import android.database.sqlite.sqlitedatabase;
import android.database.sqlite.sqlitedatabase.cursorfactory;
import android.database.sqlite.sqliteopenhelper;

public class databasehelper extends sqliteopenhelper {
	static string name="user.db";
	static int dbversion=1;
	public databasehelper(context context) {
		super(context, name, null, dbversion);
	}

	public void oncreate(sqlitedatabase db) {
		string sql="create table user(id integer primary key autoincrement,username varchar(20),password varchar(20),age integer,sex varchar(2))";
		db.execsql(sql);
	}
	public void onupgrade(sqlitedatabase db, int oldversion, int newversion) {

	}

}

(3)在service包userservice中用sql语句写登录注册功能的实现:

package com.example.sqlitelogin.service;

import android.content.context;
import android.database.cursor;
import android.database.sqlite.sqlitedatabase;

import com.example.sqlitelogin.user;


public class userservice {
	private databasehelper dbhelper;
	public userservice(context context){
		dbhelper=new databasehelper(context);
	}

	public boolean login(string username,string password){
		sqlitedatabase sdb=dbhelper.getreadabledatabase();
		string sql="select * from user where username=? and password=?";
		cursor cursor=sdb.rawquery(sql, new string[]{username,password});		
		if(cursor.movetofirst()==true){
			cursor.close();
			return true;
		}
		return false;
	}
	public boolean register(user user){
		sqlitedatabase sdb=dbhelper.getreadabledatabase();
		string sql="insert into user(username,password,age,sex) values(?,?,?,?)";
		object obj[]={user.getusername(),user.getpassword(),user.getage(),user.getsex()};
		sdb.execsql(sql, obj);	
		return true;
	}
}

(4)在user文件中声明要用到的表列名的变量,并对其添加get&&set方法:

package com.example.sqlitelogin;

import java.io.serializable;

public class user implements serializable{
  private int id;
  private string username;
  private string password;
  private int age;
  private string sex;
  public user() {
    super();
    // todo auto-generated constructor stub
  }
  public user(string username, string password, int age, string sex) {
    super();
    this.username = username;
    this.password = password;
    this.age = age;
    this.sex = sex;
  }
  public int getid() {
    return id;
  }
  public void setid(int id) {
    this.id = id;
  }
  public string getusername() {
    return username;
  }
  public void setusername(string username) {
    this.username = username;
  }
  public string getpassword() {
    return password;
  }
  public void setpassword(string password) {
    this.password = password;
  }
  public int getage() {
    return age;
  }
  public void setage(int age) {
    this.age = age;
  }
  public string getsex() {
    return sex;
  }
  public void setsex(string sex) {
    this.sex = sex;
  }
  @override
  public string tostring() {
    return "user [id=" + id + ", username=" + username + ", password="
        + password + ", age=" + age + ", sex=" + sex + "]";
  }

}

(5)为注册功能添加activity组件:

package com.example.sqlitelogin;

import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.widget.button;
import android.widget.edittext;
import android.widget.radiobutton;
import android.widget.radiogroup;
import android.widget.toast;

import com.example.sqlitelogin.service.userservice;

public class registeractivity extends appcompatactivity {

  edittext username;
  edittext password;
  edittext age;
  radiogroup sex;
  button register;
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_register);
    findviews();
    register.setonclicklistener(new view.onclicklistener() {
      public void onclick(view v) {
        string name=username.gettext().tostring().trim();
        string pass=password.gettext().tostring().trim();
        string agestr=age.gettext().tostring().trim();
        string sexstr=((radiobutton)registeractivity.this.findviewbyid(sex.getcheckedradiobuttonid())).gettext().tostring();
        log.i("tag",name+"_"+pass+"_"+agestr+"_"+sexstr);
        userservice uservice=new userservice(registeractivity.this);
        user user=new user();
        user.setusername(name);
        user.setpassword(pass);
        user.setage(integer.parseint(agestr));
        user.setsex(sexstr);
        uservice.register(user);
        toast.maketext(registeractivity.this, "注册成功", toast.length_long).show();
      }
    });
  }
  private void findviews() {
    username=(edittext) findviewbyid(r.id.usernameregister);
    password=(edittext) findviewbyid(r.id.passwordregister);
    age=(edittext) findviewbyid(r.id.ageregister);
    sex=(radiogroup) findviewbyid(r.id.sexregister);
    register=(button) findviewbyid(r.id.register);
  }

}

(6)为登录功能添加activity组件:

package com.example.sqlitelogin;

import android.content.intent;
import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.widget.button;
import android.widget.edittext;
import android.widget.toast;

import com.example.sqlitelogin.service.userservice;

public class loginactivity extends appcompatactivity {

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);//即activity_login.xml
    findviews();
  }
  private edittext username;
  private edittext password;
  private button login;
  private button register;

  private void findviews() {
    username=(edittext) findviewbyid(r.id.username);
    password=(edittext) findviewbyid(r.id.password);
    login=(button) findviewbyid(r.id.login);
    register=(button) findviewbyid(r.id.register);

    login.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        string name=username.gettext().tostring();
        system.out.println(name);
        string pass=password.gettext().tostring();
        system.out.println(pass);
        
        log.i("tag",name+"_"+pass);
        userservice uservice=new userservice(loginactivity.this);
        boolean flag=uservice.login(name, pass);

        if(flag){
          log.i("tag","登录成功");
          toast.maketext(loginactivity.this, "登录成功", toast.length_long).show();
          intent intent = new intent(loginactivity.this,registeractivity.class);
          startactivity(intent);
        }else{
          log.i("tag","登录失败");
          toast.maketext(loginactivity.this, "登录失败", toast.length_long).show();
        }
      }
    });
    register.setonclicklistener(new view.onclicklistener() {
      public void onclick(view v) {
        intent intent=new intent(loginactivity.this,registeractivity.class);
        startactivity(intent);
      }
    });
  }
}

3、androidmanifest.xml清单文件中,程序运行必备的内容一般都已经自动完成添加了。也可以进行修改:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.sqlitelogin">


  <application
    android:allowbackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundicon="@mipmap/ic_launcher_round"
    android:supportsrtl="true"
    android:theme="@style/apptheme">
    <activity android:name=".registeractivity">
      <!--<intent-filter>-->
        <!--<action android:name="android.intent.action.main" />-->

        <!--<category android:name="android.intent.category.launcher" />-->
      <!--</intent-filter>-->
    </activity>

    <activity android:name=".loginactivity">
      <intent-filter>
        <action android:name="android.intent.action.main"/>
        <category android:name="android.intent.category.launcher"/>
      </intent-filter>
    </activity>
    <!--<uses-library android:name="android.test.runner"/>-->
  </application>

</manifest>

4、在模拟器或者真机运行程序,即可!一个连接数据库的登录注册功能已经实现,效果如下:

补:

如果登录、注册的两个布局文件的 preview 视图标红,将 android.support.constraint.constraintlayout 替换为 linearlayout 即可

源码下载:

点击查看

查看创建的数据库以及插入的表数据:

到此这篇关于android studio连接sqlite数据库的登录注册实现的文章就介绍到这了,更多相关android studio连接sqlite内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网