Android ArrayAdapter和JSONArray

时间:2013-12-09 09:14:31

标签: android listview arrays jsonobject

我是Android开发的新手。

考虑到JSON Carrier与XML相比的轻盈,我纯粹喜欢使用JSON Objects和Arrays作为我的简单应用程序。

我遇到了使用ArrayAdapter来填充ListView的挑战。

这就是我克服并需要你的建议的方法。

Extend the Adaptor class.

然后将JSONArray传递给构造函数 这里构造函数使用 dummy String数组调用super来设置JSONArray的长度。
将构造函数参数存储在类中以供进一步使用。

public myAdaptor(Context context, int resource, JSONArray array)
{
    super(context, resource, new String[array.length()]);
    // Store in the local varialbles to the adapter class.
    this.context = context;
    this.resource = resource;
    this.profiles = objects;
}

getView()将从JSONArray执行获取 JSONObjects的工作来构建视图。

public View getView(int position, View convertView, ViewGroup parent)
{
    View view;
    if (convertView == null)
    {
        LayoutInflater inflater = (LayoutInflater) 
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(resource, parent, false);
    }
    else
    {
        view = convertView;
    }

    // Here 
    JSONObject item = (JSONObject) profiles.getJSONObject(position);

    // READY WITH JSONObject from the JSONArray
    // YOUR CODE TO BUILD VIEW OR ACCESS THE 
}

现在有任何改进/建议/有问题吗?

4 个答案:

答案 0 :(得分:6)

我建议你使用谷歌GSON而不是JSON。它是一个从JSON请求中为您提供创建对象的库,您不再需要解析JSON。只需创建一个包含JSON请求中所有字段的对象,并命名相同,并随意使用它 - 例如:

Your JSON request
{
    [
        {
            "id": "2663",
            "title":"qwe"

        },
        {
            "id": "1234",
            "title":"asd"
        },
        {
            "id": "5678",
            "title":"zxc"
        }

    ]
}

您的类 - JSON-Array

 public class MyArrayAdapterItem{
     int id;
     String title;
 }

您下载数据的代码中的某个地方。我不知道你是怎么做的所以我会发布我的代码,例如:

mGparser = new JsonParser();
Gson mGson = new Gson();

Url url = "http://your_api.com"
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "close");
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

JsonArray request = (JsonArray) mGparser.parse(in.readLine());
in.close();
ArrayList<MyArrayAdapterItem> items = mGson.fromJson(request, new TypeToken<ArrayList<MyArrayAdapterItem>>() {}.getType());

这就是全部,现在只需将“items”替换为适配器构造函数中的JSON数组

答案 1 :(得分:2)

您可以将null传递给super而不是创建字符串数组并实现getCount方法:

public myAdaptor(Context context, int resource, JSONArray array)
{
    super(context, resource, null);
    // Store in the local varialbles to the adapter class.
    this.context = context;
    this.resource = resource;
    this.profiles = array;
}

public int getCount(){
   return profiles.length();
}

答案 2 :(得分:0)

创建一个textview并使用item.getString(&#34; key&#34;)进行赋值,并将该字符串添加到本地字符串数组并返回该视图

答案 3 :(得分:0)

这是listview适配器类。

public class Adapter extends BaseAdapter {
    Context context = null;
    ArrayList<OffersAvailable> offers = null;


    public Adapter(Context context, ArrayList<OffersAvailable> offer) {
        this.context = context;
        this.offers = offer;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return offers.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return offers.get(position).getTitle();
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        View v;
        final TextView tvpoints;
        final TextView tv,tv_quantity;
        if (convertView == null) {
            LayoutInflater li = ((Activity) context).getLayoutInflater();
            v = li.inflate(R.layout.design_userlist, null);

        } else {
            v = convertView;
        }
        tvpoints = (TextView) v.findViewById(R.id.tvpointlist);
        tv_quantity= (TextView) v.findViewById(R.id.tv_quantity);
        tv = (TextView) v.findViewById(R.id.tvdatalist);
        ((Activity) context).runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                tv.setText(offers.get(position).getTitle().toUpperCase());
                tv_quantity.setText(offers.get(position).getQuatity().toUpperCase());
                tvpoints.setText(offers.get(position).getPoint() + "");
            }
        });

        return v;
    }

}

对象类

public class OffersAvailable {
    String title, point, quatity, description,nid;

    public String getNid() {
        return nid;
    }

    public void setNid(String nid) {
        this.nid = nid;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPoint() {
        return point;
    }

    public void setPoint(String point) {
        this.point = point;
    }

    public String getQuatity() {
        return quatity;
    }

    public void setQuatity(String quatity) {
        this.quatity = quatity;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

使用主类中的json并将其存储在OffersAvailable类型的Arraylist中。

并将其传递给listviews适配器。 如果你从互联网上获得响应,请使用asynchttpclient方法。并解析json。