Education System APP

Registration and Login Interface Design Ideas

When we are faced with the implementation of login and registration functions, we need to design the layout of login interface and registration interface first, so that we can have a complete idea before we start to achieve better results.

We need to make a title bar, the login interface, the functional code block of the login interface, the registration interface, and the functional module of the test interface.

Learning Objectives Master the development of registration and login module, to achieve user login function.

Project Practice Register interface knowledge points

Title bar creation, ImageView, EditText, Button control use, haredPreferences use, setResult (RESULT_OK, data) method use, MD5 encryption algorithm

Skill Points Master the design and logic of the registration interface, the creation of title bar and the use of common controls

SharedPreferences is used to access data, setResult(RESULT_OK,data) is used to return data between interfaces, MD5 encryption algorithm is used to encrypt passwords and register data.

Task implementation Title bar, create title bar interface layout file, create background selector, register interface, create registration interface Activity, import picture resources into drawable, write layout file activity_register.xml, create background selector.xml, create MD5 encryption algorithm, create utils package, create MDUtils class

Register interface logic code Declare Activity private properties for manipulating controls, get interface controls, save registration information to SharedPreferences, and call init() in Activity's onCreate

Login interface Reference to title bar EditText, Button control Use of SharedPreferences setResult(RESULT_OK,data) uses Intent Use

Skill Points Master logon interface design and logical ideas Accessing data through SharedPreferences setResult(RESULT_DATA,data) method for data transfer between interfaces Actitivty Jump Through Intent

Challenge Tasks Show me the package structure Green means new additions.

Project Practice The registration interface is mainly used to enter user registration information. In the registration interface, users need to enter user name, password, password again, and register when clicking the "Registration" button.Store user information using local data and save the user name and password in SharedPrefereces after successful registration for subsequent users to log in.To ensure the security of the account, MD5 encryption algorithm is used when saving the password. This algorithm is irreversible and has some security.

title bar Right-click res/layout, new->xml-layout XML file to create main_title_bar.xml

<? XML version="1.0" encoding="utf-8"?> <!--Title bar and return key are created independently in main_title_bar.xml--> <!--Title bar is set to 50dp height, match_parent width, and background color is set to @android:color/transparent--> <!--RelativeLayout is relative layout--> <RelativeLayout xmlns:android="http://schemas.com/aproid/res/android":android="@+id/title_bar" android:layout_width="match_parent" android:layout_height="50dp" android:background="@android:color/transparent"> <!--Set the return key TextView to 50dp in height and 50dp in width; ID to android:id="@+id/tv_back"--> <!--layout_alignntLeft is left aligned with the parent control--> <!--layout_centerVertical is vertically centered for the control--> <--In the title bar interfaceThe return key of <TextView android:id="@+id/tv_back" android:layout_width="50dp" android:layout_height="50dp" android:layout_height="50dp" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:background="@drawable/go_selector"/>!--Set id:For android:id="@+id/tv_main_title--> <!!!--TextView for display text-->> <!!--layout_centerInparent for centralized display--> <TextView android:id="@+id/tv_main_title "android:layout_width="@+id/tv_main_title "android:layout_width="wrap_content wrap_content "android:layout_layout__content=""wrapap_content_content"android:textColor="@android:color/white"android:textSize="20sp"android:true:textSize=": InParent=""true:layout_Parent=""/> <!--to main_titUnder the tv_main_title button in le_bar.xml, add Save --> <TextView android:id="@+id/tv_save" android:layout_width="@+id/tv_save" android:layout_width="wrap_content" android:layout_height="30dp" android:layout_centerVertical= "true" android:layout_centerVertical= "true" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:layout_ParentParentParentParentParentParentParentParentPatroid:true"android:layout_width="true"android: android:layout_:text="Save "android:textColor="@android:color/white "android:textSize=" 16sp "/> </RelativeLayout>

Paste pictures iv_back_selected.png and iv_back.png into drawable Right mouse button drawable, new->drawable resource file, create go_back_selector.xml.

<?xml version="1.0" encoding="utf-8"?> <!--establish go_back_selector.xml Background selector--> <selector xmlns:android="http://Schemas.android.com/apk/res/android'> <!--android:state_pressed='true'for pressing, such as a button touching or tapping --> <!--gray picture when pressed (iv_back_selected.png), white picture when button pops up (iv_back.png) --> <android:drawable="@drawable/iv_back_selected"android:state_pressed="true /> <ablandroid:E="@drawable/iv_back"/> </selector>

Registration interface

Create Registration Interface Activity

Right mouse button activity package, new->activity->Empty Activity, create RegisterActivity

Import picture resources into drawable register_bg.png default_icon.png user_name_icon.png psw_icon.png register_user_name_bg.png register_psw_bg.png register_psw_again_bg.png

Write layout file activity_register.xml

<?Xml version="1.0" encoding="utf-8"?> <!--Registration interface--> <!--The layout here is to place an ImageView control for displaying the user's avatar, three EditText controls for entering the user name, password, and password again, and a Button control for registration button--> <!--Modify the activity_register.xml for LinearLayout layout--> <arLayout xmlns:android="h"Ttp://schemas.android.com/apk/res/android"android:id="@+id/activity_register"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/register_bg"android:orientation="vertical"> <include="@layout/main_title_bar"></include>!--Introduction of Title bar--> <View/Imageandroid:width="70dp"android:orientation="Ayayout_height="70dp" android:layout_gravity="center_horizontal" android:layout_marginTop="center_horizontal" android:layout_marginTop="25dp" android:src="@drawable/default_icon"/><!!!--Three editbox--> <EditText android:id= "@+id/id/et_user_name" android:layout_width="EditText android:id_level_parent" android:fill_layout_height="48dp" android:layout_gravity="center_marginTop_margin="25dp"android:src="@drawable/default_icon"/>><android:layOut_marginRight= "35dp" android:layout_marginTop= "35dp" android:layout_marginTop= "35dp" android:background= "@drawable/register_user_name_bg" android:drawableLeft= "@drawable/user_name_icon" android:drawableLeft= "@drawable/user_name_icon" android:drawablePadding= "@10dp" android:gravity= "center_vertical" android:t= "Please enter user name" android:paddingLeft= "8dp" android:singleLine= "true" android= ": troid=": textid= "000000texty000" android:textCoLorHint= "#a3a3a3" android:textSize= "14sp"/> <EditText android:id= "@+id/et_psw" android:layout_width= "fill_parent" android:layout_width= "fill_parent" android:layout_gravity= "center_horizontal" android:layout_height= "48dp" android:layout_marginLeft= "35dp" android:layout_Right margin= "35dp" android:background: register= "@able/psitText android_psw_bg" android:layout_width= "fill_parent" android:layout_width= "fill_parent" android:layout_gravity:layout Left="@drawable/psw_icon" AndroidDrawablePadding= "10dp" android:hint= "Please enter password" android:inputType= "textPassword" android:paddingLeft= "8dp" android:paddingLeft= "8dp" android:singleLine= "true" android:textColor= "#000000" android:textColorHint= "#a3a3a3" android:textSize= "14sp"/> <EditText android:inputType= "@+id/psid_again" android_psw_again"android:singleLine="8dp"android:singleLine="true"android:tex="fill_parent"android:layout_height="48dp"android:layout_graVity="center_horizontal" android:layout_marginLeft="35dp" android:layout_marginLeft="35dp" android:layout_marginRight="35dp" android:background="@drawable/register_psw_again_bg" android:drawableLeft="@drawable/psw_icon" android:drawableLeft="@drawable/psw_icon" android:drawablePadding="10dp" android:hint="Please re-enter password" android:inroid:type="Pastputsword" android:layout_marginRight="35dp" android:8dpagft="8dp" android:true true"android:tExtColor="#000000" android:textColorHint="#a3a3a3" android:textSize= "#a3a3" android:textSize= "14sp"/> <Button android:id= "@+id/btn_register" android:layout_width="fill_parent" android:layout_layout_height="40dp" android:layout_gravity="center_horizontal" android:layout_layout_Left="35dp" android:textSize="14sp"/> <Button Android android:id="@+id="@+id/id/btn_register"android:layout_="15dp"android:background="@drawab"Le/register_selector "android:text=" register "android:textColor="@android:color/white "android:textSize=" 18sp "/> </LinearLayout>

Create background selector register_selector.xml Paste register_icon_normal.png,register_icon_selected.png into drawable Create register_selector.xml in drawable

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://Schemas.android.com/apk/res/android'> <!--register_icon_normal.png is a button-click style. Click the display gray picture register_icon_selected.png--> <item android:drawable="@drawable/register_icon_selected"android:state_pressed="true /> <android:drawable="@drawable/register_icon_normal/> </selector>

MD5 Encryption Algorithm The full name of MD5 is Message_Digest Algorithm 5 (5th Edition of Information-Digest Algorithms), which simply means that a string of any length becomes a fixed-length (usually 128-bit) hexadecimal string.

Create utils package Right mouse button utils package, new->java class, create MD5Utils class

package cn.edu.gdmec.android.boxuegu.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by Jack on 2018/3/27. * Create an md5() method*getInstance() method via MessageDigest*Get the digest of the data encryption object and then encrypt the password through the digest() method of the object*Since the registered login involves the password*We need to encrypt the user's password using the MD5 algorithm*The full name of MD5 is Message-Digest Algorithm 5(Information-Digest algorithm)*The MD5 algorithm is simpleThat is, any length of string is converted to a 16-bit string of fixed length (usually 128 bits)*and the algorithm is irreversible */ public class MD5Utils { // MD5 encryption algorithm public static String MD5 (String text) {MessageDigest digest = null; try {//get data fingerprint object digest = MessageDigest.getInstance("md5"); //byte array byte[] result = digest.digest (text.getBytes(); //16-bit conversion StringBuffer sb = new StringBuffer(); //get all bytes for conversion (byte: result) {//use'"With Algorithms, java uses unicode characters, so each character takes up two//needs to be run with two hexadecimal maximums to get the numbervalue int number = B & 0xff; //numbervalue conversion string String hex = Integer.toHexString (number); if (hex.length() = 1) {//if the converted string length equals 1, string concatenation sb.append ("0" +x);} {sb else.hex String (number); {Append (hex);}} return sb.toString();} catch (NoSuchAlgorithmException) {e.printStackTrace (); //send an exception return empty string return';}}}

Register interface logic code Declare Activity private properties for manipulating controls

//Title private TextView tv_main_title; //Return button private TextView tv_back; //Registration button private Button btn_register; //User name, password, re-entered password control private EditText et_user_name,et_psw,et_psw_again; //User name, password, re-entered password control get value private String userName,psw,pswAgain; //Title layoutPrivate RelativeLayout rl_title_bar;

Get interface controls Creates an initialization method init() for interface controls in RegisterAcitivity, which is used to obtain the controls to use for registering interface locks and click events to implement controls.Notice that two private class methods, getEditString(), and isExistUserName(String userName), are written after init().

private void init() { //Get the corresponding UI control tv_main_title=findViewById (R.id.tv_main_title) =findViewById (R.id.tv_main_title); tv_main_title.setText ("Registration"); tv_back=findViewById(R.id.tv_back); //layout root element rl_title_bar=findViewById (R.id.title_bar); rl_title_bar_title_bar.title_backgrogroundbar_Backtitle_bar.BackgroundColor (Color.TRANSPARENTRERENT; //Activity.xmactivity_Activity retrretrretrretrretrretrretrretrretrretrretrretrretrretrretrretrfindViewById (R.id.id.ControlPart btn_register=findViewById (R.id.btn_register); et_user_name=findViewById (R.id.et_user_name); et_user_name=findViewById (R.id.et_user_name); et_psw=findViewById (R.id.et_psw); et_psw_again=findViewById (R.id.id.et_psw_again); tv_back.setOnClickListener (View.OnClickListener() {@public void onClick (View void (Override Click (View v) {//RegisterKey returned key {///RegisterRegisterViewView {.new Activity //y.this.finish();}}; //registration button btn_registerSetOnClickListener (new View.OnClickListener () {@Override public void onClick (View v) {//Get the string getEditString ()) // Get input string getEditString () entered in the corresponding control; //Judges input box content if (TextUtils.isEmpty (userName)) {Toast.makeText (RegisterActivity.this, "Enter username", Toast.LENGTH_SHORT).show(); return;}if (TextUtils.isisvoid void onClick (View V v) {TextUtils. isEmpty (Topsast) Empty (userName)) {Toast.LENGmakeTExt ext (RegisterActivity.this,'Please Enter Password', Toast.LENGTH_SHORT).show(); return;}else if (TextUtils.isEmpty (pswAgain)) {Toast.makeText (RegisterActivity.this,'Please Enter Password Again', Toast.LENGTH_SHORT).show(); return;}else if if (!Psw.equals (pswwAgain){Toast.maketext (Regisast.TexterActivittery.SHORT). return;}else if if if (!Psw.equals (pswwAgain){Toast.maket (RegisterTexteractivity Activity.activity. This,,'Toast ActivitterLENGTH_SHORT). show(); return; /** * Read the input username from SharedPreferences to determine if there is this username in SharedPreferences*/} else if (isExistUserName (userName)) {Toast.makeText (RegisterActivity.this,'This account name already exists', Toast.LENGTH_SHORT). show (); return;} else {Toast.makeText (Registery.this,'Registration succeeded', ast.LENGTH_SHORT)/();/show()Save account, password and account ID in sp/** * Save account and password to SharedPreferences*/ saveRegisterInfo(userName, psw); //Pass account to LoginActivity.java after successful registration//Return value to loginActivity Display Intent = new Intent(); data.putExtra ("userName", userName); setResult (RESULT_OK, data); //RESULT_OK is Activity familyConstant with status code -1, // indicating that the content operation under this page successfully returned data to the previous page, if it was backed to the past, then there was no passing data value RegisterActivity.this.finish();}}});} /** * Getting the string in the control */ private void getEditString(){userName=et_user_name.getText(). toString(). psw=et_psw.getText(); psw=et_psw.getText().toString().toString().trim(); pswAgain=et_psw_again.getText().toString().trim();} //**** * Read the user name entered from SharedPreferences, and determine if there is this user name in SharedPreferences*/ private Boolean isExistUserName (String userName){Boolean has_userName=false; //mode_private SharedPreferences = ShartPreferences ()//mode_private_SharedPreferences (); //////, "/, MOlogiInfo" / "MOloginInfo" / MOlogilogilogilogilogilogilogilogilogilogilogilogilogilogiDE_PRIVATE SharedPreferences sp=getSharedPreferences ("loginInfo", MODE_PRIVATE); //Get Password String spPsw=sp.getString(userName, "); //Pass in User Name Get Password//If Password is not empty, this username if (!TextUtils.isEmpty (spPsw)) {has_userName=true;} has_returned_userName;}

Save registration information to SharedPreferences Create a saveRegisterInfo() method in REgisterActivity that says the successfully registered username and password (encrypted by MD5) are saved in SharedPreferences.

private void saveRegisterInfo(String userName,String psw){ String md5Psw = MD5Utils.md5(psw);//Encrypt the password with MD5 //loginInfo for the file name, mode_private SharedPreferences SP = getSharedPreferences (); SharedPreferences SP = getSharedPreferences ("loginInfo", MODE_PRIVATE); //Get Editor, SharedPreferences.Editor editor -> sp.edit (); SharedPreferences.Editor=sp.edit (); //Save the password as valuefer in SharedPreferences.//key,value in ences, such as key-value pairs, editor.putString (username, password); editor.putString(userName, md5Psw); //commit modify editor.commit(); editor.commit();}

Initit() is called in Activity's onCreate

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Set Page Layout, Register Interface
        setContentView(R.layout.activity_register);
        //Set this interface as a vertical screen
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        init();
    }

The complete code for RegisterActivity is as follows

package cn.edu.gdmec.android.boxuegu.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.edu.gdmec.android.boxuegu.R;
import cn.edu.gdmec.android.boxuegu.utils.MD5Utils;


public class RegisterActivity extends AppCompatActivity {
    //Title
    private TextView tv_main_title;
    //Return button
    private TextView tv_back;
    //Registration button
    private Button btn_register;
    //User name, password, control for re-entering password
    private EditText et_user_name,et_psw,et_psw_again;
    //User name, password, get value of the control for the re-entered password
    private String userName,psw,pswAgain;
    //Title Layout
    private RelativeLayout rl_title_bar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Set Page Layout, Register Interface
        setContentView(R.layout.activity_register);
        //Set this interface as a vertical screen
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        init();
    }

    private void init() {
        //Get the corresponding UI control from the main_title_bar.xml page layout
        tv_main_title=findViewById(R.id.tv_main_title);
        tv_main_title.setText("register");
        tv_back=findViewById(R.id.tv_back);
        //Layout root element
        rl_title_bar=findViewById(R.id.title_bar);
        rl_title_bar.setBackgroundColor(Color.TRANSPARENT);
        //Get the corresponding UI control from the activity_register.xml page
        btn_register=findViewById(R.id.btn_register);
        et_user_name=findViewById(R.id.et_user_name);
        et_psw=findViewById(R.id.et_psw);
        et_psw_again=findViewById(R.id.et_psw_again);
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Return key
                RegisterActivity.this.finish();
            }
        });
        //Registration button
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Gets the string entered in the corresponding control
                getEditString();
                //Decide what the input box is
                if(TextUtils.isEmpty(userName)){
                    Toast.makeText(RegisterActivity.this, "enter one user name", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(psw)){
                    Toast.makeText(RegisterActivity.this, "Please input a password", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(pswAgain)){
                    Toast.makeText(RegisterActivity.this, "Please enter your password again", Toast.LENGTH_SHORT).show();
                    return;
                }else if(!psw.equals(pswAgain)){
                    Toast.makeText(RegisterActivity.this, "Passwords entered twice are different", Toast.LENGTH_SHORT).show();
                    return;
                    /**
                     *Read the input username from SharedPreferences to determine if it exists in SharedPreferences
                     */
                }else if(isExistUserName(userName)){
                    Toast.makeText(RegisterActivity.this, "This account name already exists", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    Toast.makeText(RegisterActivity.this, "login was successful", Toast.LENGTH_SHORT).show();
                    //Save account, password and account ID in sp
                    /**
                     * Save account and password to SharedPreferences
                     */
                    saveRegisterInfo(userName, psw);
                    //Pass the account to LoginActivity.java after successful registration
                    // Return value to loginActivity display
                    Intent data = new Intent();
                    data.putExtra("userName", userName);
                    setResult(RESULT_OK, data);
                    //RESULT_OK is an Activity system constant with a status code of -1.
                    //Indicates that the content operation beneath this page successfully returned the data to the previous page, if it was returned to the past with back, no data value was passed with setResult
                    RegisterActivity.this.finish();
                }
            }
        });
    }
    /**
     * Gets the string in the control
     */
    private void getEditString(){
        userName=et_user_name.getText().toString().trim();
        psw=et_psw.getText().toString().trim();
        pswAgain=et_psw_again.getText().toString().trim();
    }
    /**
     * Read the input username from SharedPreferences to determine if it exists in SharedPreferences
     */
    private boolean isExistUserName(String userName){
        boolean has_userName=false;
        //mode_private SharedPreferences sp = getSharedPreferences( );
        // "loginInfo", MODE_PRIVATE
        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        //Get Password
        String spPsw=sp.getString(userName, "");//Pass in user name to get password
        //If the password is not empty, the username is indeed saved
        if(!TextUtils.isEmpty(spPsw)) {
            has_userName=true;
        }
        return has_userName;
    }
    /**
     * Save account and password to SharedPreferences in SharedPreferences
     */
    private void saveRegisterInfo(String userName,String psw){
        String md5Psw = MD5Utils.md5(psw);//Encrypt password with MD5
        //loginInfo denotes the file name, mode_private SharedPreferences sp = getSharedPreferences();
        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        //Get the editor, SharedPreferences.Editor editor -> sp.edit();
        SharedPreferences.Editor editor=sp.edit();
        //Save in SharedPreferences with user name key and password value
        //key,value, such as key-value pairs, editor.putString (username, password);
        editor.putString(userName, md5Psw);
        //Commit ();
        editor.commit();
    }
}

Login interface The login interface mainly inputs login information. When you click on the login button, you need to query ShatredPreferences if the user name you entered has a corresponding password. If so, you can use this password to compare with the current password you entered (which requires MD5 encryption). If the information is consistent, the login is successful and the status and user name of the successful login are saved in SharedPreferences for convenience.Subsequently, determine the login status and get the user name.

Create login interface Right mouse button activity package, new->activity->Empty Activity, create LoginAcitivity Import picture resources into drawable

login_bg.png login_user_name_bg.png login_psw_bg.png

Write the interface layout activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<!--Login interface-->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/login_bg"
    android:orientation="vertical">
    <!--title bar-->
    <include layout="@layout/main_title_bar"></include>
    <ImageView
        android:id="@+id/iv_head"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_marginTop="25dp"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/default_icon"/>
    <EditText
        android:id="@+id/et_user_name"
        android:layout_width="fill_parent"
        android:layout_height="48dp"
        android:layout_marginTop="35dp"
        android:layout_marginLeft="35dp"
        android:layout_marginRight="35dp"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/login_user_name_bg"
        android:drawableLeft="@drawable/user_name_icon"
        android:drawablePadding="10dp"
        android:paddingLeft="8dp"
        android:gravity="center_vertical"
        android:hint="enter one user name"
        android:singleLine="true"
        android:textColor="#000000"
        android:textColorHint="#a3a3a3"
        android:textSize="14sp"/>
    <EditText
        android:id="@+id/et_psw"
        android:layout_width="fill_parent"
        android:layout_height="48dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="35dp"
        android:layout_marginRight="35dp"
        android:background="@drawable/login_psw_bg"
        android:drawableLeft="@drawable/psw_icon"
        android:drawablePadding="10dp"
        android:paddingLeft="8dp"
        android:gravity="center_vertical"
        android:hint="Please input a password"
        android:inputType="textPassword"
        android:singleLine="true"
        android:textColor="#000000"
        android:textColorHint="#a3a3a3"
        android:textSize="14sp"/>
    <Button
        android:id="@+id/btn_login"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="35dp"
        android:layout_marginRight="35dp"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/register_selector"
        android:text="Sign in"
        android:textColor="@android:color/white"
        android:textSize="18sp"/>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="35dp"
        android:layout_marginRight="35dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_register"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:padding="8dp"
            android:text="Register Now"
            android:textColor="@android:color/white"
            android:textSize="14sp" />
        <!--layout_weight="1" layout_width="0dp"Achieving Equity-->
        <TextView
            android:id="@+id/tv_find_psw"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:padding="8dp"
            android:text="Retrieve password?"
            android:textColor="@android:color/white"
            android:textSize="14sp" />
    </LinearLayout>
</LinearLayout>

Logic code for login interface Declare Activity private properties for manipulating controls

//Title
    private TextView tv_main_title;
    //Return key, show registration, retrieve password
    private TextView tv_back,tv_register,tv_find_psw;
    //Logon button
    private Button btn_login;
    //Obtained username, password, encrypted password
    private String userName,psw,spPsw;
    //Input box for username and password
    private EditText et_user_name,et_psw;

Get interface controls Create the init() initialization method to get the space needed for the login interface and set the login button, return button, register now, retrieve the password click event

//Get interface controls
    private void init() {
        //id obtained from main_title_bar
        tv_main_title=findViewById(R.id.tv_main_title);
        tv_main_title.setText("Sign in");
        tv_back=findViewById(R.id.tv_back);
        //Obtained from activity_login.xml
        tv_register=findViewById(R.id.tv_register);
        tv_find_psw=findViewById(R.id.tv_find_psw);
        btn_login=findViewById(R.id.btn_login);
        et_user_name=findViewById(R.id.et_user_name);
        et_psw=findViewById(R.id.et_psw);
        //Click Event for Return Key
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Logon interface destruction
                LoginActivity.this.finish();
            }
        });
        //Register the control's click event now
        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //In order to jump to the registration interface and realize the registration function
                Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        //Retrieve the click event for the password control
        tv_find_psw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Jump to the password retrieval interface (this page is not yet created)
                /*Intent intent=new Intent(LoginActivity.this,FindPwdActivity.class);
                startActivity(intent);*/
            }
        });
        //Click Event of Logon Button
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Start logging in and get the username and password getText().toString().trim();
                userName=et_user_name.getText().toString().trim();
                psw=et_psw.getText().toString().trim();
                //Make a comparison of the passwords entered by the current user for MD5 encryption, MD5Utils.md5(); PSW for encryption to determine if they are consistent
                String md5Psw= MD5Utils.md5(psw);
                // Md5Psw; spPsw reads password based on user name from SharedPreferences
                // Define the method readPsw to get the password in order to read the user name
                spPsw=readPsw(userName);
                // TextUtils.isEmpty
                if(TextUtils.isEmpty(userName)){
                    Toast.makeText(LoginActivity.this, "enter one user name", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(psw)){
                    Toast.makeText(LoginActivity.this, "Please input a password", Toast.LENGTH_SHORT).show();
                    return;
                    // md5Psw.equals(); determines if the password entered is encrypted and identical to the one saved in SharedPreferences
                }else if(md5Psw.equals(spPsw)){
                    //Uniform Logon Success
                    Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
                    //Save the login status, save the login user name in the interface, define a method to save LoginStatus Boolean status, userName user name;
                    saveLoginStatus(true, userName);
                    //Close this page to go to the home page after successful login
                    Intent data=new Intent();
                    //datad.putExtra( ); name , value ;
                    data.putExtra("isLogin",true);
                    data.putExtra("userName",userName);
                    //RESULT_OK is an Activity system constant with a status code of -1
                    // Indicates that the content operation beneath this page successfully returned the data to the previous page, if it was returned to the past with back, no data value was passed with setResult
                    setResult(RESULT_OK,data);
                    //Destroy login interface
                    LoginActivity.this.finish();
                    //Jump to the main interface and the status of successful login is passed to MainActivity
                    //startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    return;
                }else if((spPsw!=null&&!TextUtils.isEmpty(spPsw)&&!md5Psw.equals(spPsw))){
                    Toast.makeText(LoginActivity.this, "The username and password entered are inconsistent", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    Toast.makeText(LoginActivity.this, "This user name does not exist", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
//Read password from SharedPreferences based on user name
/**
     *Read password from SharedPreferences based on user name
     */
    private String readPsw(String userName){
        //getSharedPreferences("loginInfo",MODE_PRIVATE);
        //"loginInfo",mode_private; MODE_PRIVATE means that writing can continue
        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        //sp.getString() userName, "";
        return sp.getString(userName , "");
    }

Save login status to SharedPreferences Since the icon and user name of the interface need to be set based on the login status when subsequently creating the main interface, you need to create the saveLogiinStatus() method to save the login status and user name to SharedPrefereces after successful login.

private void saveLoginStatus(boolean status,String userName){
        //saveLoginStatus(true, userName);
        //LoginInfo denotes the file name SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        //Get Editor
        SharedPreferences.Editor editor=sp.edit();
        //Save login status of boolean type
        editor.putBoolean("isLogin", status);
        //User name when logged in
        editor.putString("loginUserName", userName);
        //Submit modifications
        editor.commit();
    }

Get Return Data Override the onActivityResult() method to obtain a successfully registered user name through the data.getStringExtra() method and display it on the User Name control.

Convenient operations for overriding class methods:

Select the menu Code->Override Methods or press the shortcut key Ctrl+o, then enter the method name onActivityResult, Android Studio will find it intelligently, press Enter to add the writing code automatically.

/**
     * Data from successful registration is returned here
     * @param requestCode Request Code
     * @param resultCode Result Code
     * @param data data
     */
    @Override
    //Display data, onActivityResult
    //startActivityForResult(intent, 1); Get data from the registration interface
    //int requestCode , int resultCode , Intent data
    // LoginActivity -> startActivityForResult -> onActivityResult();
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if(data!=null){
            //Is the user name returned from getting the registration interface
            // getExtra().getString("***");
            String userName=data.getStringExtra("userName");
            if(!TextUtils.isEmpty(userName)){
                //Set user name to et_user_name control
                et_user_name.setText(userName);
                //setSelection() method of et_user_name control to set cursor position
                et_user_name.setSelection(userName.length());
            }
        }
    }

The complete code for LoginActivity is as follows

package cn.edu.gdmec.android.boxuegu.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 cn.edu.gdmec.android.boxuegu.R;
import cn.edu.gdmec.android.boxuegu.utils.MD5Utils;

public class LoginActivity extends AppCompatActivity {
    //Title
    private TextView tv_main_title;
    //Return key, show registration, retrieve password
    private TextView tv_back,tv_register,tv_find_psw;
    //Logon button
    private Button btn_login;
    //Obtained username, password, encrypted password
    private String userName,psw,spPsw;
    //Input box for username and password
    private EditText et_user_name,et_psw;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //Set this interface as a vertical screen
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        init();
    }
    //Get interface controls
    private void init() {
        //id obtained from main_title_bar
        tv_main_title=findViewById(R.id.tv_main_title);
        tv_main_title.setText("Sign in");
        tv_back=findViewById(R.id.tv_back);
        //Obtained from activity_login.xml
        tv_register=findViewById(R.id.tv_register);
        tv_find_psw=findViewById(R.id.tv_find_psw);
        btn_login=findViewById(R.id.btn_login);
        et_user_name=findViewById(R.id.et_user_name);
        et_psw=findViewById(R.id.et_psw);
        //Click Event for Return Key
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Logon interface destruction
                LoginActivity.this.finish();
            }
        });
        //Register the control's click event now
        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //In order to jump to the registration interface and realize the registration function
                Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        //Retrieve the click event for the password control
        tv_find_psw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Jump to the password retrieval interface (this page is not yet created)
                /*Intent intent=new Intent(LoginActivity.this,FindPwdActivity.class);
                startActivity(intent);*/
            }
        });
        //Click Event of Logon Button
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Start logging in and get the username and password getText().toString().trim();
                userName=et_user_name.getText().toString().trim();
                psw=et_psw.getText().toString().trim();
                //Make a comparison of the passwords entered by the current user for MD5 encryption, MD5Utils.md5(); PSW for encryption to determine if they are consistent
                String md5Psw= MD5Utils.md5(psw);
                // Md5Psw; spPsw reads password based on user name from SharedPreferences
                // Define the method readPsw to get the password in order to read the user name
                spPsw=readPsw(userName);
                // TextUtils.isEmpty
                if(TextUtils.isEmpty(userName)){
                    Toast.makeText(LoginActivity.this, "enter one user name", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(psw)){
                    Toast.makeText(LoginActivity.this, "Please input a password", Toast.LENGTH_SHORT).show();
                    return;
                    // md5Psw.equals(); determines if the password entered is encrypted and identical to the one saved in SharedPreferences
                }else if(md5Psw.equals(spPsw)){
                    //Uniform Logon Success
                    Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
                    //Save the login status, save the login user name in the interface, define a method to save LoginStatus Boolean status, userName user name;
                    saveLoginStatus(true, userName);
                    //Close this page to go to the home page after successful login
                    Intent data=new Intent();
                    //datad.putExtra( ); name , value ;
                    data.putExtra("isLogin",true);
                    data.putExtra("userName",userName);
                    //RESULT_OK is an Activity system constant with a status code of -1
                    // Indicates that the content operation beneath this page successfully returned the data to the previous page, if it was returned to the past with back, no data value was passed with setResult
                    setResult(RESULT_OK,data);
                    //Destroy login interface
                    LoginActivity.this.finish();
                    //Jump to the main interface and the status of successful login is passed to MainActivity
                    //startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    return;
                }else if((spPsw!=null&&!TextUtils.isEmpty(spPsw)&&!md5Psw.equals(spPsw))){
                    Toast.makeText(LoginActivity.this, "The username and password entered are inconsistent", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    Toast.makeText(LoginActivity.this, "This user name does not exist", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    /**
     *Read password from SharedPreferences based on user name
     */
    private String readPsw(String userName){
        //getSharedPreferences("loginInfo",MODE_PRIVATE);
        //"loginInfo",mode_private; MODE_PRIVATE means that writing can continue
        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        //sp.getString() userName, "";
        return sp.getString(userName , "");
    }
    /**
     *Save login status and login user name to SharedPreferences
     */
    private void saveLoginStatus(boolean status,String userName){
        //saveLoginStatus(true, userName);
        //LoginInfo denotes the file name SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        //Get Editor
        SharedPreferences.Editor editor=sp.edit();
        //Save login status of boolean type
        editor.putBoolean("isLogin", status);
        //User name when logged in
        editor.putString("loginUserName", userName);
        //Submit modifications
        editor.commit();
    }
    /**
     * Data from successful registration is returned here
     * @param requestCode Request Code
     * @param resultCode Result Code
     * @param data data
     */
    @Override
    //Display data, onActivityResult
    //startActivityForResult(intent, 1); Get data from the registration interface
    //int requestCode , int resultCode , Intent data
    // LoginActivity -> startActivityForResult -> onActivityResult();
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if(data!=null){
            //Is the user name returned from getting the registration interface
            // getExtra().getString("***");
            String userName=data.getStringExtra("userName");
            if(!TextUtils.isEmpty(userName)){
                //Set user name to et_user_name control
                et_user_name.setText(userName);
                //setSelection() method of et_user_name control to set cursor position
                et_user_name.setSelection(userName.length());
            }
        }
    }
}

Review package structure ~

Challenge Tasks Verify the login and registration modules. Please modify MainActivity and LoginActivity, welcome the interface to the main interface, automatically jump into the login interface, after successful login, return to the main interface, in the Hello World location of the main interface: User Name + Login Success.

summary This is the second step to getting Android right!

Don't forget to leave a footprint of your study [compliment + collection + comment]

Author Info:

[Author]: Jeskson Original Public Number: Dada Front End Bistro. Welfare: Public Number replies to the big gift package for self-study materials (share in groups, just say anything you want, see if I have one)! [Reprint instructions]: Please explain the source of reprinting, thank you for your cooperation!~

Big Front End Development, Locate Front End Development Technology Stack Blog, PHP Background Knowledge Point, web Full Stack Technology Field, Data Structure and Algorithms, Network Principles and other understandable presentations to small partners.Thank you for your support and love!!!

If there are inadequacies in this number (e.g. copyright or other issues), please contact us in time to make corrections, which will be dealt with at the first time.

Please compliment!Because your approval/encouragement is my greatest motivation to write!

Welcome to your attention Dada CSDN!

This is a quality, attitudinal blog

Tags: Front-end Android xml Java encoding

Posted on Tue, 07 Jan 2020 02:13:17 -0800 by nitestryker