Simple Android JSON parsing example with output into ListActivity

android-branko

One of my planned projects in the upcoming 2011 is the Magento – Android application. I already did a fair part on the Android side, plus I started the Magento Mapy extension few weeks ago. Due to my recent one month vacation I was “off the grid” when it comes to my free time work so all my stuff were in a “pause mode”.

Besides my playing around with Android and XML-RPC, here is a simple JSON parsing example that might get you started with more serious things.

In this example, I am connecting to Twitters public timeline JSON url.

package net.inchoo.demo.andy1;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
 
public class HomeActivity extends ListActivity {
 
    /** Called when the activity is first created. */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
		setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));        
    }
 
	public ArrayList<String> fetchTwitterPublicTimeline()
    {
    	ArrayList<String> listItems = new ArrayList<String>();
 
    	try {
			URL twitter = new URL(
					"http://twitter.com/statuses/public_timeline.json");
			URLConnection tc = twitter.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					tc.getInputStream()));
 
			String line;
			while ((line = in.readLine()) != null) {
				JSONArray ja = new JSONArray(line);
 
				for (int i = 0; i < ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);
					listItems.add(jo.getString("text"));
				}
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listItems;
    }
}

Please direct your attention on the listItems.add(jo.getString(“text”)); line. This is the part that I am grabbing a “text” attribute/property of single JSON object. To get a more “visual” picture of all available attributes/properties you might want to take a look at the XML version of twitters public timeline. This way you will get nice colored XML in your browser, where you can see all available attributes.

Cheers.


41 comments

  1. hiii. i want to retrieve data from sqlite database and send it ti MYSQL. please give me some guideline.

  2. package com.example.pratik.jsonparsingdelete;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.widget.ListView;
    import android.widget.Toast;

    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.VolleyLog;
    import com.android.volley.toolbox.JsonArrayRequest;
    import com.android.volley.toolbox.JsonObjectRequest;

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

    import java.util.ArrayList;
    import java.util.List;

    public class MainActivity extends Activity {
    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    private static final String url = “http://www.androidbegin.com/tutorial/jsonparsetutorial.txt”;
    private ProgressDialog pDialog;
    private List movieList = new ArrayList();
    private ListView listView;
    private CustomListAdapter adapter;

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

    listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, movieList);
    listView.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage(“Loading…”);
    pDialog.show();

    /*// changing action bar color
    getActionBar().setBackgroundDrawable(
    new ColorDrawable(Color.parseColor(“#1b1b1b”)));*/

    // Creating volley request obj

    /*JsonArrayRequest movieReq = new JsonArrayRequest(url,
    new Response.Listener() {
    @Override
    public void onResponse(JSONArray response) {
    Log.d(TAG, response.toString());
    hidePDialog();

    // Parsing json
    for (int i = 0; i < response.length(); i++) {
    try {

    JSONObject obj = response.getJSONObject(i);
    Movie movie = new Movie();
    movie.setCountry(obj.getString("country"));
    movie.setThumbnailUrl(obj.getString("flag"));
    movie.setPopulation(obj.getInt("population"));
    movie.setRank(obj.getInt("rank"));

    // Genre is json array

    // adding movie to movies array
    movieList.add(movie);

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

    }

    // notifying list adapter about data changes
    // so that it renders the list view with updated data
    adapter.notifyDataSetChanged();
    }
    }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    VolleyLog.d(TAG, "Error: " + error.getMessage());
    hidePDialog();

    }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
    }

    */

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
    url, null, new Response.Listener() {

    @Override
    public void onResponse(JSONObject response) {
    Log.d(TAG, response.toString());

    try {
    // Parsing json object response
    // response will be a json object

    JSONArray obj1 = response.getJSONArray(“worldpopulation”);
    for (int i = 0; i < obj1.length(); i++) {
    JSONObject obj = obj1.getJSONObject(i);
    Movie movie = new Movie();
    movie.setCountry(obj.getString("country"));
    movie.setThumbnailUrl(obj.getString("flag"));
    movie.setPopulation(obj.getString("population"));
    movie.setRank(obj.getString("rank"));

    movieList.add(movie);
    }

    } catch (JSONException e) {
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
    }

    adapter.notifyDataSetChanged();
    }

    },new Response.ErrorListener()
    {
    @Override
    public void onErrorResponse (VolleyError error){
    VolleyLog.d(TAG, "Error: " + error.getMessage());
    hidePDialog();
    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
    // hide the progress dialog
    }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);

    }

    @Override
    public void onDestroy() {
    super.onDestroy();
    hidePDialog();
    }

    private void hidePDialog() {
    if (pDialog != null) {
    pDialog.dismiss();
    pDialog = null;
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
    }

    }

  3. package com.example.pratik.complexjson;

    import android.app.ListActivity;
    import android.content.ContentValues;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;

    /*import com.example.pratik.complexjson.dbhelper.DBKeys;
    import com.example.pratik.complexjson.dbhelper.DatabaseHelper;*/

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

    import java.util.ArrayList;
    import java.util.HashMap;

    public class DisplayActivity extends ListActivity {

    private static final String TAG_DATE = “date”;
    private static final String TAG_CHANNEL_NAME = “channelName”;
    private static final String TAG_SHOW_TITLE = “showTitle”;
    private static final String TAG_SHOW_TIME = “showTime”;
    private static final String TAG_SHOW_THUMB = “showThumb”;
    private static final String TAG_LANGUAGE = “Language:”;
    private static final String TAG_RELEASE_DATE = “Release Date”;
    private static final String TAG_ACTOR = “Actor”;
    private static final String TAG_GENRE = “Genre:”;
    private static final String TAG_CREATED_BY = “Created By”;
    private static final String TAG_PRODUCER = “Producer”;
    private static final String TAG_SHOW_TYPE = “Show Type:”;
    private static final String TAG_SHOW_DESCRIPTION = “Show Description”;

    private static String url = “http://indian-television-guide.appspot.com/indian_television_guide?channel=%26tv&date=18072016”;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ListView listView = (ListView) findViewById(R.id.list);

    new GetStudents().execute();

    }

    private ArrayList<HashMap> ParseJSON(String json) {
    if (json != null) try {
    // Hashmap for ListView
    ArrayList<HashMap> studentList = new ArrayList<HashMap>();

    JSONObject id = new JSONObject(json);
    String channelName = id.getString(TAG_CHANNEL_NAME);
    String date = id.getString(TAG_DATE);
    HashMap student1 = new HashMap();
    student1.put(TAG_DATE, date);
    student1.put(TAG_CHANNEL_NAME, channelName);
    studentList.add(student1);

    // JSONArray jArray = new JSONArray(json);
    JSONArray jArray = id.getJSONArray(“listOfShows”);
    for (int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);

    String showTitle = "";
    if (json_data.has(TAG_SHOW_TITLE)) {
    showTitle = json_data.getString(TAG_SHOW_TITLE);
    }

    String showTime = "";
    if (json_data.has(TAG_SHOW_TIME)) {
    showTime = json_data.getString(TAG_SHOW_TIME);
    }

    String showThumb = "";
    if (json_data.has(TAG_SHOW_THUMB)) {
    showThumb = json_data.getString(TAG_SHOW_THUMB);
    }

    // JSONObject show_details = new JSONObject(DBKeys.SHOW_DETAIL);

    JSONObject show_details = json_data.getJSONObject("showDetails");

    String Language = "";
    if (show_details.has(TAG_LANGUAGE)) {
    Language = show_details.getString(TAG_LANGUAGE);
    }

    String ReleaseDate = "";
    if (show_details.has(TAG_RELEASE_DATE)) {
    ReleaseDate = show_details.getString(TAG_RELEASE_DATE);
    }

    String Actor = "";
    if (show_details.has(TAG_ACTOR)) {
    Actor = show_details.getString(TAG_ACTOR);
    }

    String Genre = "";
    if (show_details.has(TAG_GENRE)) {
    Genre = show_details.getString(TAG_GENRE);
    }

    String CreatedBY = "";
    if (show_details.has(TAG_CREATED_BY)) {
    CreatedBY = show_details.getString(TAG_CREATED_BY);
    }

    String Producer = "";
    if (show_details.has(TAG_PRODUCER)) {
    Producer = show_details.getString(TAG_PRODUCER);
    }

    String ShowType = "";
    if (show_details.has(TAG_SHOW_TYPE)) {
    ShowType = show_details.getString(TAG_SHOW_TYPE);
    }

    String ShowDescription = "";
    if (show_details.has(TAG_SHOW_DESCRIPTION)) {
    ShowDescription = show_details.getString(TAG_SHOW_DESCRIPTION);
    }

    HashMap student = new HashMap();

    // adding every child node to HashMap key => value

    student.put(TAG_SHOW_TITLE, showTitle);
    student.put(TAG_SHOW_TIME, showTime);
    student.put(TAG_SHOW_THUMB, showThumb);
    student.put(TAG_LANGUAGE, Language);
    student.put(TAG_RELEASE_DATE, ReleaseDate);
    student.put(TAG_ACTOR, Actor);
    student.put(TAG_GENRE, Genre);
    student.put(TAG_CREATED_BY, CreatedBY);
    student.put(TAG_PRODUCER, Producer);
    student.put(TAG_SHOW_TYPE, ShowType);
    student.put(TAG_SHOW_DESCRIPTION, ShowDescription);
    studentList.add(student);

    /* ContentValues cv = new ContentValues();
    cv.put(DBKeys.DATE, date);
    cv.put(DBKeys.CHANNEL_NAME, channelName);
    cv.put(DBKeys.SHOW_TITLE, showTitle);
    cv.put(DBKeys.SHOW_TIME, showTime);
    cv.put(DBKeys.SHOW_THUMB, showThumb);
    cv.put(DBKeys.LANGUAGE, Language);
    cv.put(DBKeys.RELEASE_DATE, ReleaseDate);
    cv.put(DBKeys.ACTOR, Actor);
    cv.put(DBKeys.GENRE, Genre);
    cv.put(DBKeys.CREATED_BY, CreatedBY);
    cv.put(DBKeys.PRODUCER, Producer);
    cv.put(DBKeys.SHOW_TYPE, ShowType);
    cv.put(DBKeys.SHOW_DESCRIPTION, ShowDescription);
    if (DatabaseHelper.getInstance(DisplayActivity.this).checkitemdetail(showTime)) ;
    {
    DatabaseHelper.getInstance(DisplayActivity.this).insertDetail(cv);
    }*/
    }
    //if (date.equals(“date”))

    return studentList;
    } catch (JSONException e) {
    e.printStackTrace();
    return null;
    }
    else {
    Log.e(“ServiceHandler”, “No data received from HTTP request”);
    return null;
    }
    }

    private class GetStudents extends AsyncTask {

    // Hashmap for ListView
    ArrayList<HashMap> studentList = new ArrayList<HashMap>();

    //ProgressDialog proDialog;
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    // Showing progress loading dialog
    /* proDialog = new ProgressDialog(DisplayActivity.this);
    proDialog.setMessage(“Please wait…”);
    proDialog.show();*/
    }

    @Override
    protected Void doInBackground(Void… arg0) {
    // Creating service handler class instance
    ServiceCall serviceCall = new ServiceCall();
    try {

    // Making a request to url and getting response
    String jsonStr = serviceCall.doHTTPGetRequest(url);
    Log.v(“jsonStr:”, jsonStr);
    studentList = ParseJSON(jsonStr);

    } catch (Exception e) {
    e.printStackTrace();
    Log.v(“Exception do in back:”, e.getMessage() + “”);
    }
    return null;
    }

    @Override
    protected void onPostExecute(Void requestresult) {
    super.onPostExecute(requestresult);

    ListAdapter adapter;
    adapter = new SimpleAdapter(DisplayActivity.this, studentList,
    R.layout.list_view, new String[]{TAG_DATE, TAG_CHANNEL_NAME,
    TAG_SHOW_TITLE, TAG_SHOW_TIME, TAG_SHOW_THUMB, TAG_LANGUAGE, TAG_RELEASE_DATE, TAG_ACTOR, TAG_GENRE, TAG_CREATED_BY, TAG_PRODUCER, TAG_SHOW_TYPE, TAG_SHOW_DESCRIPTION},
    new int[]{R.id.date, R.id.channelname, R.id.showtitle, R.id.showtime, R.id.showthumb, R.id.language, R.id.releasedate, R.id.actor, R.id.genre, R.id.createdby, R.id.producer, R.id.showtype, R.id.showdescription});

    setListAdapter(adapter);
    }
    }
    }

  4. package com.example.pratik.complexjson.dbhelper;

    /**
    * Created by Pratik on 04-Jan-16.
    */
    public class DBKeys {

    public static final String DETAIL=”detail”;
    public static final String DATE = “date”;
    public static final String CHANNEL_NAME = “channelName”;
    public static final String SHOW_TITLE = “showTitle”;
    public static final String SHOW_TIME = “showTime”;
    public static final String SHOW_THUMB = “showThumb”;
    public static final String LANGUAGE = “Language”;
    public static final String RELEASE_DATE = “Release_Date”;
    public static final String ACTOR = “Actor”;
    public static final String GENRE = “Genre”;
    public static final String CREATED_BY = “Created_By”;
    public static final String PRODUCER = “Producer”;
    public static final String SHOW_TYPE = “Show_Type”;
    public static final String SHOW_DESCRIPTION = “Show_Description”;
    public static final String ROW_ID=”row_id”;

    }

  5. package com.example.pratik.complexjson.dbhelper;

    import android.annotation.SuppressLint;
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.os.Environment;
    import android.util.Log;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    /**
    * Created by Pratik on 04-Jan-16.
    */
    public class DatabaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH;

    private static String DB_NAME = “ComplexJson.db”;

    protected SQLiteDatabase myDataBase;

    private final Context myContext;

    private static final String log_tag = “log_tag”;
    private static DatabaseHelper instance;

    public static DatabaseHelper getInstance(Context context) {
    if (instance == null) {
    instance = new DatabaseHelper(context);
    instance.openDataBase();
    }
    return instance;
    }

    /**
    * Constructor Takes and keeps a reference of the passed context in order to
    * access to the application assets and resources.
    *
    * @param context
    */
    @SuppressLint(“SdCardPath”)
    public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, 1);
    this.myContext = context;
    // DB_PATH = “/data/data/” + context.getPackageName() + “/databases/”;

    DB_PATH =
    Environment.getExternalStorageDirectory().getAbsolutePath()+ “/”;

    try {
    createDataBase();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    /**
    * Creates a empty database on the system and rewrites it with your own
    * database.
    */
    public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if (dbExist) {
    // do nothing – database already exist
    } else {
    // By calling this method and empty database will be created into
    // the default system path
    // of your application so we are gonna be able to overwrite that
    // database with our database.
    this.getReadableDatabase();

    try {

    copyDataBase();
    Log.d(log_tag, “Data base created…….”);

    } catch (IOException e) {
    e.printStackTrace();
    throw new Error(“Error copying database”);

    }
    }

    }

    /**
    * Check if the database already exist to avoid re-copying the file each
    * time you open the application.
    *
    * @return true if it exists, false if it doesn’t
    */
    private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
    String myPath = DB_PATH + DB_NAME;
    checkDB = SQLiteDatabase.openDatabase(myPath, null,
    SQLiteDatabase.OPEN_READONLY);
    } catch (Exception e) {
    }

    if (checkDB != null) {
    checkDB.close();
    }
    return checkDB != null ? true : false;
    }

    /**
    * Copies your database from your local assets-folder to the just created
    * empty database in the system folder, from where it can be accessed and
    * handled. This is done by transfering bytestream.
    */
    private void copyDataBase() throws IOException {
    InputStream myInput = myContext.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);
    if (myInput != null && myOutput != null) {
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
    myOutput.write(buffer, 0, length);
    }
    } else {
    Log.d(“error”, “Not Found”);
    }
    myOutput.flush();
    myOutput.close();
    myInput.close();
    }

    public void openDataBase() throws SQLException {
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null,
    SQLiteDatabase.OPEN_READWRITE);
    Log.d(log_tag, “Database is opened….”);
    }

    @Override
    public synchronized void close() {
    /*
    * if (myDataBase != null) myDataBase.close(); super.close();
    */
    Log.d(log_tag, “Database is closed….”);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long insertDetail(ContentValues values){
    return myDataBase.insert(DBKeys.DETAIL,null,values);
    }

    public Boolean checkitemdetail(String showTime) {

    Cursor cursor = myDataBase.query(DBKeys.DETAIL, null, DBKeys.SHOW_TIME + “='” + showTime + “‘”, null, null, null, null);
    if (cursor == null) {
    if (cursor.moveToFirst())
    {
    return false;
    }
    cursor.close();
    }
    return true;
    }

    }

  6. package com.example.pratik.complexjson;

    import android.app.ListActivity;
    import android.content.ContentValues;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;

    import com.example.pratik.complexjson.dbhelper.DBKeys;
    import com.example.pratik.complexjson.dbhelper.DatabaseHelper;

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

    import java.util.ArrayList;
    import java.util.HashMap;

    public class DisplayActivity extends ListActivity {

    private static final String TAG_DATE = “date”;
    private static final String TAG_CHANNEL_NAME = “channelName”;
    private static final String TAG_SHOW_TITLE = “showTitle”;
    private static final String TAG_SHOW_TIME = “showTime”;
    private static final String TAG_SHOW_THUMB = “showThumb”;
    private static final String TAG_LANGUAGE = “Language:”;
    private static final String TAG_RELEASE_DATE = “Release Date”;
    private static final String TAG_ACTOR = “Actor”;
    private static final String TAG_GENRE = “Genre:”;
    private static final String TAG_CREATED_BY = “Created By”;
    private static final String TAG_PRODUCER = “Producer”;
    private static final String TAG_SHOW_TYPE = “Show Type:”;
    private static final String TAG_SHOW_DESCRIPTION = “Show Description”;

    private static String url = “http://indian-television-guide.appspot.com/indian_television_guide?channel=%26tv&date=28062016”;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ListView listView = (ListView) findViewById(R.id.list);

    new GetStudents().execute();

    }

    private ArrayList<HashMap> ParseJSON(String json) {
    if (json != null) try {
    // Hashmap for ListView
    ArrayList<HashMap> studentList = new ArrayList<HashMap>();

    JSONObject id = new JSONObject(json);
    String channelName = id.getString(TAG_CHANNEL_NAME);
    String date = id.getString(TAG_DATE);
    HashMap student1 = new HashMap();
    student1.put(TAG_DATE, date);
    student1.put(TAG_CHANNEL_NAME, channelName);
    studentList.add(student1);

    // JSONArray jArray = new JSONArray(json);
    JSONArray jArray = id.getJSONArray(“listOfShows”);
    for (int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);

    String showTitle = "";
    if (json_data.has(TAG_SHOW_TITLE)) {
    showTitle = json_data.getString(TAG_SHOW_TITLE);
    }

    String showTime = "";
    if (json_data.has(TAG_SHOW_TIME)) {
    showTime = json_data.getString(TAG_SHOW_TIME);
    }

    String showThumb = "";
    if (json_data.has(TAG_SHOW_THUMB)) {
    showThumb = json_data.getString(TAG_SHOW_THUMB);
    }

    // JSONObject show_details = new JSONObject(DBKeys.SHOW_DETAIL);

    JSONObject show_details = json_data.getJSONObject("showDetails");

    String Language = "";
    if (show_details.has(TAG_LANGUAGE)) {
    Language = show_details.getString(TAG_LANGUAGE);
    }

    String ReleaseDate = "";
    if (show_details.has(TAG_RELEASE_DATE)) {
    ReleaseDate = show_details.getString(TAG_RELEASE_DATE);
    }

    String Actor = "";
    if (show_details.has(TAG_ACTOR)) {
    Actor = show_details.getString(TAG_ACTOR);
    }

    String Genre = "";
    if (show_details.has(TAG_GENRE)) {
    Genre = show_details.getString(TAG_GENRE);
    }

    String CreatedBY = "";
    if (show_details.has(TAG_CREATED_BY)) {
    CreatedBY = show_details.getString(TAG_CREATED_BY);
    }

    String Producer = "";
    if (show_details.has(TAG_PRODUCER)) {
    Producer = show_details.getString(TAG_PRODUCER);
    }

    String ShowType = "";
    if (show_details.has(TAG_SHOW_TYPE)) {
    ShowType = show_details.getString(TAG_SHOW_TYPE);
    }

    String ShowDescription = "";
    if (show_details.has(TAG_SHOW_DESCRIPTION)) {
    ShowDescription = show_details.getString(TAG_SHOW_DESCRIPTION);
    }

    HashMap student = new HashMap();

    // adding every child node to HashMap key => value

    student.put(TAG_SHOW_TITLE, showTitle);
    student.put(TAG_SHOW_TIME, showTime);
    student.put(TAG_SHOW_THUMB, showThumb);
    student.put(TAG_LANGUAGE, Language);
    student.put(TAG_RELEASE_DATE, ReleaseDate);
    student.put(TAG_ACTOR, Actor);
    student.put(TAG_GENRE, Genre);
    student.put(TAG_CREATED_BY, CreatedBY);
    student.put(TAG_PRODUCER, Producer);
    student.put(TAG_SHOW_TYPE, ShowType);
    student.put(TAG_SHOW_DESCRIPTION, ShowDescription);
    studentList.add(student);

    ContentValues cv = new ContentValues();
    cv.put(DBKeys.DATE, date);
    cv.put(DBKeys.CHANNEL_NAME, channelName);
    cv.put(DBKeys.SHOW_TITLE, showTitle);
    cv.put(DBKeys.SHOW_TIME, showTime);
    cv.put(DBKeys.SHOW_THUMB, showThumb);
    cv.put(DBKeys.LANGUAGE, Language);
    cv.put(DBKeys.RELEASE_DATE, ReleaseDate);
    cv.put(DBKeys.ACTOR, Actor);
    cv.put(DBKeys.GENRE, Genre);
    cv.put(DBKeys.CREATED_BY, CreatedBY);
    cv.put(DBKeys.PRODUCER, Producer);
    cv.put(DBKeys.SHOW_TYPE, ShowType);
    cv.put(DBKeys.SHOW_DESCRIPTION, ShowDescription);
    if (DatabaseHelper.getInstance(DisplayActivity.this).checkitemdetail(showTime)) ;
    {
    DatabaseHelper.getInstance(DisplayActivity.this).insertDetail(cv);
    }
    }
    //if (date.equals(“date”))

    return studentList;
    } catch (JSONException e) {
    e.printStackTrace();
    return null;
    }
    else {
    Log.e(“ServiceHandler”, “No data received from HTTP request”);
    return null;
    }
    }

    private class GetStudents extends AsyncTask {

    // Hashmap for ListView
    ArrayList<HashMap> studentList = new ArrayList<HashMap>();

    //ProgressDialog proDialog;
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    // Showing progress loading dialog
    /* proDialog = new ProgressDialog(DisplayActivity.this);
    proDialog.setMessage(“Please wait…”);
    proDialog.show();*/
    }

    @Override
    protected Void doInBackground(Void… arg0) {
    // Creating service handler class instance
    ServiceCall serviceCall = new ServiceCall();
    try {

    // Making a request to url and getting response
    String jsonStr = serviceCall.doHTTPGetRequest(url);
    Log.v(“jsonStr:”, jsonStr);
    studentList = ParseJSON(jsonStr);

    } catch (Exception e) {
    e.printStackTrace();
    Log.v(“Exception do in back:”, e.getMessage() + “”);
    }
    return null;
    }

    @Override
    protected void onPostExecute(Void requestresult) {
    super.onPostExecute(requestresult);

    ListAdapter adapter;
    adapter = new SimpleAdapter(DisplayActivity.this, studentList,
    R.layout.list_view, new String[]{TAG_DATE, TAG_CHANNEL_NAME,
    TAG_SHOW_TITLE, TAG_SHOW_TIME, TAG_SHOW_THUMB, TAG_LANGUAGE, TAG_RELEASE_DATE, TAG_ACTOR, TAG_GENRE, TAG_CREATED_BY, TAG_PRODUCER, TAG_SHOW_TYPE, TAG_SHOW_DESCRIPTION},
    new int[]{R.id.date, R.id.channelname, R.id.showtitle, R.id.showtime, R.id.showthumb, R.id.language, R.id.releasedate, R.id.actor, R.id.genre, R.id.createdby, R.id.producer, R.id.showtype, R.id.showdescription});

    setListAdapter(adapter);
    }
    }
    }

  7. package com.example.pratik.complexjson;

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Map;

    import javax.net.ssl.HttpsURLConnection;

    /**
    * Created by Pratik on 04-Jan-16.
    */
    public class ServiceCall {
    public final static int GETRequest = 1;
    public final static int POSTRequest = 2;

    //Constructor with no parameter
    public ServiceCall() {
    }
    public String makeWebServiceCall(String url, int requestmethod) {
    return this.makeWebServiceCall(url, requestmethod, null);
    }

    public String makeWebServiceCall(String urladdress, int requestmethod,
    HashMap params) {
    URL url;
    String response = “”;
    try {
    url = new URL(urladdress);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(15001);
    conn.setConnectTimeout(15001);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    /* if (requestmethod == POSTRequest) {
    conn.setRequestMethod(“POST”);
    }
    else {*/
    if (requestmethod == GETRequest) {
    conn.setRequestMethod(“GET”);
    }

    /* if (params != null) {
    OutputStream ostream = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(ostream, “UTF-8”));
    StringBuilder requestresult = new StringBuilder();
    boolean first = true;
    for (Map.Entry entry : params.entrySet()) {
    if (first)
    first = false;
    else
    requestresult.append(“&”);
    requestresult.append(URLEncoder.encode(entry.getKey(), “UTF-8”));
    requestresult.append(“=”);
    requestresult.append(URLEncoder.encode(entry.getValue(), “UTF-8”));
    }
    writer.write(requestresult.toString());

    writer.flush();
    writer.close();
    ostream.close();
    }*/
    int reqresponseCode = conn.getResponseCode();

    if (reqresponseCode == HttpsURLConnection.HTTP_OK) {
    String line;
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line = br.readLine()) != null) {
    response += line;
    }
    } else {
    response = “”;
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return response;
    }

    public static String doHTTPGetRequest(String urlStr) throws Exception {

    String outputString = “”;

    URL url = new URL(urlStr);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
    InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
    BufferedReader in=new BufferedReader(isr);
    String responseString=null;
    while ((responseString = in.readLine()) != null)
    {
    outputString = outputString + responseString;
    }
    }
    finally{
    urlConnection.disconnect();
    }

    return outputString;
    }
    }

  8. This Sample Project is showing a force close error.. whether any changes in xml file

  9. I want to check some data from android to MySQL can u provide me the whole script for this. . !

  10. [2012-06-22 19:51:26 – jason_example5] Failed to install jason_example5.apk on device ’emulator-5554′: EOF
    [2012-06-22 19:51:26 – jason_example5] java.io.IOException: EOF
    [2012-06-22 19:51:26 – jason_example5] Launch canceled!
    ven i m launching this code its showing the above error ?i m new to android so please help me out in that.
    i have created xml which contains image view ,text view,buttons .so i wantes to reterive all images so anyone can tell me how to do that…..

  11. Thanks for the article,
    Can you please write any article that something like this:
    get name from android page send it into server in POST method and again read data from server that send by JSON fromat from server and display that data in android page.

    Thanks.

  12. 1HI, nice one but you have to remove
    setContentView(R.layout.main); if you use setListAdapter.
    and add parameter after new ArrayAdapter. no need of setcontentview()
    . This is the source code that I have changed :

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
    }

  13. Hi, I am newbie for android, please help me guys for following problem.
    ex. “profile_image_url”:”http:\/\/a0.twimg.com\/profile_images\/1882839203\/ThugMissez4_normal.jpg”

    i’m having same kind of json string and i want load and display this kind of image in my imageview
    ex.
    Bitmap bmp = BitmapFactory.decodeFile(jo.getString(“Picurl”));
    imageurl.add(bmp);
    where imageur is Arraylist
    but i get null values. please help me out for this problem. πŸ™‚

  14. basically the core of the logic is totally worng,

    String line;
    while ((line = in.readLine()) != null) {
    JSONArray ja = new JSONArray(line);

    for (int i = 0; i < ja.length(); i++) {
    JSONObject jo = (JSONObject) ja.get(i);
    listItems.add(jo.getString("text"));
    }
    }

    in this logic jsonarray cant parse a single line it needs
    the hole string of json objects..

  15. i like your tutorial.we do the json parsing using android json classes.but for parsing purpose android provides Gson API.so can u tell me wats the benifit of gsonAPI.

  16. thank you so much for the support and effort. This is what exactly i am looking for .great app πŸ™‚

  17. sorry text is not appearing just give user permission in side manifest for “android.permission.INTERNET”.

  18. @Corey,@asif:

    Just give the permission inside Android mAnifest file as

    “”

    it surely works

    and thanks Branko Ajzele for the code it is very useful one…

    requesting more like this

  19. I can’t seem to get this code to work, It just gives me a blank screen with no data. Can someone tell me what should be in my main.xml file?

  20. we have to mention url which contains result and this line should be according to the attributes in result
    listItems.add(jo.getString(“text”));
    “text” should be your attribute.

  21. I can’t seem to get this code to work, It just gives me a blank screen with no data. Can someone tell me what should be in my main.xml file?

  22. Hei Branko nice artikel! but you need to remove

    setContentView(R.layout.main); if you use setListAdapter.

    and add parameter after new ArrayAdapter. Because I am getting error from your original source code. This is the source code that I have changed :

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));  
        }

    CMIIW, Keep Posting! πŸ˜€

  23. hi , i have some warnings in this code , so its not properly work. .it show warning at @SuppressWarnings({ “rawtypes”, “unchecked” }). . kindly help me . .thanx

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.