📜  使用PHP和Volley Android在MySQL中进行CRUD操作–读取数据

📅  最后修改于: 2021-05-13 16:52:16             🧑  作者: Mango

在上一篇文章中,我们执行了插入数据操作。在本文中,我们将执行读取数据操作。首先,执行此操作之前,我们必须创建一个新的PHP脚本以从SQL数据库读取数据

先决条件:您应该在系统中安装Postman来测试此PHP脚本。

创建一个PHP脚本以从My SQL数据库中读取数据

我们将构建一个简单的PHP脚本,在该脚本中,我们将使用该脚本从我们在上一篇文章中创建的SQL表中读取数据。使用此脚本,我们将从SQL表中读取数据。

分步实施

步骤1:启动您的XAMPP服务器,我们在上一篇文章中已经看到

在上一篇文章中,我们已经看到启动XAMPP服务器,并且还创建了数据库。在本文中,我们将创建一个脚本,用于将数据添加到数据库中。

步骤2:浏览至xampp资料夹

现在,我们必须导航到您PC中的C驱动器,并在其中检查文件夹名称是否为xampp。在该文件夹内,导航到htdocs文件夹并在其中创建一个新文件夹,并将其命名为courseApp。在此文件夹中,我们将存储所有PHP脚本。现在,您可以使用任何简单的文本编辑器来编写PHP脚本。我正在使用VS代码。创建此文件夹后,我们只需要用VS代码打开此文件夹。

步骤3:建立新的PHP档案

用VS代码打开文件夹后,在该文件夹内,我们必须按快捷键,因为Ctrl + N将创建新文件。我们必须使用名称readCourses保存该文件。 PHP并添加以下代码。在代码中添加了注释,以便更详细地了解。

PHP
prepare("SELECT courseName,courseDescription,courseDuration FROM courseDb WHERE id = ?");
     $stmt->bind_param("s",$id);
     $result = $stmt->execute();
   // on below line we are checking if our 
   // table is having daata with specific id. 
   if($result == TRUE){
         // if we get the respone then we are displaying it below.
         $response['error'] = false;
         $response['message'] = "Retrieval Successful!";
         // on below line we are getting our result. 
         $stmt->store_result();
         // on below line we are passing parameters which we want to get.
         $stmt->bind_result($courseName,$courseDescription,$courseDuration);
         // on below line we are fetching the data. 
         $stmt->fetch();
         // after getting all data we are passing this data in our array.
         $response['courseName'] = $courseName;
         $response['courseDescription'] = $courseDescription;
         $response['courseDuration'] = $courseDuration;
     } else{
         // if the id entered by user donot exist then 
         // we are displaying the error message
         $response['error'] = true;
         $response['message'] = "Incorrect id";
     }
 } else{
      // if the user donot adds any paramter while making request
      // then we are displaying the error as insufficient parameters.
      $response['error'] = true;
      $response['message'] = "Insufficient Parameters";
 }
 // at last we are printing 
 // all the data on below line. 
 echo json_encode($response);
?>


XML


XML


  
    
    
  
    
    


Java
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
  
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.HashMap;
import java.util.Map;
  
public class MainActivity extends AppCompatActivity {
      
    // creating variables for our edit text
    private EditText courseIDEdt;
      
    // creating variable for button
    private Button getCourseDetailsBtn;
      
    // creating variable for card view and text views.
    private CardView courseCV;
    private TextView courseNameTV, courseDescTV, courseDurationTV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing all our variables.
        courseNameTV = findViewById(R.id.idTVCourseName);
        courseDescTV = findViewById(R.id.idTVCourseDescription);
        courseDurationTV = findViewById(R.id.idTVCourseDuration);
        getCourseDetailsBtn = findViewById(R.id.idBtnGetCourse);
        courseIDEdt = findViewById(R.id.idEdtCourseId);
        courseCV = findViewById(R.id.idCVCOurseItem);
          
        // adding click listener for our button.
        getCourseDetailsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking if the id text field is empty or not.
                if (TextUtils.isEmpty(courseIDEdt.getText().toString())) {
                    Toast.makeText(MainActivity.this, "Please enter course id", Toast.LENGTH_SHORT).show();
                    return;
                }
                // calling method to load data.
                getCourseDetails(courseIDEdt.getText().toString());
            }
        });
    }
  
    private void getCourseDetails(String courseId) {
          
        // url to post our data
        String url = "http://localhost/courseApp/readCourses.php";
          
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
          
        // on below line we are calling a string 
        // request method to post the data to our API
        // in this we are calling a post method.
        StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener() {
            @Override
            public void onResponse(String response) {
                try {
                    // on below line passing our response to json object.
                    JSONObject jsonObject = new JSONObject(response);
                    // on below line we are checking if the response is null or not.
                    if (jsonObject.getString("courseName") == null) {
                        // displaying a toast message if we get error
                        Toast.makeText(MainActivity.this, "Please enter valid id.", Toast.LENGTH_SHORT).show();
                    } else {
                        // if we get the data then we are setting it in our text views in below line.
                        courseNameTV.setText(jsonObject.getString("courseName"));
                        courseDescTV.setText(jsonObject.getString("courseDescription"));
                        courseDurationTV.setText(jsonObject.getString("courseDuration"));
                        courseCV.setVisibility(View.VISIBLE);
                    }
                    // on below line we are displaying
                    // a success toast message.
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // method to handle errors.
                Toast.makeText(MainActivity.this, "Fail to get course" + error, Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            public String getBodyContentType() {
                // as we are passing data in the form of url encoded 
                // so we are passing the content type below
                return "application/x-www-form-urlencoded; charset=UTF-8";
            }
  
            @Override
            protected Map getParams() {
                 
                // below line we are creating a map for storing our values in key and value pair.
                Map params = new HashMap();
                  
                // on below line we are passing our key and value pair to our parameters.
                params.put("id", courseId);
                  
                // at last we are returning our params.
                return params;
            }
        };
        // below line is to make 
        // a json object request.
        queue.add(request);
    }
}


步骤4:获取PHP脚本的URL

为了获取我们的PHP脚本的URL,我们只需要在浏览器中键入localhost,然后将其附加我们的文件夹名称和文件名即可。您将看到以下突出显示的URL:

http://localhost/courseApp/readCourses.php

现在,我们将使用Postman测试我们的API。

步骤5:在Postman中测试我们的PHP脚本

为了测试您的PHP脚本,请选择postman中的POST方法,因为我们将从SQL表中获取数据,并在URL部分内添加上述URL。添加URL之后。现在,单击下面的屏幕快照中所示的“正文”选项卡,并在其中选择x-www-form-urlencoded,然后在下面的部分中添加参数,如屏幕快照所示。确保您输入的键必须与用于在SQL表中命名列的键相同。添加完所有数据之后。现在,单击“发送”选项以发送我们的ID并从我们的SQL表接收数据。

您将在上面的屏幕上看到来自API的响应。

读取数据操作

在上半部分,我们创建了一个PHP脚本来从SQL表中读取数据。在这一部分中,我们将把它集成到我们的Android应用程序中,并从我们的Android应用程序中将数据读取到我们的SQL表中。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在该应用程序中,我们将通过传递ID从SQL表中读取数据。我们将使用之前创建的PHP脚本读取此数据。下面是视频,我们将在其中观看我们将要构建的内容。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在您的build.gradle文件中添加以下依赖项

以下是Volley的依赖关系,我们将使用它们来从API获取数据。要添加此依赖关系,请导航至应用程序> Gradle脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。

implementation ‘com.android.volley:volley:1.1.1’

添加此依赖项后,同步您的项目,现在移至AndroidManifest.xml部分。

步骤3:在AndroidManifest.xml文件中向Internet添加权限

导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。

XML格式



步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  
    
    

步骤5:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
  
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.HashMap;
import java.util.Map;
  
public class MainActivity extends AppCompatActivity {
      
    // creating variables for our edit text
    private EditText courseIDEdt;
      
    // creating variable for button
    private Button getCourseDetailsBtn;
      
    // creating variable for card view and text views.
    private CardView courseCV;
    private TextView courseNameTV, courseDescTV, courseDurationTV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing all our variables.
        courseNameTV = findViewById(R.id.idTVCourseName);
        courseDescTV = findViewById(R.id.idTVCourseDescription);
        courseDurationTV = findViewById(R.id.idTVCourseDuration);
        getCourseDetailsBtn = findViewById(R.id.idBtnGetCourse);
        courseIDEdt = findViewById(R.id.idEdtCourseId);
        courseCV = findViewById(R.id.idCVCOurseItem);
          
        // adding click listener for our button.
        getCourseDetailsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking if the id text field is empty or not.
                if (TextUtils.isEmpty(courseIDEdt.getText().toString())) {
                    Toast.makeText(MainActivity.this, "Please enter course id", Toast.LENGTH_SHORT).show();
                    return;
                }
                // calling method to load data.
                getCourseDetails(courseIDEdt.getText().toString());
            }
        });
    }
  
    private void getCourseDetails(String courseId) {
          
        // url to post our data
        String url = "http://localhost/courseApp/readCourses.php";
          
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
          
        // on below line we are calling a string 
        // request method to post the data to our API
        // in this we are calling a post method.
        StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener() {
            @Override
            public void onResponse(String response) {
                try {
                    // on below line passing our response to json object.
                    JSONObject jsonObject = new JSONObject(response);
                    // on below line we are checking if the response is null or not.
                    if (jsonObject.getString("courseName") == null) {
                        // displaying a toast message if we get error
                        Toast.makeText(MainActivity.this, "Please enter valid id.", Toast.LENGTH_SHORT).show();
                    } else {
                        // if we get the data then we are setting it in our text views in below line.
                        courseNameTV.setText(jsonObject.getString("courseName"));
                        courseDescTV.setText(jsonObject.getString("courseDescription"));
                        courseDurationTV.setText(jsonObject.getString("courseDuration"));
                        courseCV.setVisibility(View.VISIBLE);
                    }
                    // on below line we are displaying
                    // a success toast message.
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // method to handle errors.
                Toast.makeText(MainActivity.this, "Fail to get course" + error, Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            public String getBodyContentType() {
                // as we are passing data in the form of url encoded 
                // so we are passing the content type below
                return "application/x-www-form-urlencoded; charset=UTF-8";
            }
  
            @Override
            protected Map getParams() {
                 
                // below line we are creating a map for storing our values in key and value pair.
                Map params = new HashMap();
                  
                // on below line we are passing our key and value pair to our parameters.
                params.put("id", courseId);
                  
                // at last we are returning our params.
                return params;
            }
        };
        // below line is to make 
        // a json object request.
        queue.add(request);
    }
}

现在运行您的应用程序,然后查看代码输出。

输出: