如何将EditText中的PHP变量值传递给Android Studio?

时间:2018-03-27 12:33:28

标签: java php android-studio

我想问你是否知道如何将PHP中变量的值传递给android studio中的EditText? 让我解释一下,我有一个Android应用程序,其中有两种形式,其中输入信息并保存在MySQL数据库中。 数据库有第一个表单的表和第二个表的表,这两个表是链接的,然后第二个表有一个外键,该外键与第一个表插入的第一个表的主键相关联。

我不能做的是,一旦我输入第一个表中的数据并通过mysqli Insert_id ()得到主键,我不知道如何在一个edittext中传递$ People_id中变量的值以第二种形式出现。

下面我留下我的android代码,第二种形式的代码存在问题,因为输入的数据没有到达PHP脚本。

通过总结问题,有没有人知道如何在php文件中传递使用mysql insert id获得的主键,并将此值放在第二种形式的EditText中?

第一种形式将数据保存到表格' Persone'中,此表中的字段为:

  • id(PK)
  • 姓名和姓氏(VARCHAR)

第二种形式将数据保存在表格Persone2'中,此表中的字段为:

  • idP2(PK)
  • FK_persone(外键)
  • Squadra,Ruolo和Numero_maglia(VARCHAR)

PS。在第二种形式中,数据保存在表格'人物2'字段' Ruolo' Squadra'和' Numero_maglia'由用户输入,但字段“id_People2'必须已经插入(变量值必须是我从第一个表单的PHP脚本获得的$ _SESSION ['People_id'] = $ People_id;值。)

第一个表单有效,idata保存在DataBase中,但第二个Form不起作用,android studio .JAVA文件有问题,但我不明白是什么问题:(

第一种形式的java文件是:

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



}

第二种形式的java文件是:

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


}

HttpParse.java文件的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 ;
    }
}

第一种形式的PHP文件:

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

?>

第二种形式的PHP文件:

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

?>

文件XML到第二种形式:

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

1 个答案:

答案 0 :(得分:1)

这是一个漫长的旅程,以下是步骤:

首先:您需要确保php服务器返回xml或json格式所需的值,您可以通过创建Web服务来实现。

第二:从Android应用程序中,您需要使用http post或get来与Web服务进行通信。

第三:来自Web服务的响应应该由您的Android应用程序解析。解析器将读取响应并为您提供所需的字段值(有许多可用的解析包)

Forth:获取值后,您可以选择将它们存储在首选项或sqlite表中(以备将来使用),或者直接使用intent将它们发送到下一个活动。

掌握此技术后,您将能够制作任何需要后端服务器的移动应用程序。

祝你好运