fetch data from mysql

  • Replies:2
Rimpy
  • Forum posts: 1

Jun 13, 2017, 2:06:30 PM via Website

I want to import data from MySql to android. I am using android studio.

Reply
Dev Lt
  • Forum posts: 54

Jun 16, 2017, 4:27:15 PM via Website

so just write php scripts for your web server and send queries from Android app

Reply
Jeremiah Kalaiyo
  • Forum posts: 4

Jun 18, 2017, 9:37:51 PM via Website

*All you have to do is get a host server.
*write a php script to select from the database in the server that throws a json response.

*add this below:

while (mysqli_stmt_fetch($statement)){

$response ["success"] = true;
$response ["Name"] = $name;
$response ["Number"] = $number;
}

echo json_encode($response);

*upload the php file into the online server in the public folder located in the file manager in that server.

*Then in the activity add this to the Response.Listener onResponse event
String name = jsonResponse.getString("Name");
Int number= jsonResponse.getString("Number");

make sure your Request.java class is available.

FetchRequest.java below

public class FetchRequest extends StringRequest {

private static final String FETCH_REQUEST_URL = "Domain/FetchData.php";
private Map<String, String> params;

public FetchRequest (String name, String number, Response.Listener<String> listener){
    super(Method.POST, FETCH_REQUEST_URL, listener, null);
    params =  new HashMap<>();
    params.put("Name", name);
    params.put("Number", number);
}

@Override
public Map<String, String> getParams() {
    return params;
}

}

MainActivity.java below

Response.Listener responseListener = new Response.Listener() {

                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if (success) {

                      // this is the gotten data retrieved from the daabase in the server
                            String name = jsonResponse.getString("Name");
                            int number= jsonResponse.getString("Number");

                        } else {

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            };


            FetchRequest fetchRequest = new FetchRequest(name, number, responseListener);
            RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
            queue.add(fetchRequest)

dont forget to add in your build.gradle:app
dependencies:
'com.android.volley:volley:1.0.0'

— modified on Jun 18, 2017, 9:46:15 PM

Reply