Shwetabh Singh
Shwetabh Singh

Reputation: 197

How to show JSON objects in listview?

Main class Using volley library to fetch JSON data from URL.

   public class MyActivity extends Activity {   

ListView listView;
List<Details> rowItems;

RequestQueue requestQueue;

 @Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.details2);
    url = getIntent().getStringExtra("key");
    if(savedInstanceState!=null){
        Log.d("STATE",savedInstanceState.toString());
    }


    requestQueue = Volley.newRequestQueue(this);

    JsonObjectRequest jor = new  JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>()  {
                @Override
                public void onResponse(JSONObject response) {

                    try {


                        JSONArray ja = response.getJSONArray("results");

                        ArrayList<Details> myModelList = new     ArrayList<Details>();
                        Details mymodel = null;
                        for (int i = 0; i < ja.length(); i++) {

                            JSONObject jsonObject = ja.getJSONObject(i);
                            mymodel = new Details();
                            mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
                            mymodel.url = jsonObject.getString("resLink");
                            mymodel.resType = jsonObject.getString("resType");
                            mymodel.name = jsonObject.getString("resName");

                            myModelList.add(mymodel);
                              setData();
                        }


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

            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley","Error");

                }
            }
    );
    requestQueue.add(jor);
}

private void setData() {

    listView = (ListView) findViewById(R.id.list);
    CustomListViewAdapter adapter = new CustomListViewAdapter(this,
            R.layout.list_item, rowItems);
    listView.setAdapter(adapter);
    //listView.setOnItemClickListener(this);
}



@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

My CustomListViewAdapter claas is below

 public class CustomListViewAdapter extends ArrayAdapter<Details> {

Context context;

public CustomListViewAdapter(Context context, int resourceId,
                             List<Details> items) {
    super(context, resourceId, items);
    this.context = context;
}

/*private view holder class*/
private class ViewHolder {

    TextView txtTitle;
    TextView txtDesc;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    Details rowItem = getItem(position);

    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_item, null);
        holder = new ViewHolder();
        holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
        holder.txtTitle = (TextView) convertView.findViewById(R.id.title);

        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.txtDesc.setText(rowItem.getResType());
    holder.txtTitle.setText(rowItem.getName());

    return convertView;
}

My Details class public class Details extends Results {

String name;
String resType;
String url;
int id;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getResType() {
    return resType;
}
public void setResType(String resType) {
    this.resType = resType;
}
public String getUrl() {
    return url;
}
public void setUrl(String url) {
    this.url = url;
}

* want to showthe data I received in list view*

my XML

    <ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

list_item.xml

       <LinearLayout       xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">


<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/icon"
    android:paddingBottom="10dp"
    android:textColor="#CC0033"
    android:textSize="16dp" />

<TextView
    android:id="@+id/desc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/title"
    android:layout_toRightOf="@+id/icon"
    android:paddingLeft="10dp"
    android:textColor="#3399FF"
    android:textSize="14dp" />

Upvotes: 0

Views: 233

Answers (4)

turbandroid
turbandroid

Reputation: 2306

In adapter you are using List rowItems;

so code of onResponse method should be like as follows

 JSONArray ja = response.getJSONArray("results");
 rowItems = new     ArrayList<Details>();
 Details mymodel = null;
 for (int i = 0; i < ja.length(); i++) {
    JSONObject jsonObject = ja.getJSONObject(i);
    mymodel = new Details();
    mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
    mymodel.url = jsonObject.getString("resLink");
    mymodel.resType = jsonObject.getString("resType");
    mymodel.name = jsonObject.getString("resName");
    rowItems.add(mymodel);
    }
    setData();

To make the json parsing easy you can use Gson library as explained here http://www.mysamplecode.com/2013/07/android-json-stream-data-parsing.html

Upvotes: 1

Android Geek
Android Geek

Reputation: 9225

Update your setData methode as you are not getting list to set data.

 private void setData(List<Details> list) {
          listView = (ListView) findViewById(R.id.list);
          CustomListViewAdapter adapter = new CustomListViewAdapter(this,
            R.layout.list_item, list);
          listView.setAdapter(adapter);
    }

Also change setData(); to setData(myModelList);

Upvotes: 1

Ragesh Ramesh
Ragesh Ramesh

Reputation: 3520

You are doing everything right but not passing your myModelList which contains the data and are passing the empty rowItems list. Once you fetch all data and create your myModelList, call

             setData(myModelList);

And change your setData method as follows

private void setData(List<Details> mList) {
      listView = (ListView) findViewById(R.id.list);
      CustomListViewAdapter adapter = new CustomListViewAdapter(this,
        R.layout.list_item, mList);
      listView.setAdapter(adapter);
}

Upvotes: 1

malli
malli

Reputation: 640

use following line in your adapter class getView()

Details rowItem = (Details) getItem(position);

instead of

Details rowItem = getItem(position);

Upvotes: 1

Related Questions