2016-12-15 49 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