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

时间:2018-02-21 08:43:54

标签: php android mysql

使用Android studio,我创建了一个Activity,其中有2个按钮和2个editText。 用户输入姓名和姓氏,然后按下两个按钮之一,一个用于注册,另一个用于登录。

根据用户按下的按钮,他将被定向到另一个活动。

我只想在一个按钮中使用2个注册和登录按钮。

即,用户输入他/她的姓名,如果输入的信息在数据库中然后登录,否则通过将数据保存在数据库中来保存

AndroidStudio文件是:

  • -LoginActivity java / xml
  • -MainActivity java / xml
  • -RegisterActivity java / xml
  • -HttpParse.java(与DB的连接)

数据库信息:

  • 数据库名称:my_oae
  • 表名:UserTable

  • 表字段:id,nome,cognome

我希望你能帮助我,我很感激。

下面我会告诉你我的代码。

-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:

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:

<?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和LoginActivity.java它们是空的,因为我只是在该活动的.xml文件中放置了一个Text View。

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

<?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

<?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";

?>

1 个答案:

答案 0 :(得分:0)

每当用户按下按钮时,您必须首先检查这是否是现有用户。如果他然后登录他,否则首先将他的信息保存到db然后登录。