简体   繁体   English

在Android中只需一个按钮即可登录和注册

[英]Login and Registration with just one button in Android

With Android studio, I created an Activity in which there are 2 buttons and 2 editText. 使用Android studio,我创建了一个Activity,其中有2个按钮和2个editText。 The user enters Name and Surname and then presses one of the two buttons, one is for Registering and the other is to Login. 用户输入名称和姓氏,然后按两个按钮之一,一个用于注册,另一个用于登录。

Depending on which button the user presses, he will be directed to another activity. 根据用户按下哪个按钮,他将被定向到另一个活动。

I would like the 2 Registration and Login buttons in only one button. 我只想要一个按钮中的2个注册和登录按钮。

That is, the user enters his / her name and surname, if the information entered is in the DB then Log in, otherwise, it is saved by saving the data in the DB 也就是说,用户输入他/她的姓名和姓氏,如果输入的信息在数据库中然后登录,否则,通过将数据保存在数据库中来保存

AndroidStudio files are: AndroidStudio文件为:

  • -LoginActivity java / xml -LoginActivity Java / XML
  • -MainActivity java / xml -MainActivity Java / XML
  • -RegisterActivity java / xml -RegisterActivity Java / XML
  • -HttpParse.java (connection with the DB) -HttpParse.java(与数据库的连接)

DB Information: 数据库信息:

  • DB name: my_oae 数据库名称:my_oae
  • Table Name: UserTable 表名:UserTable

  • Table fields: id, nome, cognome 表格栏位:id,nome,cognome

I hope you can help me, I'm grateful. 希望您能帮助我,谢谢。

Below I show you my code. 在下面,我向您展示我的代码。

-HttpParse.java -HttpParse.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Juned on 3/3/2017.
 */

public class HttpParse {

    String FinalHttpData = "";
    String Result ;
    BufferedWriter bufferedWriter ;
    OutputStream outputStream ;
    BufferedReader bufferedReader ;
    StringBuilder stringBuilder = new StringBuilder();
    URL url;

    public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {

        try {
            url = new URL(HttpUrlHolder);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setReadTimeout(14000);

            httpURLConnection.setConnectTimeout(14000);

            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoInput(true);

            httpURLConnection.setDoOutput(true);

            outputStream = httpURLConnection.getOutputStream();

            bufferedWriter = new BufferedWriter(

                    new OutputStreamWriter(outputStream, "UTF-8"));

            bufferedWriter.write(FinalDataParse(Data));

            bufferedWriter.flush();

            bufferedWriter.close();

            outputStream.close();

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                bufferedReader = new BufferedReader(
                        new InputStreamReader(
                                httpURLConnection.getInputStream()
                        )
                );
                FinalHttpData = bufferedReader.readLine();
            }
            else {
                FinalHttpData = "Something Went Wrong";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return FinalHttpData;
    }

    public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {

        for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){

            stringBuilder.append("&");

            stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));

            stringBuilder.append("=");

            stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));

        }

        Result = stringBuilder.toString();

        return Result ;
    }
    }

MainActivity.java : MainActivity.java:

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.net.FileNameMap;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    Button register, LogIn, tutto;
    EditText First_Name, Last_Name ;
    String F_Name_Holder, L_Name_Holder;
    String finalResult ;
    String HttpURLRegister = "http://oae.altervista.org/DB/registrazione.php";
    String HttpURLLogin = "http://oae.altervista.org/DB/login.php";

    Boolean CheckEditText ;

    ProgressDialog progressDialog;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();


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




        //REGISTRATION
        //Assign Id'S
        First_Name = (EditText)findViewById(R.id.name);
        Last_Name = (EditText)findViewById(R.id.surname);


        //REGISTRATION
        register = (Button)findViewById(R.id.buttonReg);

        //LOGIN
        LogIn = (Button)findViewById(R.id.buttonLog);









        //REGISTRATION
        //Adding Click Listener on button.
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Checking whether EditText is Empty or Not
                CheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    // If EditText is not empty and CheckEditText = True then this block will execute.

                    UserRegisterFunction(F_Name_Holder,L_Name_Holder);

                }
                else {

                    // If EditText is empty then this block will execute.
                    Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }


            }
        });



        //LOGIN
        LogIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    UserLoginFunction(F_Name_Holder, L_Name_Holder);

                }
                else {

                    Toast.makeText(MainActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });



    }

    //REGISTRAZIONE
    public void CheckEditTextIsEmptyOrNot(){

        F_Name_Holder = First_Name.getText().toString();
        L_Name_Holder = Last_Name.getText().toString();



        if(TextUtils.isEmpty(F_Name_Holder) || TextUtils.isEmpty(L_Name_Holder) )
        {

            CheckEditText = false;

        }
        else {

            CheckEditText = true ;
        }

    }



    //REGISTRATION
    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    public void UserRegisterFunction(final String F_Name, final String L_Name){

        class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                progressDialog = ProgressDialog.show(MainActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                Toast.makeText(MainActivity.this,httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

                if(httpResponseMsg.equalsIgnoreCase("Registration Successfully")){

                    finish();

                    Intent intent = new Intent(MainActivity.this, RegisterActivity.class);



                    startActivity(intent);

                }

            }

            //REGISTRATION
            @Override
            protected String doInBackground(String... params) {

                hashMap.put("f_name",params[0]);

                hashMap.put("L_name",params[1]);



                finalResult = httpParse.postRequest(hashMap, HttpURLRegister);

                return finalResult;
            }
        }

        UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();

        userRegisterFunctionClass.execute(F_Name,L_Name);
    }












    public void UserLoginFunction(final String F_name, final String L_name){

        class UserLoginClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                progressDialog = ProgressDialog.show(MainActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                if(httpResponseMsg.equalsIgnoreCase("Data Matched")){

                    finish();

                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);



                    startActivity(intent);
            }
            else{

                Toast.makeText(MainActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
            }

        }

        @Override
        protected String doInBackground(String... params) {

            hashMap.put("f_name",params[0]);

            hashMap.put("L_name",params[1]);

            finalResult = httpParse.postRequest(hashMap, HttpURLLogin);

            return finalResult;
        }
    }

    UserLoginClass userLoginClass = new UserLoginClass();

    userLoginClass.execute(F_name,L_name);
}

} }

Activity_Main.xml : 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"
    android:visibility="visible"
    tools:context="com.example.bruzi.db4.MainActivity">

    <Button
        android:id="@+id/buttonReg"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="50dp"
        android:background="@color/colorAccent"
        android:text="Register"
        android:textColor="@android:color/background_light"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/surname" />

    <EditText
        android:id="@+id/surname"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="Surname"
        android:inputType="textPersonName"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name" />

    <EditText
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="48dp"
        android:ems="10"
        android:hint="Name"
        android:inputType="textPersonName"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonLog"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:background="@color/colorAccent"
        android:text="Login"
        android:textColor="@android:color/background_light"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonReg" />

</android.support.constraint.ConstraintLayout>

RegisterActivity.java and LoginActivity.java they are empty because I just put a Text View in the .xml files of that activity. RegisterActivity.java和LoginActivity.java它们为空,因为我只是将文本视图放在该活动的.xml文件中。

Register.php Register.php

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){

include 'db4config.php';

 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

 $F_name = $_POST['f_name'];
 $L_name = $_POST['L_name'];


 $CheckSQL = "SELECT * FROM UserTable WHERE nome='$F_name'";

 $check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));

 if(isset($check)){

 echo 'Email Already Exist';

 }
else{ 
$Sql_Query = "INSERT INTO UserLoginTable (nome,cognome) values ('$F_name','$L_name')";

 if(mysqli_query($con,$Sql_Query))
{
 echo 'Registration Successfully';
}
else
{
 echo 'Something went wrong';
 }
 }
}
 mysqli_close($con);
?>

Login.php Login.php

<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){

 include 'db4config.php';

 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

 $F_name = $_POST['f_name'];
 $L_name = $_POST['L_name'];

 $Sql_Query = "select * from UserTable where nome = '$F_name' and cognome = '$L_name' ";

 $check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));

 if(isset($check)){

 echo "Data Matched";
 }
 else{
 echo "Invalid Username or Password Please Try Again";
 }

 }else{
 echo "Check Again";
 }
mysqli_close($con);

?>

db4config.php db4config.php

<?php

//Define your host here.
$HostName = "DB4";

//Define your database username here.
$HostUser = "oae";

//Define your database password here.
$HostPass = "*********";

//Define your database name here.
$DatabaseName = "my_oae";

?>

Whenever user presses the button you have to first check if this is an existing user. 每当用户按下按钮时,您都必须首先检查该用户是否是现有用户。 If he is then log him in otherwise first save his information to db and then log him in. 如果他要登录,否则先将其信息保存到db,然后再登录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM