【Android】入手练习——登录注册

130 阅读1分钟

本文已参加[新人创作礼]活动,一起开启掘金创作之路​ ​

 提前准备的资源

​shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#446e9cf9" />
    <corners android:radius="30dip" />
</shape>

 

 Android-studio

1.新建项目

2.新建活动register

3.activity_register

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:gravity="center"
    android:orientation="vertical"
    android:background="@drawable/dlbj">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="125dp"
            android:layout_height="50dp"
            android:text="注  册"
            android:gravity="center"
            android:textColor="#3333FF"
            android:textSize="20sp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"/>

    <EditText
        android:id="@+id/username"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:hint="用户名"
        android:textColorHint="#FF0000"
        />

    <EditText
        android:id="@+id/userpassword"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:hint="密 码"
        android:textColorHint="#FF0000"


        />
    <EditText
        android:id="@+id/confirmpassword"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:hint="确认密码"
        android:textColorHint="#FF0000"


        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"/>

    <Button
        android:id="@+id/button"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:background="@drawable/shape"
        android:text="注册"
        android:textSize="17sp"
        tools:ignore="TouchTargetSizeCheck" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:background="@drawable/shape"
        android:text="去登录"
        android:textSize="17sp"
        tools:ignore="TouchTargetSizeCheck" />


</LinearLayout>

4.register.Java

package com.example.yourhousekeeper;

import androidx.appcompat.app.AppCompatActivity;

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

public class Register extends AppCompatActivity {
    Button register_btn, tologin;
    EditText username, userpassword, confirmpassword;
    DBOperation db;
    SharedPreferences sharedPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        db = new DBOperation(Register.this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        register_btn = findViewById(R.id.button);
        tologin = findViewById(R.id.button2);
        username = findViewById(R.id.username);
        userpassword = findViewById(R.id.userpassword);
        confirmpassword = findViewById(R.id.confirmpassword);

        register_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PersonInfo personInfo = db.queryStu(username.getText().toString());
                if (personInfo.getName() == null) {
                    if (confirmpassword.getText().toString().equals(userpassword.getText().toString())) {
                        db.insertStu(username.getText().toString(), userpassword.getText().toString());
                        sharedPreferences=getSharedPreferences("person",MODE_PRIVATE);
                        String username = sharedPreferences.getString("username", null);
                        String paassword = sharedPreferences.getString("paassword", null);
                        SharedPreferences.Editor editor=sharedPreferences.edit();
                        if (username!=null){
                            editor.remove("username");
                            editor.remove("password");
                            editor.commit();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_SHORT).show();
                    }
                } else{
                    Toast.makeText(getApplicationContext(), "该用户名已被注册", Toast.LENGTH_SHORT).show();
                }


            }
        });
        tologin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(Register.this, MainActivity.class));
            }
        });
    }
}

5.这时就需要三个个新的Java类了

基本的DBManager.java

package com.example.yourhousekeeper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class DBManager extends SQLiteOpenHelper {

    public static final String DB_NAME = "se2022.db";
    public static final int DB_VERSION = 1;

    public static final String TABLE_STU = "student";
    public static final String CREATE_STU = "create table "+TABLE_STU
            +" (name string primary key,password string);";

    public static final String DROP_STU = "drop table if exists "+TABLE_STU;

    // 上下文:我在哪个线程,web中常用于资源目录定位
    private Context context;

    //TABLE_STU,   DBManager.TABLE_STU

    public DBManager(Context context) {
        //创建数据库
        super(context, DB_NAME, null, DB_VERSION);
        this.context = context;
        Toast.makeText(context, "数据库已创建", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(CREATE_STU);
            Toast.makeText(context, "table已创建", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Log.e("ERROOOR",e.toString());
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        try {
            db.execSQL(DROP_STU);
            onCreate(db);
            Toast.makeText(context, "数据库已更新", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Log.e("ERROOOR",e.toString());
        }
    }
}

PersonInfo.java

package com.example.yourhousekeeper;

public class PersonInfo {
    private String name;
    private String password;

    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 "PersonInfo{" +
                "name='" + name + ''' +
                ", password='" + password + ''' +
                '}';
    }
}

DBOperation.java

package com.example.yourhousekeeper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class DBOperation {
    public DBManager dbManager;
    public SQLiteDatabase db;
    private Context context;

    public DBOperation(Context context) {
        dbManager = new DBManager(context);
        this.context = context;
    }

    public long insertStu(String name, String password) {
        //获取SQLiteOpenhelper创建的数据库
        db = dbManager.getWritableDatabase();

        ContentValues cv = new ContentValues();
        cv.put("name", name);
        cv.put("password", password);

        long line = db.insert(DBManager.TABLE_STU, null, cv);
        Toast.makeText(context, String.valueOf(line), Toast.LENGTH_SHORT).show();

        db.close();
        return line;
    }

    public List<PersonInfo> getAll() {
        db = dbManager.getWritableDatabase();

        ArrayList<PersonInfo> list = new ArrayList<>();
        Cursor rs = db.query(DBManager.TABLE_STU, new String[]{"name", "password"}, null, null, null, null, null);
        while (rs.moveToNext()) {
            PersonInfo personInfo=new PersonInfo();
            String data = "[name]: " + rs.getString(0)+ " [password]: " + rs.getString(1);
            personInfo.setName(rs.getString(0));
            personInfo.setPassword(rs.getString(1));
            list.add(personInfo);
        }
        rs.close();
        db.close();
        return list;
    }

    public void updateStu( String name, String password) {
        db = dbManager.getWritableDatabase();
        String sql = "update student set password=? where name=?";
        SQLiteStatement statement = db.compileStatement(sql);
        statement.bindString(1, password);
        statement.bindString(2, name);
        int line = statement.executeUpdateDelete();
        Toast.makeText(context, String.valueOf(line), Toast.LENGTH_SHORT).show();
    }

    // 替换为动态SQL
    public PersonInfo queryRowStu(String name, String password) {
        PersonInfo personInfo=new PersonInfo();
        db = dbManager.getWritableDatabase();
        String sql = "select * from student where name=? and password=?";
        Cursor cursor = db.rawQuery(sql, new String[]{name, password});
        while (cursor.moveToNext()) {
            personInfo.setName(cursor.getString(0));
            personInfo.setPassword(cursor.getString(1));
        }
        db.close();
        return personInfo;
    }
    public PersonInfo queryStu(String name) {
        PersonInfo personInfo=new PersonInfo();
        db = dbManager.getWritableDatabase();
        String sql = "select * from student where name=?";
        Cursor cursor = db.rawQuery(sql, new String[]{name});
        while (cursor.moveToNext()) {
            personInfo.setName(cursor.getString(0));
        }
        Toast.makeText(context,personInfo.toString(),Toast.LENGTH_LONG).show();
        return personInfo;
    }
    public void deleteStu(String username) {
        int line = db.delete("student", "name=?", new String[]{username});
        if (line > 0)
            Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
    }
}

6.activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:gravity="center"
    android:orientation="vertical"
    android:background="@drawable/dlbj">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="125dp"
            android:layout_height="50dp"
            android:text="登 录"
            android:gravity="center"
            android:textColor="#3333FF"
            android:textSize="20sp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"/>

    <EditText
        android:id="@+id/editTextTextPersonName"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:hint="用户名"
        android:textColorHint="#FF0000"
        />

    <EditText
        android:id="@+id/editTextTextPassword"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:hint="密 码"
        android:textColorHint="#FF0000"


        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"/>

    <Button
        android:id="@+id/button3"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:background="@drawable/shape"
        android:text="登  录"
        android:textSize="17sp"
        tools:ignore="TouchTargetSizeCheck" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"/>

    <Button
        android:id="@+id/button5"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:background="@drawable/shape"
        android:text="去注册"
        android:textSize="17sp"
        tools:ignore="TouchTargetSizeCheck" />


</LinearLayout>

7.MainActivity.java

package com.example.yourhousekeeper;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText editTextTextPersonName, editTextTextPassword;
    Button button5_toreg, button3_login;
    SharedPreferences sharedPreferences;

    DBOperation db;
    static Integer i=1;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        button3_login = findViewById(R.id.button3);
        button5_toreg = findViewById(R.id.button5);
        editTextTextPassword = findViewById(R.id.editTextTextPassword);
        editTextTextPersonName = findViewById(R.id.editTextTextPersonName);
        sharedPreferences = getSharedPreferences("person", MODE_PRIVATE);
        db = new DBOperation(MainActivity.this);
        String username = sharedPreferences.getString("username", null);
        String password = sharedPreferences.getString("password", null);
//        boolean pressed = button5_toreg.isPressed();
//        boolean pressed1 = button3_login.isPressed();


        if (username != null) {
            editTextTextPersonName.setText(username);
            editTextTextPassword.setText(password);
//            button5_toreg.setEnabled(false);
//            button3_login.setEnabled(true);
            if (db.queryRowStu(username,password).getName()==null){
                Toast.makeText(MainActivity.this,"密码已更新请自己登录",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(MainActivity.this,"即将登录",Toast.LENGTH_LONG).show();
                Intent intent = new Intent(MainActivity.this, Menu.class);
                startActivity(intent);
            }


//          Toast.makeText(getApplicationContext(),String.valueOf(pressed)+String.valueOf(pressed1),Toast.LENGTH_LONG).show();

        }
        button5_toreg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                MainActivity mainActivity=new MainActivity();
                MainActivity.i=0;
                Intent intent = new Intent(MainActivity.this, Register.class);
                startActivity(intent);
            }
        });

        button3_login.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {
                MainActivity mainActivity=new MainActivity();
                MainActivity.i=0;
                if (editTextTextPassword.getText().toString() == null || editTextTextPersonName.getText().toString() == null) {
                    Toast.makeText(MainActivity.this, "登录错误", Toast.LENGTH_LONG).show();
                } else {
                    PersonInfo personInfo = db.queryRowStu(editTextTextPersonName.getText().toString(), editTextTextPassword.getText().toString());
                    if (personInfo.getName()==null) {
                        Toast.makeText(MainActivity.this, "密码或用户名出错", Toast.LENGTH_LONG).show();
                    } else {
                        SharedPreferences.Editor editor=sharedPreferences.edit();
                        if (username!=null){
                            editor.remove("username");
                            editor.remove("password");
                            editor.commit();
                        }
                        editor.putString("username",editTextTextPersonName.getText().toString());
                        editor.putString("password",editTextTextPassword.getText().toString());
                        editor.commit();
                        Intent intent = new Intent(MainActivity.this, Menu.class);
                        intent.putExtra("user", personInfo.getName() + personInfo.getPassword());
                        startActivity(intent);
                    }

                }
            }
        });
        MainActivity mainActivity=new MainActivity();
        Log.i("MSG",String.valueOf(this.i));

    }
}

8.这是,需要你登录完的跳转页面,我这里是Home

也是一个活动哦

空活动,写你应用的主页面以及相关活动

Home.java

package com.example.yourhousekeeper;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class Home extends AppCompatActivity {

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

activity_home

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".Home">

</androidx.constraintlayout.widget.ConstraintLayout>

​