Get data from PHP and MySQL in Android Java

Get data from PHP and MySQL in Android Java

In this tutorial, we will teach you how you can get data from database using PHP and MySQL in Android Java. We will be using Volley for sending HTTP request.

Following will be the structure of users table from where we will fetch data. You can add more fields as per your need. Important thing here is auto-increment primary key ID:

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

We will be sending an HTTP request to a PHP server, here it is it’s code:

get-data.php

<?php

    $userId = $_POST["userId"];
    $conn = mysqli_connect("localhost", "root", "root", "tutorials");

    $sql = "SELECT * FROM `users` WHERE `id` = '" . $userId . "'";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0)
    {
        $row = mysqli_fetch_object($result);

        echo json_encode(array(
            "status" => "success",
            "message" => "Successfully logged in",
            "user" => $row
        ));
    }
    else
    {
        echo json_encode(array(
            "status" => "error",
            "message" => "User not found"
        ));
    }
    exit();

?>
  1. First we are getting userId which will be sent by android app using POST method.
  2. Then we are connecting with MySQL database using host, username, password and database name respectively.
  3. Then we are fetching data from users table using his ID.
  4. Check if record does not exists, then simply send an error message as response. All responses must be in JSON string.
  5. If exists, then simply fetch that row, and send in response. That will be received by android.

Now include Volley in your android project’s app/build.gradle:

dependencies {
    ...

    // To convert JSON string into Java class object
    implementation 'com.google.code.gson:gson:2.8.5'

    // To send an HTTP request to PHP server
    implementation 'com.android.volley:volley:1.1.1'
}

First, we need to define the structure of data received from server. Create a class in your android project’s java package named UserModel.java, you can add more fields as per need:

public class UserModel {

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Now simply send an HTTP request using Volley and convert the response into this UserModel class:

String url = "http://localhost/tutorials/get-data.php";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {
                    JSONObject responseJson = new JSONObject(response);
                    String status = responseJson.getString("status");
                    String message = responseJson.getString("message");

                    if (status.contains("error")) {
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                    } else {
                        UserModel userModel = new Gson().fromJson(responseJson.getString("user"), UserModel.class);

                        // do whatever you want with userModel
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        error.printStackTrace();
        Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
    }
}) {
    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("userId", "1");

        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.put("Content-Type", "application/x-www-form-urlencoded");
        return params;
    }
};

// To prevent timeout error
stringRequest.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

// Add the request to the RequestQueue.
stringRequest.setShouldCache(false);
queue.add(stringRequest);
  1. We are sending request to get-data.php file.
  2. The method should be POST. We are sending userId parameter and sending the value in it. You might be storing this ID in shared preference. Learn how to save values in Shared Preference from here.
  3. When the response is received, we are simply converting that into JSON. Getting status and message strings.
  4. If the status is “error”, then simply display a message in Toast.
  5. Then convert the “user” key into UserModel class object and save it in object named userModel.
  6. Now you can use that object however you want.

Now that you have learned to fetch data from database using PHP and MySQL and convert that into Android Java class object, learn how to save the data from android to PHP and MySQL.

Leave a Reply

Please disable your adblocker or whitelist this site!