Вход и регистрация с помощью одной кнопки в Android

0

В студии Android я создал Activity, в котором есть 2 кнопки и 2 editText. Пользователь вводит имя и фамилию, а затем нажимает одну из двух кнопок, один для регистрации, а другой - для входа в систему.

В зависимости от того, какая кнопка нажата, он будет перенаправлен на другую деятельность.

Я бы хотел, чтобы 2 кнопки регистрации и входа только одна кнопка.

То есть пользователь вводит свое имя и фамилию, если введенная информация находится в БД, тогда войдите в систему, в противном случае она сохраняется путем сохранения данных в БД

Файлы 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 они пустые, потому что я просто поместил текстовый вид в.xml файлы этого действия.

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
Лучший ответ

Всякий раз, когда пользователь нажимает кнопку, вы должны сначала проверить, является ли это существующим пользователем. Если он затем зарегистрирует его в противном случае, сначала сохраните его информацию в db, а затем войдите в него.

  • 0
    Спасибо за ваш ответ, но я также хотел бы увидеть код, касающийся вашего решения, я не очень практичен, код, который я написал, я получил из учебника. Но я думаю, что для такого опытного человека, как ты, написать код не проблема. Мне было бы жаль ошибаться в отношении моего мнения о вас. Спасибо

Ещё вопросы

Сообщество Overcoder
Наверх
Меню