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:

<?php

 error_reporting(0);
 $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');
 exit($encoded);

?>


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="http://schemas.android.com/apk/res/android"
 package="com.example.eric.testjson">

 <application
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:supportsRtl="true"
  android:theme="@style/AppTheme">
  <activity android:name=".MainActivity">
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />

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


The following codes are from the main Android Java called MainActivity.java:

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

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  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 grabFromPHPServer.java. 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;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

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

 private Context context;

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

 protected void onPreExecute() {

 }

 @Override
 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 = "http://www.yourOwnURL.com/testJSON.php"+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());
  }
 }

 @Override
 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 grabFromPHPServer.java 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