Я пытаюсь показать избранные элементы держателя просмотра, которые пользователи щелкали как избранные из меню. Я не получаю ошибок в моем коде. Предполагается, что название и изображение еды показывают, но только FoodId, а не изображение, которое показывает. Это мой любимый код активности:
public class FavouritesActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FavoritesAdapter adapter;
List<Favorites> context = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourites);
recyclerView = findViewById(R.id.recycler_fav);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadFavorites();
}
private void loadFavorites() {
adapter = new FavoritesAdapter(this, new Database(this).getAllFavorites(Common.currentUser.getPhone()));
recyclerView.setAdapter(adapter);
}
}
Это адаптер избранного и держатель представления.
class FavoritesViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public TextView food_name;
public ImageView food_image, fav_image;
private ItemClickListener itemClickListener;
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
public FavoritesViewHolder(View itemView) {
super(itemView);
food_name = itemView.findViewById(R.id.food_name_fi);
food_image = itemView.findViewById(R.id.food_image_fi);
fav_image = itemView.findViewById(R.id.fav);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition(), false);
}
}
public class FavoritesAdapter extends RecyclerView.Adapter<FavoritesViewHolder> {
private Context context;
private List<Favorites> favoritesList = new ArrayList<>();
public FavoritesAdapter(Context context, List<Favorites> favoritesList) {
this.context = context;
this.favoritesList = favoritesList;
}
@NonNull
@Override
public FavoritesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context)
.inflate(R.layout.favorites_item, parent, false);
return new FavoritesViewHolder(itemView);
}
@Override
public void onBindViewHolder
(@NonNull FavoritesViewHolder viewHolder, final int position) {
viewHolder.food_name.setText(favoritesList.get(position).getFoodName());
Picasso.get().load(favoritesList.get(position).getFoodImage())
.into(viewHolder.food_image);
final Favorites local = favoritesList.get(position);
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
Intent foodDetail = new Intent(context, FoodDetails.class);
foodDetail.putExtra("FoodId", favoritesList.get(position).getFoodId());
context.startActivity(foodDetail);
}
});
}
@Override
public int getItemCount() {
return favoritesList.size();
}
public void removeItem(int position)
{
favoritesList.remove(position);
notifyItemRemoved(position);
}
public void restoreItem(Favorites item, int position)
{
favoritesList.add(position, item);
notifyItemInserted(position);
}
public Favorites getItem (int positon) {
return favoritesList.get(positon);
}
}
Это xml для activity_favoris
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FoodList">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_fav"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
</RelativeLayout>
Я не уверен, где проблема в основном, когда она нажата, добавьте в избранное на странице сведений о еде, она добавляет ее в базу данных sql lite и затем должна отображаться на странице действий в избранном.
SQL Информация о базе данных:
public void addToFavorites (Favorites food) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO Favorites(" +
"FoodId, FoodName, FoodPrice, FoodMenuId, FoodImage, FoodDiscount, FoodDescription, UserPhone) " +
"VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');",
food.getFoodId(),
food.getFoodName(),
food.getFoodPrice(),
food.getFoodMenuId(),
food.getFoodImage(),
food.getFoodDiscount(),
food.getFoodDescription(),
food.getUserPhone());
db.execSQL(query);
}
public void removeFromFavorites (String foodId, String userPhone) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM Favorites WHERE FoodId='%s' and UserPhone='%s';",foodId, userPhone);
db.execSQL(query);
}
public boolean isFavorite (String foodId, String userPhone) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT * From Favorites WHERE FoodId='%s' and UserPhone='%s';",foodId,userPhone);
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount() <= 0)
{
cursor.close();
return false;
}
cursor.close();
return true;
}
public List<Favorites> getAllFavorites(String userPhone){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"UserPhone", "FoodId", "FoodName", "FoodPrice", "FoodMenuId", "FoodImage", "FoodDiscount", "FoodDescription"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor c = qb.query(db, sqlSelect, "UserPhone=?", new String[] {userPhone}, null,null, null);
final List<Favorites> result = new ArrayList<>();
if (c.moveToFirst()){
do{
result.add(new Favorites(
c.getString(c.getColumnIndex("UserPhone")),
c.getString(c.getColumnIndex("FoodId")),
c.getString(c.getColumnIndex("FoodName")),
c.getString(c.getColumnIndex("FoodPrice")),
c.getString(c.getColumnIndex("FoodMenuId")),
c.getString(c.getColumnIndex("FoodImage")),
c.getString(c.getColumnIndex("FoodDiscount")),
c.getString(c.getColumnIndex("FoodDescription"))
));
}while (c.moveToNext());
}
return result;
}
}
На странице списка продуктов при добавлении в избранное:
//Add Favorites
if(localDB.isFavorite(adapter.getRef(position).getKey(), Common.currentUser.getPhone()))
viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_black_24dp);
//Click to change status of Favorites
viewHolder.fav_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Favorites favorites = new Favorites();
favorites.setFoodId(adapter.getRef(position).getKey());
favorites.setFoodName(model.getName());
favorites.setFoodDescription(model.getDescription());
favorites.setFoodDiscount(model.getDiscount());
favorites.setFoodImage(model.getImage());
favorites.setFoodMenuId(model.getMenuId());
favorites.setUserPhone(Common.currentUser.getPhone());
favorites.setFoodPrice(model.getPrice());
if(!localDB.isFavorite(adapter.getRef(position).getKey(), Common.currentUser.getPhone()))
{
localDB.addToFavorites(favorites);
viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_black_24dp);
Toast.makeText(FoodList.this, ""+model.getName() +" was added to Favorites", Toast.LENGTH_SHORT).show();
}
else {
localDB.removeFromFavorites(adapter.getRef(position).getKey(), Common.currentUser.getPhone());
viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_border_black_24dp);
Toast.makeText(FoodList.this, ""+model.getName() +" was removed from Favorites", Toast.LENGTH_SHORT).show();
}
}
});