2015-08-15 72 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顯示類別名。