2016-12-15 46 views
-1

我在開發的Android應用程序中有一個GridView,我從API獲取這個GridView的數據並將API數據存儲到本地數據庫中,然後將其顯示在GridView。我的問題是,當我第一次顯示數據時,它的確定,但是當我重新啓動應用程序的GridView時,會發生重複數據。stop當從api顯示數據到gridview時重複數據android

JsonArrayRequest movieReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { 
     @Override 
     public void onResponse(JSONArray response) { 
      Log.d(TAG, response.toString()); 
      hidePDialog(); 

      // Parsing json 
      for (int i = 0; i < response.length(); i++) { 
       try { 

        JSONObject obj = response.getJSONObject(i); 
        Movie movie = new Movie(); 
        movie.setTitle(obj.getString("title")); 
        movie.setThumbnailUrl(obj.getString("image")); 


        // adding movie to movies array 
        movieList.add(movie); 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

      } 

      // notifying list adapter about data changes 
      // so that it renders the list view with updated data 
      adapter.notifyDataSetChanged(); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      VolleyLog.d(TAG, "Error: " + error.getMessage()); 
      hidePDialog(); 

     } 
    }); 

如何在我的GridView中阻止此問題?

回答

0

您需要使用一組數據(如:HashSet的)結構刪除重複項。

步驟:

  1. 裏面的電影類,覆蓋equals和hashCode方法和定義自己的定義。 哈希碼:您可以返回標題和縮略圖網址的哈希碼之和 等於:您可以根據比較標題和縮略圖網址進行返回。

  2. 在onResponse方法中,創建一個Hashset,然後將電影對象添加到散列集。一旦添加了所有項目,將哈希集值複製到列表中並使用它。您將獲得唯一的網格項輸出。

    public class Movie{ 
    
    public String thumbnailUrl; 
    public String title; 
    
    @Override 
    public int hashCode() { 
        return 31 * title.hashCode() + thumbnailUrl.hashCode(); 
    } 
    
    @Override 
    public boolean equals(Object o) { 
        if(o instanceof Movie){ 
         Movie other = (Movie) o; 
         return other.title.equalsIgnoreCase(title) && other.thumbnailUrl.equalsIgnoreCase(thumbnailUrl); 
        } 
        return false; 
    } 
    } 
    

在onResponse方法:

@Override 
    public void onResponse(JSONArray response) { 
     ..... 

     HashSet<Movie> set = new HashSet<Movie>(); 
     set.add(movie); 

     ..... 

     movieList.addAll(set); 
    } 
0

使用HashSet的instaed的ArrayList,設置刪除duplicacy