Android implements a small demo for logging in

Android, in the years before Xiaobian’s internship, Xiaobian never played. If I did, it would be an Android phone. Ahem, there is a special long-lost familiarity when I tap to log in. This kind of familiarity The feeling is the same as when I knocked on the computer room charging system at that time. It was a difficult task. However, I believe that on the way of my IT growth, it was precisely because of these difficulties and obstacles that I grew up with me that I made my editor grow up. Be more brave and strong, bravely face one bug after another, and finish typing line by line of code. After a few days of research, the function of logging in a line has been realized. Now I will briefly summarize it, and please friends A lot of advice (<em>∩_∩</em>)'!</p> <p>In general, the Android architecture is very similar to the three-tier architecture we have learned before, because the knowledge is the same. , First, create an entity in the model, and then create an XML file in the layout in res to make the relevant layout of the required pages. So far, the editor has no idea about the pendulum control, and it needs a lot of practice. Finally, in the Create a class in ui in src to write specific logic. When I was logging in, I downloaded a lot of demos on the Internet, but their architecture is not very similar to the structure of the project I am knocking on now, so I crossed the river by feeling the stones. The process is very beautiful(∩_∩)’, next, let’s look at the specific code implementation.

First, we need to create an entity in the model. Since the editor uses two tables, we need to create two models. The first one uses LoginMsg. The code is as follows:

/***
 * Description: Relevant information required when logging in
 * Author: Ding Guohua
 * Time: July 17, 2015 09:40:18
 */


package jczb.shoping.model;

import java.io.Serializable;

import android.R.string;


public class loginMsg implements Serializable {
    private String avatarPath;
    private String accountNum;
    private String littleName;
    private String memberRank;
    private int growths;
    private String memberIntegral;
    public String getAvatarPath() {
        return avatarPath;
    }
    public void setAvatarPath(String avatarPath) {
        this.avatarPath = avatarPath;
    }
    public String getAccountNum() {
        return accountNum;
    }
    public void setAccountNum(String accountNum) {
        this.accountNum = accountNum;
    }
    public String getLittleName() {
        return littleName;
    }
    public void setLittleName(String littleName) {
        this.littleName = littleName;
    }
    public String getMemberRank() {
        return memberRank;
    }
    public void setMemberRank(String memberRank) {
        this.memberRank = memberRank;
    }
    public int getGrowths() {
        return growths;
    }
    public void setGrowths(int growths) {
        this.growths = growths;
    }
    public String getMemberIntegral() {
        return memberIntegral;
    }
    public void setMemberIntegral(String memberIntegral) {
        this.memberIntegral = memberIntegral;
    }

}

The second used FoundPassWord, the specific code is as follows:

/***
 * Description: Information about retrieving the password
 * Author: Ding Guohua
 * Time: July 17, 2015 09:41:18
 */
package jczb.shoping.model;
import java.io.Serializable;
import android.R.string;

public  class  foundPassWord  implements  Serializable  {
     private String phoneNumber; //Phone number 
    private String vlidationNum; //Verification code 
    private String passWord; //Password 
    private String repetyPassWord; //Confirm password


    public String getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    public String getVlidationNum() {
        return vlidationNum;
    }
    public void setVlidationNum(String vlidationNum) {
        this.vlidationNum = vlidationNum;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public String getRepetyPassWord() {
        return repetyPassWord;
    }
    public void setRepetyPassWord(String repetyPassWord) {
        this.repetyPassWord = repetyPassWord;
    }
}

Next, let’s draw the page and use xml to set the relevant layout of our login page. The specific code is as follows:

<?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="@color/login_background_color">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:gravity="center"
        android:textColor="@color/blue_ipsetting"
        android:textSize="30sp"
        android:textStyle="bold" />

    <!-- The entire LinearLayout is the rectangle frame for the account number and please enter the account number--> 
    < LinearLayout 
                android:layout_width = "fill_parent" 
                android:layout_height = "wrap_content" 
                android:layout_margin = "5dp" 
                android:orientation = "horizontal" 
                android: padding = "10sp" 
                android:background = "@color/white" >

                <!-- Account layout--> 
                < TextView 
                    android:id = "@+id/tv_loginAccount" 
                    android:layout_width = "wrap_content" 
                    android:layout_height = "wrap_content" 
                    android:text = "@string/loginAccount" 
                    android:textColor = "@android:color/black" 
                    android:textSize = "18.0sp" /> 
                <!-- EditText represents a layout for entering an account --> 
                < EditText 
                    android:id = "@+id/loginAccount_id" 
                    android :layout_width = "160dp" 
                    android:layout_height = "wrap_content"
                    android:layout_weight="1"
                    android:background="@null"

                    android:ems="10"
                    android:hint="@string/inputAccount"
                    android:padding="5.0dip"
                    android:paddingRight="40dp"                    
                    android:textColor="#ff3b3b3b"
                    android:textSize="16.0sp" >
                </EditText>
      </LinearLayout>

      <!-- Entire layout for password and enter password--> 
      < LinearLayout  
          android:layout_width = "fill_parent" 
          android:layout_height = "wrap_content" 
          android:layout_margin = "5dp" 
          android:orientation = "horizontal" 
          android:padding = " 10sp" 
          android:background = "@color/white" >

          <TextView 
              android:id="@+id/tv_password"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/password"
              android:textColor="@android:color/black"
              android:textSize="18.0sp"/>

          <EditText
              android:id="@+id/password_id"
              android:layout_width="163dp"
              android:layout_height="wrap_content"
              android:layout_weight="1"
              android:background="@null"
              android:ems="10"
              android:hint="@string/inputPassword"
              android:inputType="textPassword"
              android:padding="5.0dip"
              android:paddingRight="30dp"
              android:textColor="#ff3b3b3b"
              android:textSize="16.0sp"/>  

             </LinearLayout>

         <Button
            android:id="@+id/login"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="14dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="80dp"
            android:background="@drawable/android_title_bg"
            android:gravity="center"
            android:text="@string/login"
            android:textColor="#fff" />

         <!-- Retrieve password and understand the layout of registration -->

          <!-- Retrieve password and register now layout-->

      <LinearLayout
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_margin="5dp"
          android:background="@color/white"
          android:orientation="horizontal"
          android:padding="10sp" >

          <!-- Retrieve password-->

          <TextView
              android:layout_width="70dp"
              android:layout_height="50dp"
              android:layout_marginLeft="40dp"
              android:layout_marginTop="15dp"
              android:textSize="15sp"
              android:textStyle="bold" />

          <!-- Register now-->

          <TextView
              android:layout_width="70dp"
              android:layout_height="56dp"
              android:layout_marginLeft="55dp"
              android:layout_marginTop="15dp"
              android:layout_weight="0.03"
              android:textSize="15sp"
              android:textStyle="bold" />
      </LinearLayout>

</LinearLayout>

Finally, let’s take a look at the code of the specific logic part, the specific code is as follows:

package jczb.shoping.ui;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import jczb.shoping.common.AgentApi;
import jczb.shoping.model.foundPassWord;
import jczb.shoping.model.loginMsg;
import android.R.integer;
import android.R.string;
import android.accounts.Account;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {    


    //declare variable 
    private Handler mHandler;
    EditText account;
    EditText password;
    private Button loginButton ;

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);

            account =(EditText) findViewById(R.id.loginAccount_id);
            password=(EditText) findViewById(R.id.password_id);
            loginButton=(Button) findViewById(R.id.login);

         // Set a listener for the login button, the method is implemented by the following Onclick 
            loginButton.setOnClickListener( this );
}


        @Override
        /**
         * Realize the jump of the login button
         */ 
        public  void  onClick (View v)  {
             // Determine which control is clicked according to the id, fixed writing 
            switch (v.getId()) {
             case R.id.login:
                login();
                break;          
            default:
                break;
            }

        }



        /**
         * Login method
         */
        public boolean login() {

            if (isUserNameAndPwdValid()) {
                mHandler=new Handler(){

                    public void handleMessage(Message msg){
                        switch(msg.what){
                        case -1:
                        Toast.makeText(LoginActivity. this , "Server connection failed!" ,
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case -2:
                        Toast.makeText(LoginActivity.this , " Oops, something went wrong..." ,
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case 1:
                            String temp=(String)msg.obj;
                            //Convert the received json into an array
                List<loginMsg> loginMsgInfo=JSON.parseArray(temp, loginMsg.class);
           List<foundPassWord> foundPassWordInfo=JSON.parseArray(temp,foundPassWord.class);


            String userName=account.getText().toString().trim();
                String pwd=password.getText().toString().trim();

            String AccountNum=loginMsgInfo.get(0).getAccountNum();
            String psaaword=foundPassWordInfo.get(0).getPassWord();

             if (account.equals(AccountNum)&& pwd.equals(psaaword)) {
                 //Implement interface jump 
               Intent intent = new Intent(LoginActivity.this , MainActivity.class );
                            startActivity(intent);
                            //Close the current interface
                            finish();
                           } else {
                         //Implement interface jump 
                 Intent intent = new Intent(LoginActivity.this , MainActivity.class );
                         startActivity(intent);
                         //Close the current interface
                          finish();
// Toast.makeText(LoginActivity.this, "Incorrect username or password", 0).show();
                           }

                        }
                    }
                };



                //Main thread 
                    new Thread(){
                         public  void  run () {
                            Message msg= new Message();
                        try{
                            Map<String,String> parmas=new HashMap<String,String>();
                            parmas.put("username","1");
                            parmas.put("password","2");
         String loginMsgurl="http://192.168.1.110:8080/SchoolShopJson/LoginMsg.txt";
         String foundPassWordurl="http://192.168.1.110:8080/SchoolShopJson/foundPassWord.txt";


                            //The data to send and the address to access
                    String resultloginMsgString=AgentApi.dopost(parmas,loginMsgurl);

                        String resultfpasswordString=AgentApi.dopost(parmas, foundPassWordurl);


                            //Send handler information 
                            msg.what= 1 ;
                            msg.obj=resultloginMsgString;



                        }catch(Exception e){
                            e.printStackTrace();
                            //Use -1 to represent program exception 
                            msg.what= -2 ;
                            msg.obj=e;
                        }
                        mHandler.sendMessage(msg);
                    }
                   }.start();

            }
            return  false ;

        }


        /**
         * Determine whether the username and password are valid
         * 
         * @return 
         */ 
        public  boolean  isUserNameAndPwdValid ()  {
             // username and password must not be empty 
            if (account.getText().toString().trim().equals( "" )) {
                Toast.makeText(this, getString(R.string.accountName_empty),
                        Toast.LENGTH_SHORT).show();
                return  false ;
            } else if (password.getText().toString().trim().equals("")) {
                Toast.makeText(this, getString(R.string.password_empty),
                        Toast.LENGTH_SHORT).show();
                return  false ;
            }
            return true;
        }
}

Finally, let’s take a look at the running effect. If the user name and password are correct, jump to the home page. If the user name and password are wrong, a prompt will be given, as shown in the following screenshot:

Xiaobian’s message : In this blog, the editor mainly briefly introduced how to implement Android login, but to be honest, the editor is still in a fog, and I am not proficient in xml layout pages, but it doesn’t matter, the editor It will become more and more courageous. This is the meaning of life. For the editor, it is both a challenge and an opportunity, because knowledge is the same. Besides, in the editor’s program life, stay The most precious memory, although the editor will not necessarily be engaged in the Android industry in the future, in the world of code, there are many things, some sweet, some warm, some tactfully turned into songs, and some endless, in these stories, The only thing we have in common is that in a certain year, a certain month, a certain calm day, we used to love you very much! Love you–In the days of this internship, Android brought all kinds of surprises to the editor.

Leave a Comment

Your email address will not be published. Required fields are marked *