如何使用数组适配器显示数据

时间:2015-08-15 14:04:25

标签: android android-listview android-adapter

我想在ListView中显示来自API的数据。我不知道为什么,但它似乎在列表中显示我的模型路径。 这是代码:

型号:

public class Categories {
    private String name;

    public Categories(String name) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

适配器:

public class CategoriesAdapter extends ArrayAdapter<Categories> {

    private final List<Categories> list;
    private final Activity context;

    public CategoriesAdapter(Activity context, List<Categories> list) {
        super(context, android.R.layout.simple_list_item_activated_1, list);
        this.context = context;
        this.list = list;
    }
}

主要活动请求

private void makeJsonArrayRequest(String api_url) {
        showpDialog();

        JsonArrayRequest req = new JsonArrayRequest(api_url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            for (int i = 0; i < response.length(); i++) {
                                JSONObject cat_obj = (JSONObject) response.get(i);
                                list.add(new Categories(cat_obj.getString("title")));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                        hidepDialog();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                hidepDialog();
            }
        });
        // Volley Request Queue
        AppController.getInstance().addToRequestQueue(req);
}

此代码的结果适用于每个数据: &#34; com.xxx.xxx.Models.Categories@52b3adec" 等...

1 个答案:

答案 0 :(得分:1)

您还需要覆盖您的Categories#toString()。您目前在列表中看到的内容来自默认的Object#toString()实施。

public class Categories {

    private String name;

    public Categories(String name) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

以上内容现在会在ListView中显示类别名称。