6

I am trying to display the elements in listview from the JSON::

JsonURL- https://dl.dropboxusercontent.com/s/rhk01nqlyj5gixl/jsonparsing.txt?token_hash=AAHpfauVxJaC9Rkx_5abNtJnPFG04os7TZky1AhOuC5jEw


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/listViewID"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:layout_gravity="center">
    </ListView>

</LinearLayout>

JSONParser.java

package com.example.testjson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONArray jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativelay"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="5dip"
        android:maxLines="1"
        android:text="Name"
        android:textColor="@android:color/black"
        android:textSize="14dp"
        android:textStyle="bold" >
    </TextView>

    <TextView
        android:id="@+id/tvcity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tvname"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="3dip"
        android:maxLines="1"
        android:text="City"
        android:textColor="@android:color/black"
        android:textSize="14dp" >
    </TextView>

    <TextView
        android:id="@+id/tvbdate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tvcity"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="3dip"
        android:maxLines="1"
        android:text="Birthdate"
        android:textColor="@android:color/black"
        android:textSize="14dp" >
    </TextView>

    <TextView
        android:id="@+id/tvgender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="15dip"
        android:maxLines="1"
        android:text="Gender"
        android:textColor="@android:color/black"
        android:textSize="14dp"
        android:textStyle="bold" >
    </TextView>

    <TextView
        android:id="@+id/tvage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/tvgender"
        android:layout_marginRight="15dip"
        android:layout_marginTop="3dip"
        android:maxLines="1"
        android:text="Age"
        android:textColor="@android:color/black"
        android:textSize="14dp" >
    </TextView>

</RelativeLayout>

MainActivity.java

package com.example.testjson;

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

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

import android.os.Bundle;
import android.app.Activity;
import android.text.StaticLayout;
import android.view.Menu;

public class MainActivity extends Activity {

    private static String url="https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";

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

        //Create a JSON parser Instance ----- Used JSON parser from Android
        JSONParser jParser=new JSONParser();

        //Getting JSON string from URL ------ Used JSON Array from Android
        JSONArray json=jParser.getJSONFromUrl(url);

        try {
            for(int i=0;i<json.length();i++)
            {
                JSONObject c=json.getJSONObject(i);// Used JSON Object from Android

                //Storing each Json in a string variable
                int AGE=c.getInt("age");
                String NAME=c.getString("name");
                String CITY=c.getString("city");
                String GENDER=c.getString("Gender");
                String BIRTHDATE=c.getString("birthdate");



            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


}
  • I am trying to populate the data from the JSON to listView, some ambiguity on filling MainActivity.java
  • what collection to use for this functionality ?
  • Any ideas, This looks a simple task but for a beginner like me its giving a lot of fight to learn

Thanks ,

  • 1
    Good Question there ! .... Even i am looking for something like this ..... and good explanation about the problem !... Will wait for answers ! – Devrath Aug 01 '13 at 08:00

4 Answers4

5

Continuing your class:

public class MainActivity extends Activity {

    private static String url="https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";

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

        //Create a JSON parser Instance ----- Used JSON parser from Android
        JSONParser jParser=new JSONParser();

        //Getting JSON string from URL ------ Used JSON Array from Android
        JSONArray json=jParser.getJSONFromUrl(url);

        List<WhateverObject> yourData = new ArrayList<WhateverObject>();

        try {
            for(int i=0;i<json.length();i++)
            {
                JSONObject c=json.getJSONObject(i);// Used JSON Object from Android

                //Storing each Json in a string variable
                int AGE=c.getInt("age");
                String NAME=c.getString("name");
                String CITY=c.getString("city");
                String GENDER=c.getString("Gender");
                String BIRTHDATE=c.getString("birthdate");


                yourData.add(new WhateverObject(NAME, CITY, GENDER, BIRTHDATE));

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ListView yourListView = (ListView) findViewById(R.id.itemListView);

        ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);

        yourListView.setAdapter(customAdapter);

    }


}

adater:

public class ListAdapter extends ArrayAdapter<Item> {

    public ListAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
        // TODO Auto-generated constructor stub
    }

    private List<Item> items;

    public ListAdapter(Context context, int resource, List<Item> items) {

        super(context, resource, items);

        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        TextView tt = null;
        TextView tt1 = null;
        TextView tt2 = null;
        TextView tt3 = null;
        TextView tt4 = null;

        if (v == null) {

            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.itemlistrow, null);

            tt = (TextView) v.findViewById(R.id.age);
            tt1 = (TextView) v.findViewById(R.id.name);
            tt2 = (TextView) v.findViewById(R.id.city);
            tt3 = (TextView) v.findViewById(R.id.gender);
            tt4 = (TextView) v.findViewById(R.id.birthdate);
        }

        Item p = items.get(position);

        if (p != null) {

            if (tt != null) {
                tt.setText(""+p.getAge());
            }
            if (tt1 != null) {

                tt1.setText(""+p.getName());
            }
            if (tt2 != null) {

                tt2.setText(""+p.getCity());
            }

            if (tt3 != null) {

                tt3.setText(""+p.getGender());
            }

            if (tt4 != null) {

                tt4.setText(""+p.getBirthdate());
            }
        }



        return v;

    }
}

object holding data:

public class WhateverObject{
    private int age;
    private String name;
    private String city;
    private String gender;
    private String birthdate;        

    public WhateverObject(int age, String name, String city, String gender, String birthdate){
        this.age = age;
        this.name = name;
        this.city = city;
        this.gender = gender;
        this.birthdate = birthdate;
    }

    public int getAge(){
        return this.age;
    }

    public String getName(){
        return this.name;
    }

    public String getCity(){
        return this.city;
    }

    public String getGender(){
        return this.gender;
    }

    public String getBirthdate(){
        return this.birthdate;
    }
}

xml for listview item (save under itemlistrow name):

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_height="wrap_content" android:orientation="vertical"
             android:layout_width="fill_parent">

    <TableRow android:layout_width="fill_parent"
              android:id="@+id/TableRow01"
              android:layout_height="wrap_content">

        <TextView
                android:id="@+id/age"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="age" android:textStyle="bold"
                android:gravity="left"
                android:layout_weight="1"
                android:typeface="monospace"
                android:height="40sp"/>
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView
                android:id="@+id/name"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="name"
                android:layout_weight="1"
                android:height="20sp"/>
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView
                android:id="@+id/city"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="city"
                android:layout_weight="1"
                android:height="20sp"/>
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView
                android:id="@+id/gender"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="city"
                android:layout_weight="1"
                android:height="20sp"/>
    </TableRow>

    <TableRow android:layout_height="wrap_content"
              android:layout_width="fill_parent">

        <TextView
                android:id="@+id/birthdate"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="city"
                android:layout_weight="1"
                android:height="20sp"/>
    </TableRow>

</TableLayout>

Reused elements from https://stackoverflow.com/a/8166802/1276374


Simpler example:

public class MainActivity extends Activity {

    private static String url="https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";

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

        //Create a JSON parser Instance ----- Used JSON parser from Android
        JSONParser jParser=new JSONParser();

        //Getting JSON string from URL ------ Used JSON Array from Android
        JSONArray json=jParser.getJSONFromUrl(url);

        List<Map<String, String>> personList = new ArrayList<Map<String,String>>();

        try {
            for(int i=0;i<json.length();i++)
            {
                JSONObject c=json.getJSONObject(i);// Used JSON Object from Android

                //Storing each Json in a string variable
                int AGE=c.getInt("age");
                String NAME=c.getString("name");
                String CITY=c.getString("city");
                String GENDER=c.getString("Gender");
                String BIRTHDATE=c.getString("birthdate");


                personList.add(createPerson(AGE, NAME, CITY, GENDER, BIRTHDATE));

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ListView yourListView = (ListView) findViewById(R.id.itemListView);

        simpleAdpt = new SimpleAdapter(this, personList, android.R.layout.simple_list_item_1, new String[] {"person"}, new int[] {android.R.id.text1});

        yourListView.setAdapter(simpleAdpt);

    }

    private HashMap<String, String> createPerson(int age, String name, String city, String gender, String birthdate) {
        HashMap<String, String> person = new HashMap<String, String>();
        person.put("person", name+" | "+age + " | "+city + " | "+gender + " | "+birthdate);
        return person;
    }



}

Thanks to http://www.javacodegeeks.com/2013/06/android-listview-tutorial-and-basic-example.html

Community
  • 1
  • 1
Boris Mocialov
  • 3,439
  • 2
  • 28
  • 55
  • Mocialov Boris ..... I tried your solution with your first solution ... I am getting the error as below in my **LogCat** .................................. 08-01 14:38:15.625: E/Buffer Error(710): Error converting result java.lang.NullPointerException 08-01 14:38:15.634: E/JSON Parser(710): Error parsing data org.json.JSONException: End of input at character 0 of 08-01 14:38:15.644: D/AndroidRuntime(710): Shutting down VM .........................also some more errors ! –  Aug 01 '13 at 09:11
  • 1
    @Sky seems like an exception from your JSON parser – Boris Mocialov Aug 01 '13 at 09:24
  • ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData); ..... i solved the exception from JSON parser but........ having problem in this line ..... error ::constructor adapter is undefined –  Aug 01 '13 at 09:27
  • 1
    @Sky changed some things in my answer `Item` object substituted with `WhateverObject`, do the same – Boris Mocialov Aug 01 '13 at 10:14
  • @ Mocialov Boris .... Thanks on the i/p's.... I made the changes on **whateverobject** .... But the error ::`The constructor ListAdapter(MainActivity, int, List) is undefined` .... Still exists .... Its in the main class on the line `ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);` .....Looks like... some changes have to be made in Adapter class constructor .... ! any Ideas ? –  Aug 01 '13 at 11:02
  • 1
    @Sky change `ArrayList` to `List` in `ListAdapter` - edited answer – Boris Mocialov Aug 01 '13 at 11:10
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/34617/discussion-between-sky-and-mocialov-boris) –  Aug 01 '13 at 11:18
  • @Mocialov Boris, `jObj = new JSONArray(json);` throws `JSONException` in JSONParser.java when trying to load data from http://stichoza.com/projects/usa2georgia/api/ . Can you help me? Here's the screenshot of debugging process http://i.imgur.com/SbUKkJp.png – Stichoza Nov 12 '13 at 23:57
  • @Stichoza because you are trying to cast JSON object into JSON Array object – Boris Mocialov Nov 13 '13 at 08:10
  • @Mocialov Boris, `jObj` is defined like this: `static JSONArray jObj = null;`, I'm using `JSONParser.java` as it's posted in this question – Stichoza Nov 13 '13 at 11:20
1

Create a class, say Student, to contain a record, create an array of Student from the JSON, and then use that with ArrayAdapter to populate your ListView.

Ben Williams
  • 6,027
  • 2
  • 30
  • 54
1

Use of ArrayList will be better for you.See the following snippet,

Declare the following on the top,

public static ArrayList<String> FriendName = new ArrayList<String>();

And the following inside the try block after fetching the Name

FriendName .add(Name);

And you can easily fetch the values from the arraylist through the index value like follows,

String data=FriendName.get(0);
Spring Breaker
  • 8,233
  • 3
  • 36
  • 60
1

I would use GSON library for its simplicity. In this case you will have the following:

A POJO student class for data mapping

public class Student
    private int id;
    private String name;
    private String city;
    private String  Gender;
    private int age;
    private String birthdate;

    //getters and setters
}

To parse the data just do

Student[] students;
Type token = new TypeToken<Student[]>() {}.getType();
Gson gson = new Gson();   
students = gson.fromJson(jsonString, token);

And from here you just add the data to the adapter, and that's it.

Axxiss
  • 4,759
  • 4
  • 26
  • 45