2015-08-15 73 views
0

我想在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); 
} 

此代码的结果是对于每一个数据: “ [email protected]“ etc ...

回答

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显示类别名。