Friday, September 15, 2017

Android Java to Get JSON Data from Server via PHP

The following Android Java codes are based on Android Studio 2.3. In order for Android to obtain information from a server such as the login password verification, the easiest way is to connect to a web server via PHP. Android then establishes a connection to the server through a URL or a link to a PHP script. The following shows the PHP portion of the codes. I named this file testJSON.php:


 $all = array();

 if ($_POST['pc'] == "android") {
  $all[0] = array("a"=>1,"b"=>2,"c"=>3);
  $all[1] = array("d"=>4,"e"=>5,"f"=>6);
  $all[2] = array("g"=>7,"h"=>8,"i"=>9);

 $encoded = json_encode($all);
 header('Content-type: application/json');


The following will be the codes from the Android Studio side. But before going into the Java coding, one must make sure Android can access to the Internet. This can be achieved by adding the following line in red in the AndroidManifest.xml file.

<manifest xmlns:android=""

  <activity android:name=".MainActivity">
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
 <uses-permission android:name="android.permission.INTERNET"/>

The following codes are from the main Android Java called

package com.example.eric.testjson; // Your package name will be different, there is no need to paste this code to your file.

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

 protected void onCreate(Bundle savedInstanceState) {

  new grabFromPHPServer(this).execute("android"); // "android" is a parameter that will be passed to doInBackground in grabFromPHPServer Java sub class

The following codes are from the Java class called You can create this Java class by right clicking your Java folder.

package com.example.eric.testjson; // you use your own package info, no need to paste this to your java file

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

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


public class grabFromPHPServer extends AsyncTask<String, Void, String> {

 private Context context;

 public grabFromPHPServer(Context context) {
  this.context = context;

 protected void onPreExecute() {


 protected String doInBackground(String... arg) {

  String passcode = arg[0];
  String link;
  String data;
  BufferedReader bufferedReader;
  String result;

  Log.d("result","start trying to grab from PHP server...");
  try {
   Log.d("result","preparing parameter sent to server...");

   data = "?pc=" + URLEncoder.encode(passcode, "UTF-8");

   link = ""+data;
   URL url = new URL(link);
   HttpURLConnection con = (HttpURLConnection) url.openConnection();
   Log.d("result","connection response: "+con.toString());

   bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
   result = bufferedReader.readLine();

   Log.d("result",result.toString()); // spit all JSON data received

   String jSONString = result;
   if (jSONString != null) {
    Log.d("result", "jSON received: "+jSONString.toString());
    JSONArray jsonArr = new JSONArray(jSONString);
    JSONObject query_result = jsonArr.getJSONObject(0);
    Log.d("result", "a->"+query_result.getString("a"));
    query_result = jsonArr.getJSONObject(1);
    Log.d("result", "e->"+query_result.getString("e"));
    query_result = jsonArr.getJSONObject(2);
    Log.d("result", "g->"+query_result.getString("g"));
   else {
    Log.d("result", "jSON received is null");
   return result;
  } catch (Exception e) {
   Log.d("result","grab failed");
   return new String("Exception: " + e.getMessage());

 protected void onPostExecute(String result) {
  // you can also process your jSON here

AsyncTask extension is crucial in the Java class as it is quite meaningless if you run the connection in your main activity Java class as the connection takes time and you will get an exception error if the JSON data failed to be received within a short period of wait time. But in order to use AsyncTask extension, you need to create a sub class to handle background tasks such as this sub class. Please also replace yourOwnURL with your own domain name where your PHP file resides.

The following is the screen shot I took from my Android Monitor. The log is filtered with the keyword 'result' so that I only see output from my very own Log.d results:

No comments:

Post a Comment