How to convert JSONArray to ListView?

旧时模样 提交于 2020-01-10 19:59:05

问题


I have a code which does following -

  1. Connect to a web service via HttpClient to PHP file
  2. Returns a result from an SQL query
  3. Returns format is a jArray (a JSONArray)

for(int i=0; i < jArray.length() ; i++) {
    json_data = jArray.getJSONObject(i);
    int id=json_data.getInt("id");
    String name=json_data.getString("name");
    Log.d(name,"Output");
}

When I look at the LogCat, I see all the "names" of the query, Each record is printed. I just need to plug these results into a ListView. How can I accomplish this ?

PS - I do not have a separate class for an ArrayAdapter. Could this be the reason ?


回答1:


If you just want to display a list of textViews you don't need to override anything, you can just add all of the items into an arrayList and use an arrayAdapter.

Put a list view in your xml that is named android:list and then create your arrayAdapter with the textView you want to use.

After that all you have to do is call setListAdapter(mArrayAdapter) and it should populate your list.

ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
    json_data = jArray.getJSONObject(i);
    int id=json_data.getInt("id");
    String name=json_data.getString("name");
    items.add(name);
    Log.d(name,"Output");
}

ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,  
           android.R.layout.simple_expandable_list_item_1, items));
setListAdapter(mArrayAdapter)

hope this helps!




回答2:


you could take a look at this webpage that has an example to do just what you are looking for: http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/

Basically, inside your for loop where you are printing the names, you should be loading an array list containing the values you would like to insert to the list later. Notice that the example uses the following:

ArrayList< HashMap < String, String > > mylist = new ArrayList < HashMap < String, String > > ();

And you have an integer and a string to add to the structure so you could simply turn that ID into a String and problem solved. Afterwards you can use a list adapter without the need of creating a separate class:

ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, new String[] { "name", "id" }, new int[] { R.id.item_title, R.id.item_subtitle });

Where "name" and "id" will be the keys in your map for the name and id values returned by json and item_title, item_subtitle the views to "adapt" the text on.

Hope I was clear enough, take a look at the example anyway its pretty straightforward.




回答3:


I do not like to remap data while i already have them in a JSON array so this is my code ... it is simple enough for me ....hope it helps

package ...;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

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

public class DataListFragment extends ListFragment{
    JSONArray data;

    public DataListFragment(){

    }

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.i("mycode", "DataListFragment onActivityCreated");
        data=((MainActivity)this.getActivity()).data;
        Log.i("mycode", "data length "+data.toString());
        setEmptyText("No Data Here");
        final JSONArrayAdapter adapter = new JSONArrayAdapter(this.getActivity(),data);
        setListAdapter(adapter);

        // Start out with a progress indicator.
        //setListShown(false);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Insert desired behavior here.
        Log.i("mycode", "Item clicked: " + id);
    }

    private class JSONArrayAdapter extends BaseAdapter {
        JSONArray data;
        Context context;

        public JSONArrayAdapter(Context context,JSONArray data) {
            super();
            this.context=context;
            this.data=data;
        }

        @Override
        public int getCount() {
            return data.length();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            try {
                return data.getJSONObject(arg0);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public boolean hasStableIds(){
            return true;
        }

        @Override
        public boolean isEmpty(){
            return data==null || data.length()==0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(R.layout.single_item, parent, false);
            TextView textView1 = (TextView) rowView.findViewById(R.id.firstLine);
            TextView textView2 = (TextView) rowView.findViewById(R.id.secondLine);
            //ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
            try {
                JSONObject jo = (JSONObject) data.get(position);
                textView1.setText(jo.getString("category_title"));
                textView2.setText(jo.getString("description"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return rowView;
        }

    }

}


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:padding="6dip" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="6dip"
        android:contentDescription="icon"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/secondLine"
        android:layout_width="fill_parent"
        android:layout_height="26dip"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@id/icon"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:textSize="12sp" />

    <TextView
        android:id="@+id/firstLine"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/secondLine"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="true"
        android:layout_toRightOf="@id/icon"
        android:gravity="center_vertical"
        android:textSize="16sp" />

</RelativeLayout> 



回答4:


Put the data into an Array and use ArrayAdapter to bind data to a list items.

See the article on:

http://www.josecgomez.com/2010/05/03/android-putting-custom-objects-in-listview/



来源:https://stackoverflow.com/questions/9440138/how-to-convert-jsonarray-to-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!