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

How to show datas with array 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;
    }
}

主要Activity请求

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

此代码的结果针对每个数据: "com.xxx.xxx.Models.Categories@52b3adec" 等...

您也需要覆盖您的Categories#toString()。您当前在 list 中看到的内容来自默认 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.

中显示 类别 名称