First modify the Category model adding the id
public class Category {
private int id;
...
public String getId() {
return id;
}
public void setId(int ind) {
this.id = id;
}
...
}
then set it when loading categories
Category cat = new Category();
cat.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)))
cat.setName(cursor.getString(cursor.getColumnIndex(catName)));
cat.setImage(category_image_urls[i]);
list.add(cat);
pass the id to fragment B as Rajesh suggested
MealsListFragment fragment = new MealsListFragment();
Bundle bundle = new Bundle();
bundle.putInt("categoryId", Categories.get(pos).getId());
fragment.setArguments(bundle);
get the value in fragment B and modify the getAllMealsValues to filter by the category id
if (bundle != null) {
//Load your data by id or any reference from your Model data
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recycler_view);
final Activity activity = getActivity();
rv.setLayoutManager(new GridLayoutManager(activity, 2));
rv.setAdapter(new MealsAdapter(this.getActivity(), dbHelper.GetAllMealsValues(bundle.getInt("categoryId")) ));
//ADDING SOME SPACE AROUND FRAGMENTS
int mMargin = 15;
rv.addItemDecoration(new SpacesItemDecoration(mMargin));
}
Change DBHelper to add the category id in meals table, just make sure to assign a category to the meal when adding meals
private static final String categoryId = "category_id";
...
private static final String CREATE_MEALS = "CREATE TABLE "
+ TABLE_Meals + "(" + KEY_ID + " INTEGER PRIMARY KEY," + mealsName
+ " TEXT unique," + desc + " TEXT," + size + " TEXT,"
+ price + " TEXT," + categoryId + " INTEGER)";
...
public Cursor getMeals(int id)
{
Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TABLE_Meals + " WHERE " + cagegoryId + "=" + String.valueOf(id), null);
return cursor;
}
...
public ArrayList<Meals> GetAllMealsValues(int id)
{
ArrayList<Meals> list = new ArrayList<Meals>();
Cursor cursor = getMeals(id);
int i = 0; // Iterator for 'do-while'. While it gets Categories names, it shall catch all the url's from array as well.
if (cursor.moveToFirst())
{
do
{
Meals meal = new Meals();
meal.setName(cursor.getString(cursor.getColumnIndex(mealsName))); //mealsName
list.add(meal);
i++;
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
return list;
}