php - Android 系统一键登录注册

标签 php android mysql

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

根据用户按下的按钮,他将被引导到另一个 Activity 。

我希望将 2 个注册和登录按钮合并到一个按钮中。

即用户输入姓名,如果输入的信息在DB中则登录,否则通过将数据保存在DB中来保存

AndroidStudio 文件是:

  • -LoginActivity java/xml
  • -MainActivity java/xml
  • -RegisterActivity java/xml
  • -HttpParse.java(与数据库连接)

数据库信息:

  • 数据库名称: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 它们是空的,因为我只是将 TextView 放入该 Activity 的 .xml 文件中。

注册.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);
?>

登录.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";

?>

最佳答案

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

关于php - Android 系统一键登录注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901429/

相关文章:

php - 为什么这个 .htaccess 文件不显示存在的文件?

php - 如何使单个值更新 SQL 查询与 Wordpress 中的 $wpdb 类一起使用?

android - 如何使用 gradle 从 .AAR Android 库存档中排除文件

android - SQLite UPDATE 值与行号可能/选项?

mysql - Oracle的 "sequence"和MySql的Auto_increment特性有什么区别?

PHP 登录表单 : SQL database Password

php - 如何使用 PHP 创建没有列名的 JSON 文件?

android - libdvm.so 位置

php - mysql_fetch_array 不工作

php - Instagram API 如何获取用户 ID?