Android parse json from url

In this Android tip, I am going to show you how to parse a JSON string from a url. To achieve the goal you follow the steps below:
1. You need a PHP page on your remote server to return the JSON string. In my case, I have getoutlet.php file hosted at http://www.gtwebsolutions.net/hd/. The getoutlet.php file fetches data from mysql database and returns a json string as you see in the picture below. The json string will be transferred to Android and parsed there.

parse json from url
2. Create a new project in Android Studio. Add id and orientation attributes to the layout of activity_main.xml file.



<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
   xmlns:tools= "http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:id="@+id/layoutparent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:orientation="vertical"
   >
</LinearLayout>


In the MainActivity class, you create a class called BackTaskGetJSON that extends Asynctask. It represents a background process to connect to the remote server and get the json string. In the onCreate() method of the MainActivity class, you execute the background process. In the onPostExecute() method of BackTaskGetJSON class, you pass the response json string to the showResult() method to be parsed.


import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends ActionBarActivity {
   Activity context;
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     // Execute background task to read json string from url
     BackTaskGetJSON backTaskGetJSON= new BackTaskGetJSON();
     backTaskGetJSON.execute();

   }
   private void showResult(String jsonString){
     // Reference to the parent layout
     LinearLayout layoutroot= (LinearLayout)findViewById(R.id.layoutparent);
     //Parse Json and show output
     try {
        JSONArray jArr=new JSONArray(jsonString);
        for(int i=0;i<jArr.length();i++) {
           JSONObject obj=jArr.getJSONObject(i);
           // Create layout to display the outlet info (id and name)
           LinearLayout cust_layout = new LinearLayout(MainActivity.this);
           cust_layout.setBackgroundColor(Color.parseColor("#f8f8f8"));
           LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
           params.setMargins(15, 5, 5, 5);
           cust_layout.setLayoutParams(params);           cust_layout.setOrientation( LinearLayout.HORIZONTAL);
           cust_layout.setHorizontalGravity(Gravity.CENTER_HORIZONTAL);
           cust_layout.setPadding(10, 10, 5, 5);
           // Create textviews for id and name
           TextView tvId=new TextView(MainActivity.this);
           tvId.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
           tvId.setText(obj.getString("outlet_id"));
           TextView tvName=new TextView(MainActivity.this);
           tvId.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
           tvName.setText(obj.getString("outlet_name"));
           // Add textviews to layout
           cust_layout.addView(tvId);
           cust_layout.addView(tvName);
           // Add layout to its parent
           layoutroot.addView(cust_layout);
        }

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

   //background process to get outlet info at remotee server
   private class BackTaskGetJSON extends AsyncTask<String,Void,Void> {
     String jsonString="";

     protected Void doInBackground(String...params){

        try{
           HttpClient httpclient=new DefaultHttpClient();
           HttpPost httppost= new HttpPost("http://www.gtwebsolutions.net/hd/getoutlet.php"); //delivery linux
           ResponseHandler<String> responseHandler = new BasicResponseHandler();
           // Get json string from the url
           jsonString= httpclient.execute(httppost, responseHandler);
        }catch(Exception e){
           e.printStackTrace();
        }
        return null;
     }
     protected void onPostExecute(Void result){
        try{
           if(!jsonString.equals("")) {
             // Parse json and show output
             showResult(jsonString);
           }
        }catch(Exception e){e.printStackTrace();}
     }

   }
}

Before you run the example application, do not forget to declare INTERNET person in AndroidManifest.xml file.

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



parse json from url

Posted by: Dara | post date: 04-13-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.