Android JSON ListView Master Detail

Android JSON ListView Master Detail







Quick Intro

The most popular data exchange format nowadays is JSON.It used to be XML.That's not the case nowadays.JSON is not popular because of any fluke.Its lighter and easier to read than XML.So its faster for both machine and human to work with.

Lets see how we can fetch some JSON from online then parse them and display in a listview.When the listview item is clicked we open a new activity passing data to the detail activity via intents.

Generally this is the plan :

  • Download JSON data from online.
  • We do this in the background thread using AsyncTask class.
  • We override methods like onPreExecute() where we show a progress dialog while loading data.
  • We do the real job via HttpURLConnection class,which belongs to  java.net package.
  • Our JSON data that we download,we parse using JSONArray and JSONObject native classes,no third party library.
  • Also we don't want to freeze the UI so we do this in the background thread too.
  • We then bind the data in the ListView.
  • When an Item is clicked in the listview,we open its details in the new activity.

OK,Lets say we have a user like this

 

public class User {
    String username,name,email;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

 

Then we want to download its details as below :

 

 

@@ -0,0 +1,134 @@
package com.tutorials.hp.jsonlistviewmdetail.m_JSON;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
/**
 * Created by Oclemy on 7/7/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 * -----------------------ROLES-------------------------
 * 1.CONNECT TO NETWORK
 * 2.DOWNLOAD DATA IN BACKGROUND THREAD
 * 3.SEND THE DATA TO PARSER TO BE PARSED
 */
public class JSONDownloader extends AsyncTask<Void,Void,String> {
    Context c;
    String jsonURL;
    ListView lv;
    ProgressDialog pd;
    public JSONDownloader(Context c, String jsonURL, ListView lv) {
        this.c = c;
        this.jsonURL = jsonURL;
        this.lv = lv;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd=new ProgressDialog(c);
        pd.setTitle("Download JSON");
        pd.setMessage("Downloading...Please wait");
        pd.show();
    }
    @Override
    protected String doInBackground(Void... voids) {
        return download();
    }
    @Override
    protected void onPostExecute(String jsonData) {
        super.onPostExecute(jsonData);
        pd.dismiss();
        if(jsonData.startsWith("Error"))
        {
            String error=jsonData;
            Toast.makeText(c, error, Toast.LENGTH_SHORT).show();
        }else
        {
            //PARSER
            new JSONParser(c,jsonData, lv).execute();
        }
    }
    //DOWNLOAD
    private String download()
    {
        Object connection=Connector.connect(jsonURL);
        if(connection.toString().startsWith("Error"))
        {
            return connection.toString();
        }
        try
        {
            HttpURLConnection con= (HttpURLConnection) connection;
            if(con.getResponseCode()==con.HTTP_OK)
            {
                //GET INPUT FROM STREAM
                InputStream is=new BufferedInputStream(con.getInputStream());
                BufferedReader br=new BufferedReader(new InputStreamReader(is));
                String line;
                StringBuffer jsonData=new StringBuffer();
                //READ
                while ((line=br.readLine()) != null)
                {
                    jsonData.append(line+"\n");
                }
                //CLOSE RESOURCES
                br.close();
                is.close();
                //RETURN JSON
                return jsonData.toString();
            }else
            {
                return "Error "+con.getResponseMessage();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();
        }
    }
}

 

Hey look everything is in the source code above.Just downlaod and import to your android studio or clone it.



Leave a Reply

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

14 + four =

COMMENTS