Connect Android to PHP and Read Data from PHP API

This is an android app that I have been doing my tests on. In this app, I connected my android app to a PHP data source, read data from the PHP source and displayed it on the main page as a List. In this case, a list of highest mountains is pulled from a PHP API to be displayed in the Android applicaction.

First thing first, let’s create a PHP data source for the app to read from. Let’s create a file named read.php as below:

<?php
	$highestmountains = array("Mount Everest", "Mount K2", "Mount Kanchenjunga", "Mount Lhotse", "Mount Makalu", 
"Mount Cho Oyu", "Mount Dhaulagiri I", "Mount Manaslu", "Mount Nanga Parbat", "Mount Annapurna I");
	$heights = array("8,848m", "8,611m", "8,586m ", "8,516m", "8,485m", "8,188m", "8,167m", "8,163m", "8,126m", "8,091m");
	$mountainrange = array("Mahalangur Himalaya", "Baltoro Karakoram", "Kangchenjunga Himalaya", "Mahalangur Himalaya",
 "Mahalangur Himalaya", "Mahalangur Himalaya", "Dhaulagiri Himalaya", "Manaslu Himalaya", "Nanga Parbat Himalaya", 
"Annapurna Himalaya");

            $data = array();
            $data["highest_mountains"] = array();
	    for($ctr = 0; $ctr < 10; $ctr++){
	        $highestmountain = array();             

	        $highestmountain["name"] = $highestmountains[$ctr];
	        $highestmountain["height"] = $heights[$ctr];
	        $highestmountain["mountainrange"] = $mountainrange[$ctr];
              
	        array_push($data["highest_mountains"], $highestmountain);
	    }
	    $data["source"] = "Wikipedia";
	    $data["success"] = 1;
	    echo json_encode($data);
	?>

This is a simple code in PHP that puts data in arrays so as to send them to the Android app in JSON Format. The structure of the resulting JSON message will be as below:

{
     "highest_mountains":[
          {
               "name":"Mount Everest",
               "height":"8,848m",
               "mountainrange":"Mahalangur Himalaya"
          },
          {
               "name":"Mount K2",
               "height":"8,611m",
               "mountainrange":"Baltoro Karakoram"
          },
          {
               "name":"Mount Kanchenjunga",
               "height":"8,586m ",
               "mountainrange":"Kangchenjunga Himalaya"
          },
          {
               "name":"Mount Lhotse",
               "height":"8,516m",
               "mountainrange":"Mahalangur Himalaya"
          },
          {
               "name":"Mount Makalu",
               "height":"8,485m",
               "mountainrange":"Mahalangur Himalaya"
          },
          {
               "name":"Mount Cho Oyu",
               "height":"8,188m",
               "mountainrange":"Mahalangur Himalaya"
          },
          {
               "name":"Mount Dhaulagiri I",
               "height":"8,167m",
               "mountainrange":"Dhaulagiri Himalaya"
          },
          {
               "name":"Mount Manaslu",
               "height":"8,163m",
               "mountainrange":"Manaslu Himalaya"
          },
          {
               "name":"Mount Nanga Parbat",
               "height":"8,126m",
               "mountainrange":"Nanga Parbat Himalaya"
          },
          {
               "name":"Mount Annapurna I",
               "height":"8,091m",
               "mountainrange":"Annapurna Himalaya"
          }
     ],
     "source":"Wikipedia",
     "success":1
}

This is how the data looks like with fixed alignments. It will be different when opened in the browser. For the purpose of this post, the data has been uploaded to:

http://saurabrajkarnikar.com/read.php

Now the Android App. For this purpose, we can create a simple Android App with Blank Activity. Firstly, we need to change the AndroidManifest.xml file for permissions to access the wireless and/or internet. For that add the following permissions in the AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Now add the following to the main_activity.xml file or the default xml file in the Android application.

     <TextView android:text="Source : Wikipedia" android:layout_width="wrap_content"
               android:layout_height="wrap_content"
	       android:id="@+id/source" />
	
      <Button
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="Get Data"
	        android:id="@+id/getData"
	        android:layout_below="@+id/source"
	        android:layout_alignParentStart="true"
	        android:layout_marginTop="18dp" />

	<ListView
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:id="@+id/list"
	        android:layout_below="@+id/getData"
	        android:layout_alignParentStart="true" />

Here, when the user clicks the “Get Data” button, the app requests data from the PHP API and displays it in the ListView.

Now, to display the values in the “ListView”, create a layout file for the ListView format and name it “list_item.xml”.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:orientation="horizontal" >

	    <TextView
	        android:id="@+id/mountainName"
	        android:layout_width="130dp"
	        android:layout_height="wrap_content" />

	    <TextView
	        android:id="@+id/mountainHeight"
	        android:layout_width="75dp"
	        android:layout_height="wrap_content" />

	    <TextView
	        android:id="@+id/mountainRange"
	        android:layout_width="120dp"
	        android:layout_height="wrap_content" />
	</LinearLayout>

Now, go to the MainActivity class or the activity class that the data is to be read by. and change/add the following:

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import np.com.saurab.testphase.R;	

public class PhoneActivity extends AppCompatActivity{
    boolean d = true;
    protected static final String TAG = "MainActivity";
    Button getDataButton;
    ArrayList<HashMap<String, String>> allList;

    String TAG_HIGHEST_MOUNTAINS = "highest_mountains";
    String TAG_NAME = "name";
    String TAG_HEIGHT = "height";
    String TAG_MOUNTAIN_RANGE = "mountainrange";

    private static String urlString = "http://saurabrajkarnikar.com/read.php";

    TextView sourceTV;
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone);
 
       listView = (ListView) findViewById(R.id.list);
       sourceTV = (TextView) findViewById(R.id.source);

       getDataButton = (Button) findViewById(R.id.getData);
       getDataButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  new ReadOnlineData().execute();
             }
       });
    }

    class ReadOnlineData extends AsyncTask<String, String, String> {
         @Override
         protected String doInBackground(String... params) ;
               URL url = null;
               try {
	                url = new URL(urlString);
	                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
	                httpURLConnection.setRequestMethod("POST");

	                if(d) Log.d(TAG, "Response Code: " + httpURLConnection.getResponseCode());
	                InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
	                String dataFromAPI = changeInputStreamToString(in);
	                if (d) Log.d(TAG, "Response : " + dataFromAPI);

	                JSONObject jsonObject = new JSONObject(dataFromAPI);
	                JSONArray highestMountains = jsonObject.getJSONArray(TAG_HIGHEST_MOUNTAINS);
	                allList = new ArrayList<HashMap<String, String>>();
	                for(int i=0; i<highestMountains.length(); i++){
	                    JSONObject highestMountain = highestMountains.getJSONObject(i);

	                    String name = highestMountain.getString(TAG_NAME);
	                    String height = highestMountain.getString(TAG_HEIGHT);
	                    String mountainRange = highestMountain.getString(TAG_MOUNTAIN_RANGE);

	                    HashMap<String, String> map = new HashMap<String, String>();
	                    map.put(TAG_NAME, name);
	                    map.put(TAG_HEIGHT, height);
	                    map.put(TAG_MOUNTAIN_RANGE, mountainRange);

	                    allList.add(map);
	                }
	            } catch (MalformedURLException e) {
	                e.printStackTrace();
	            } catch (IOException e) {
	                e.printStackTrace();
	            } catch (JSONException e) {
	                e.printStackTrace();
	            }
	            return null;
	        }

	        @Override
	        protected void onPostExecute(String s) {
	            runOnUiThread(new Runnable() {
	                @Override
	                public void run() {
	                    ListAdapter adapter = new SimpleAdapter(
	                            PhoneActivity.this, allList, R.layout.list_item, new String[]{TAG_NAME, TAG_HEIGHT, TAG_MOUNTAIN_RANGE},
	                            new int[]{R.id.mountainName, R.id.mountainHeight, R.id.mountainRange}
	                    );

	                    listView.setAdapter(adapter);
	                }
	            });
	        }
	    }

	    private String changeInputStreamToString(InputStream in){
	        String bufferedReaderLine = "";
	        StringBuilder jsonString = new StringBuilder();
	        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));

	        try {
	            while ((bufferedReaderLine = bufferedReader.readLine()) != null){
	                jsonString.append(bufferedReaderLine);
	            }
	        }catch (IOException e){
	            Log.e(TAG, "Exception : " + e.getMessage());
	        }
	        return jsonString.toString();
	    }
}

Now the App can be “Run” and installed in the Android Phone. In the Android device, once the user clicks on the the “GET DATA” button the Android App will read the JSON format data from the PHP API and display it in the “ListView” in the app itself. The App will be as shown below:

This application uses “HttpURLConnection” class to connect with the PHP api server URL with request method set to “POST“. Once connected, the application gets data as an “InputStream” which is changed to “String” using the “StringBuilder” class as displayed in function “changeInputStreamToString“. The “String” value is in turn converted into a “JSONObject” from which the data is extracted as required and displayed in the “ListView“.

Add a Comment

Your email address will not be published. Required fields are marked *