Read Data Operation
In the upper part, we have created a PHP script for reading the data from the SQL table. In this part, we will integrate that in our Android App and read data to our SQL table from our Android app.
What we are going to build in this article?
We will be building a simple application in which we will be reading data from our SQL table by passing the ID. We will be reading this data using PHP scripts that we have created earlier. Below is the video in which we will get to see what we are going to build in this article.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.
implementation ‘com.android.volley:volley:1.1.1’
After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
Step 3: Adding permissions to the internet in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it.
XML
<!--permissions for INTERNET--> < uses-permission android:name = "android.permission.INTERNET" /> |
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" tools:context = ".MainActivity" > <!--Edit text for getting course id--> < EditText android:id = "@+id/idEdtCourseId" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginStart = "10dp" android:layout_marginTop = "20dp" android:layout_marginEnd = "10dp" android:hint = "Enter Course Id" android:importantForAutofill = "no" android:inputType = "number" /> <!--Button for adding your course to Firebase--> < Button android:id = "@+id/idBtnGetCourse" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "10dp" android:text = "Get Course Details" android:textAllCaps = "false" /> < androidx.cardview.widget.CardView xmlns:app = "http://schemas.android.com/apk/res-auto" android:id = "@+id/idCVCOurseItem" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "5dp" android:visibility = "gone" app:cardCornerRadius = "6dp" app:cardElevation = "4dp" > < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "2dp" android:orientation = "vertical" android:padding = "4dp" > <!--Textview for displaying our Course Name--> < TextView android:id = "@+id/idTVCourseName" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:padding = "2dp" android:text = "CourseName" android:textColor = "@color/purple_500" android:textSize = "18sp" android:textStyle = "bold" /> <!--Textview for displaying our Course Duration--> < TextView android:id = "@+id/idTVCourseDuration" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:padding = "2dp" android:text = "Duration" android:textColor = "@color/black" /> <!--Textview for displaying our Course Description--> < TextView android:id = "@+id/idTVCourseDescription" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:padding = "2dp" android:text = "Description" android:textColor = "@color/black" /> </ LinearLayout > </ androidx.cardview.widget.CardView > </ LinearLayout > |
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
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<String>() { @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<String, String> getParams() { // below line we are creating a map for storing our values in key and value pair. Map<String, String> params = new HashMap<String, String>(); // 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); } } |
Now run your app and see the output of the code.
Output:
CRUD Operation in MySQL Using PHP, Volley Android – Read Data
In the previous article, we have performed the insert data operation. In this article, we will perform the Read data operation. Before performing this operation first of all we have to create a new PHP script for reading data from SQL Database.
Prerequisite: You should be having Postman installed in your system to test this PHP script.