M. Loira
M. Loira

Reputation: 5

How to pass the value of a PHP variable within an EditText to Android Studio?

I wanted to ask you if you know how to pass the value of a variable in PHP into an EditText in android studio? Let me explain better, I have an android application in which there are 2 forms in which information is entered and saved in a MySQL database. The database has a table for the first form and a table for the second form, these two tables are linked and then the second table has an external key that is associated with the primary key of the first table that is inserted with the first form.

What I can not do is that once I entered the data in the first table and I got the primary key through mysqli Insert_id (), I do not know how to pass the value of the variable in $ People_id within an edittext present in the second form .

Below I leave my android code, there is a problem in the code of the second form because the data entered does not arrive to the PHP script.

So by summarizing the problem, does anyone know how to pass the primary key obtained with mysql insert id in the php file and put this value in the EditText present in the second form?

The first form save data into table 'Persone', the fields in this table are :

The second form saves the data in the table 'Persone2', the fields in this table are :

PS. In the second form the data are saved in the table 'People2', the fields 'Ruolo', 'Squadra' and 'Numero_maglia' are entered by the user, but the field 'id_People2' must already be inserted (the variable value must be there $ _SESSION ['People_id'] = $ People_id; value I get from the PHP script of the first form).

The first form works, idata are saved in the DataBase, but the second Form does not work, there is a problem on the android studio .JAVA file, but I do not understand what problem :(

the java file of the first form is :

import android.app.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;


import android.app.ProgressDialog;

import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;

import android.text.TextUtils;
import android.widget.Toast;
import java.net.FileNameMap;
import java.util.HashMap;


public class Activity1 extends AppCompatActivity {

    private EditText nome, cognome;

    private Button registrazione, login;

    //REGISTRAZIONE
    String F_Name_Holder, L_Name_Holder;
    String finalResult ;
    String HttpURLRegister = "http://provaord.altervista.org/NEW/RRR.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_1);




        nome = (EditText)findViewById(R.id.editText6);
        cognome = (EditText)findViewById(R.id.editText7);

        registrazione = (Button)findViewById(R.id.button5);
        login = (Button)findViewById(R.id.button3);



        registrazione.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(Activity1.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }


            }
        });



    }



    //REGISTRAZIONE
    public void CheckEditTextIsEmptyOrNot(){

        F_Name_Holder = nome.getText().toString();
        L_Name_Holder = cognome.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 Nome, final String Cognome){

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

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




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

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

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



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

                    finish();

                    Intent intent = new Intent(Activity1.this, Activity2.class);



                    startActivity(intent);

                }

            }

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

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

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



                finalResult = httpParse.postRequest(hashMap, HttpURLRegister);

                return finalResult;
            }
        }

        UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();

        userRegisterFunctionClass.execute(Nome,Cognome);
    }



}

The java file of the second form is :

import android.app.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;


import android.app.ProgressDialog;

import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;

import android.text.TextUtils;
import android.widget.Toast;
import java.net.FileNameMap;
import java.util.HashMap;

public class Activity2 extends AppCompatActivity {

    private EditText id, squadra, ruolo, numeromaglia;

    private Button registrazionee;

    //REGISTRAZIONE
    String Squadra_Holder, Ruolo_Holder, Numero_Maglia_Holder;
    String finalResult ;
    String HttpURLRegister = "http://provaord.altervista.org/NEW/R22.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_2);

       // id = (EditText)findViewById(R.id.editText6);
        squadra = (EditText)findViewById(R.id.editText7);
        ruolo = (EditText)findViewById(R.id.editText3);
        numeromaglia = (EditText)findViewById(R.id.editText4);

        registrazionee = (Button)findViewById(R.id.button55);

        registrazionee.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(Squadra_Holder, Ruolo_Holder, Numero_Maglia_Holder);

                }
                else {

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

                }


            }
        });



    }





    //REGISTRAZIONE
    public void CheckEditTextIsEmptyOrNot(){

        Squadra_Holder = squadra.getText().toString();
        Ruolo_Holder = ruolo.getText().toString();
        Numero_Maglia_Holder = numeromaglia.getText().toString();



        if(TextUtils.isEmpty(Squadra_Holder) || TextUtils.isEmpty(Ruolo_Holder) || TextUtils.isEmpty(Numero_Maglia_Holder) )
        {

            CheckEditText = false;

        }
        else {

            CheckEditText = true ;
        }

    }





    //REGISTRATION
    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    public void UserRegisterFunction(final String Squadra, final String Ruolo, final String Numero_maglia){

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

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




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

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

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



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

                    finish();

                    Intent intent = new Intent(Activity2.this, Activity3.class);



                    startActivity(intent);

                }

            }

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

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

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

                hashMap.put("Numero_maglia",params[2]);





                finalResult = httpParse.postRequest(hashMap, HttpURLRegister);

                return finalResult;
            }
        }

        UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();

        userRegisterFunctionClass.execute(Squadra, Ruolo, Numero_maglia);
    }


}

The java code for the HttpParse.java file is this:

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 ;
    }
}

The PHP file for the first form:

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

include 'C.php'; 

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

 $Nome = $_POST['Nome'];
 $Cognome = $_POST['Cognome'];


 $CheckSQL = "SELECT * FROM Persone WHERE Nome = '$Nome'";

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

 if(isset($check)){

 echo 'Utente già registrato';

 }
else{ 
$Sql_Query = "INSERT INTO Persone (Nome, Cognome) values ('$Nome','$Cognome')";



 if(mysqli_query($con,$Sql_Query))
{
    echo 'Registration Successfully';
    $People_id = mysqli_insert_id($con);
    $_SESSION ['People_id'] = $People_id;

}
else
{
 echo 'Something went wrong';
 }
 }

 mysqli_close($con);
}

?>

The PHP file for the second form:

<?php
error_reporting(E_ALL); 
ini_set('display_errors', 1);
session_start();
print_r($_POST);
if($_SERVER['REQUEST_METHOD']=='POST'){

include 'C.php'; 

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

 $Squadra = $_POST['Squadra'];
 $Ruolo = $_POST['Ruolo'];
 $Numero_maglia = $_POST['Numero_maglia'];


 $CheckSQL = "SELECT * FROM Persone, Persone2 WHERE Persone2.FK_persone = '" . ($_SESSION ['People_id']). "'";;

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

 if(isset($check)){

 echo 'Utente già registrato';

 }
else{ 
$Sql_Query = "INSERT INTO Persone2 (FK_persone, Squadra, Ruolo, Numero_maglia) values ('" . ($_SESSION ['People_id']). "','$Squadra', '$Ruolo', '$Numero_maglia')";



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

?>

The file XML to second form :

<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"
    tools:context="com.example.bruzi.myord.Activity2">

     <EditText
        android:id="@+id/editText6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="ID_People2"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />  

    <EditText
        android:id="@+id/editText7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="Squadra"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText6" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="Ruolo"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText7" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="Numero maglia"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText3" />

    <Button
        android:id="@+id/button55"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="32dp"
        android:layout_marginEnd="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:background="@android:color/holo_blue_light"
        android:text="Registrazione"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText4" />
</android.support.constraint.ConstraintLayout>

Upvotes: 0

Views: 1190

Answers (1)

Firas Shrourou
Firas Shrourou

Reputation: 715

It is a long journey, here are the steps:

First: You need to make sure that the php server returns the values needed in xml or json format, you can do so by creating a web service if you want.

Second: From android application you need to communicate with the web service using http post or get.

Third: The response coming back from the web service should be parsed by your android app. the parser will read the response and give you the needed fields values (there are many parsing packages available)

Forth: after getting the values, you can choose to store them in a preference or sqlite table (for future use) or directly send them to the next activity using intent.

When mastering this technique you will be able to make any kind of mobile app that needs a back-end server.

Good luck

Upvotes: 1

Related Questions