First, you must develop a contact service (WebService, REST, or whatever suits your needs) for your application. In my case, I am using a PHP script that generates a JSON response.
Here is a simple PHP script that connects to the database and outputs JSON ( json_encode method ):
<?php $link = mysqli_connect("localhost", "dbuser", "dbpassword", "database"); $response = array(); $pass = mysqli_query("select * from table"); while($data = mysqli_fetch_object($pass)) { array_push($response, array( "my_field" => $data->my_field )); } echo json_encode($response); mysqli_close($link);
? >
The script will output the JSON response as follows:
[{"my_field":1}]
When your application will request data using an HTTP POST or GET response, you will analyze the response using a library. Since I use JSON on the PHP side, I am currently using GSON for my projects.
To request JSON data from your Android application, you can use RestClass, which I took somewhere (I don't remember), but here is the code:
public class RestClient { private ArrayList <NameValuePair> params; private ArrayList <NameValuePair> headers; private String url; private int responseCode; private String message; private String response; public enum RequestMethod { GET, POST } public String getResponse() { return response; } public String getErrorMessage() { return message; } public int getResponseCode() { return responseCode; } public RestClient(String url) { this.url = url; params = new ArrayList<NameValuePair>(); headers = new ArrayList<NameValuePair>(); }
Then in your Android application you can create an instance of the RestClient class like this (you can even add a POST or GET parameter to the request):
RestClient c = new RestClient("http://www.myserver.com/json.php"); c.AddParam("my_field_value", 1); try { c.Execute(RequestMethod.POST);
And voila! You can use JSON data created using a PHP script from an Android application. Remember to add android.permission.INTERNET to your AndroidManifest.xml. Otherwise, your application will not be able to contact your PHP script.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Good luck.