0

I have a php code running on a wamp server which returns all the contents of database as a JSON array. I want to connect my android app to this php file. How do i get the response of this php file to my android java code.

MY PHP CODE:

<?php

$con = mysqli_connect("localhost","root","2015","testdatabase") or die("Error " . mysqli_error($link));
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$result = mysqli_query($con,"SELECT * FROM Customer");
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysqli_close($con);
?>

Also here is what I'm currently doing in my android code (But most of what i am doing is deemed deprecated):

public JSONArray GetAllCustomers()
    {
        // URL for getting all customers
        String url = "http://127.0.0.1/Customers/getAllCustomers.php";

        // Get HttpResponse Object from url.
        // Get HttpEntity from Http Response Object
        HttpEntity httpEntity = null;

        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);

            httpEntity = httpResponse.getEntity();

        } catch (ClientProtocolException e) {
            // Signals error in http protocol
            e.printStackTrace();

            //Log Errors Here

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

        // Convert HttpEntity into JSON Array
        JSONArray jsonArray = null;

        if (httpEntity != null) {
            try {
                String entityResponse = EntityUtils.toString(httpEntity);

                Log.e("Entity Response  : ", entityResponse);

                jsonArray = new JSONArray(entityResponse);

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

        return jsonArray;

    }
}
7
  • You could be as kind first to remove a lot of empty lines. Commented Aug 11, 2015 at 7:53
  • Google for entitytostring. Commented Aug 11, 2015 at 7:57
  • 127.0.0.1. You are not using that ip. Are you? Commented Aug 11, 2015 at 7:58
  • should i change it to localhost? Commented Aug 11, 2015 at 8:02
  • No. Because localhost is the same as 127.0.0.1. Commented Aug 11, 2015 at 13:12

1 Answer 1

1

I also connect php web services(Json formatted) with android according to this tutorial. I think it will also helpful to you also.

How to connect Android with PHP, MySQL

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.