带有标题的RecyclerView获取重复项目

时间:2018-06-16 03:10:43

标签: android recycler-adapter activeandroid

我有一个recyclerview项目列表,在适配器中,我有一个按钮,用于将项目作为收藏夹添加到active android数据库,如下面的代码:

viewholder.favoriteWP_IV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Favorites favorites = new Favorites(); // Model class for db crud

            favorites.setFavoritesId(UUID.randomUUID().toString());
            favorites.setLargeImgURL(pixaImages.getLargeImgURL());
            favorites.setPreviewImgURL(pixaImages.getPreviewImgURL());
            favorites.setImageId(favorites.getImageId());

            favorites.save();
            Log.d(TAG, "Fav_id:\t" + favorites.getId());
            Log.d(TAG, "Favorites Id:\t" + favorites.getFavoritesId());


            //TODO: 6/13/2018 Fix Duplicate Favorite WP
            Toast.makeText(context, "Added to Favorites", Toast.LENGTH_SHORT).show();

        }
    });

在我的FavoritesActivity中,我检索了所有项目并将其显示在如下代码的Recyclerview中:

 public List<Favorites> getAllFavorites() {
    return new Select()
            .all()
            .from(Favorites.class)
            .orderBy("favorites_id ASC")
            .execute();
}

private void getFavorites() {
    favsRV.setHasFixedSize(true);
    favsRV.setLayoutManager(new LinearLayoutManager(this));

    AdapterHeaderItem headerItem = new AdapterHeaderItem();
    headerItem.setHeaderIcon(R.drawable.drawer_header_trimmed);
    headerItem.setHeaderTitle("you can toggle through your favorite wallpapers using the wallpaper widget on your home screen");
    objectList.add(headerItem);

    //itemsList = getAllFavorites();
    Favorites favorites = new Favorites();
    for (int i = 0; i < getAllFavorites().size(); i++) {
        favorites.setFavoritesId(getAllFavorites().get(i).getFavoritesId());
        favorites.setLargeImgURL(getAllFavorites().get(i).getLargeImgURL());
        favorites.setPreviewImgURL(getAllFavorites().get(i).getPreviewImgURL());
        favorites.setImageId(getAllFavorites().get(i).getImageId());
        Log.d(TAG, "All Favs Ids:\t" + getAllFavorites().get(i).getFavoritesId());
        objectList.add(favorites);
    }
    Log.d(TAG, "Favorites List Size:\t" + objectList.size());

    adapter = new FavoritesAdapter(this, objectList);
    favsRV.setAdapter(adapter);

}

这里的问题是,点击要保存的项目不是and时实际保存的项目,它会检索相同项目的重复副本。

以前,我的适配器没有标头并且工作正常但是当我将标头添加到适配器时,我不得不从list has multiple items更改为允许我将标题项添加到视图中。

在我的活动中,我通过这行List<Favorites> to List<Object>使用旧的适配器代码检索了所有记录,但是使用新的适配器代码,我必须使用一个对象来存储列表中的项目。

我试过这个itemsList = getAllFavorites();但应用程序崩溃了,只有其他选项才能执行此操作并保存在对象列表中:

Favorites favs = (Favorites) itemsList = getAllFavorites();

这是我的模特课:

    Favorites favorites = new Favorites();
    for (int i = 0; i < getAllFavorites().size(); i++) {
        favorites.setFavoritesId(getAllFavorites().get(i).getFavoritesId());
        favorites.setLargeImgURL(getAllFavorites().get(i).getLargeImgURL());
        favorites.setPreviewImgURL(getAllFavorites().get(i).getPreviewImgURL());
        favorites.setImageId(getAllFavorites().get(i).getImageId());
        Log.d(TAG, "All Favs Ids:\t" + getAllFavorites().get(i).getFavoritesId());
        objectList.add(favorites);
    }

但是这个代码块为我提供了三个项目的列表,一个项目重复了三次。我认为这是因为代码的变化。适配器运行良好,但在活动中,我得到错误的结果。

这是我的适配器代码:

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;

@Table(name = "favorites")
public class Favorites extends Model{

  @Column(name = "favorites_id")
  public String favoritesId;

  @Column(name = "image_id")
  public int imageId;

  @Column(name = "large_img_url")
  public String largeImgURL;

  @Column(name = "preview_img")
  public String previewImgURL;

  public Favorites() { }

  public Favorites(String favoritesId, int imageId, String largeImgURL, String previewImgURL) {
      this.favoritesId = favoritesId;
      this.imageId = imageId;
      this.largeImgURL = largeImgURL;
      this.previewImgURL = previewImgURL;
  }

  public String getFavoritesId() {
      return favoritesId;
  }

  public void setFavoritesId(String favoritesId) {
      this.favoritesId = favoritesId;
  }

  public int getImageId() {
      return imageId;
  }

  public void setImageId(int imageId) {
      this.imageId = imageId;
  }

  public String getLargeImgURL() {
      return largeImgURL;
  }

  public void setLargeImgURL(String largeImgURL) {
      this.largeImgURL = largeImgURL;
  }

  public String getPreviewImgURL() {
      return previewImgURL;
  }

  public void setPreviewImgURL(String previewImgURL) {
      this.previewImgURL = previewImgURL;
  }
}

我认为问题在于循环和插入适配器列表:

public class FavoritesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private static final String TAG = FavoritesAdapter.class.getSimpleName();

private final Context context;
private List<Object> itemsList;

public static final int HEADER_VIEW = 0;
public static final int ITEMS_VIEW = 1;

public FavoritesAdapter(Context context, List<Object> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    if (viewType == HEADER_VIEW) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_adapter_header_layout, parent, false);
        return new AdapterHeaderItemViewHolder(view);
    } else if (viewType == ITEMS_VIEW) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.favorites_item_layout, parent, false);
        return new FavoritesViewHolder(view);
    }
    throw new RuntimeException("No matching viewTypes");
}

@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof AdapterHeaderItemViewHolder) {
        AdapterHeaderItem header = (AdapterHeaderItem) itemsList.get(position);
        ((AdapterHeaderItemViewHolder) holder).headerTitleTV.setText(header.getHeaderTitle());

        Picasso.with(context)
                .load(header.getHeaderIcon())
                .placeholder(R.drawable.drawer_header_trimmed)
                .into(((AdapterHeaderItemViewHolder) holder).headerIconIV);

    } else if (holder instanceof FavoritesViewHolder) {
        final Favorites favorites = (Favorites) itemsList.get(position);

        Picasso.with(context)
                .load(favorites.getLargeImgURL())
                .placeholder(R.mipmap.ic_launcher)
                .into(((FavoritesViewHolder) holder).favoriteWPImg);

        ((FavoritesViewHolder) holder).removeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "Adapter VH Posn:\t" + holder.getAdapterPosition());

                String fav_id = favorites.getFavoritesId();
                Log.d(TAG, "Favorites+id:\t" + fav_id);
                removeAtPosition(holder.getAdapterPosition(), fav_id);
            }
        });

        ((FavoritesViewHolder) holder).previewTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent previewIntent = new Intent(context, PreviewWallPaperActivity.class);
                previewIntent.putExtra("fav_id", favorites.getFavoritesId());
                previewIntent.putExtra("large_url", favorites.getLargeImgURL());
                previewIntent.putExtra("preview_url", favorites.getPreviewImgURL());
                context.startActivity(previewIntent);
            }
        });

    }
}

private void removeAtPosition(int position, String id) {
    Log.d(TAG, "id in method:\t" + id);
    new Delete()
            .from(Favorites.class)
            .where("favorites_id=?", id)
            .execute();
    Log.d(TAG, "Favorite Removed from db");
    itemsList.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, itemsList.size());

    Toast.makeText(context, "Removed From Favorites", Toast.LENGTH_SHORT).show();

}

@Override
public int getItemCount() {
    if (itemsList == null) {
        return 0;
    }
    return itemsList.size();
}

@Override
public int getItemViewType(int position) {
    if (isPositionHeader(position))
        return HEADER_VIEW;
    return ITEMS_VIEW;
}

private boolean isPositionHeader(int position) {
    return position == 0;
}

}

任何人都可以帮助我理解为什么同一项目会多次出现?感谢。

0 个答案:

没有答案