use of com.example.ezmeal.roomDatabase.Recipe in project EZMeal by Jake-Sokol2.
the class RecipeActivity method onCreate.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_specific_recipe);
// rateRecipeInterface = this;
Bundle extras = getIntent().getExtras();
recipeId = extras.getString("id");
ImageView imageRecipe = findViewById(R.id.imageRecipeImage);
TextView txtRecipeTitle = findViewById(R.id.txtRecipeTitle);
// rateRecipe = findViewById(R.id.rateRecipe);
// vmRateRecipeBubble = new ViewModelProvider(this).get(RateRecipeBubbleViewModel.class);
// vmRateRecipe = new ViewModelProvider(this).get(RateRecipeViewModel.class);
/*
Observer<Float> ratingObserver = new Observer<Float>()
{
@Override
public void onChanged(Float f)
{
if (f != null)
{
rateRecipe.setRating(f);
}
}
};
vmRateRecipe.getStarRating().observe(this, ratingObserver);*/
// Room database instance
// ratingsDb = Room.databaseBuilder(getApplicationContext(), RatingsDatabase.class, "user")
// .allowMainThreadQueries().fallbackToDestructiveMigration().build();
sqlDb = Room.databaseBuilder(getApplicationContext(), EZMealDatabase.class, "user").allowMainThreadQueries().fallbackToDestructiveMigration().build();
// retrieve current rating for this recipe (if one exists for this user) from Room to display in bottom rating bar
Rating userRating = sqlDb.testDao().getSpecificRatingObject(recipeId);
/*rateRecipe.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener()
{
@Override
public void onRatingChanged(RatingBar ratingBar, float value, boolean fromUser)
{
if (fromUser)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
RateRecipeBottomDialogFragment rateRecipeFrag = new RateRecipeBottomDialogFragment(value, rateRecipeInterface);
ft.setReorderingAllowed(true);
ft.add(rateRecipeFrag, "TAG");
ft.show(rateRecipeFrag);
ft.commit();
}
}
});*/
db = FirebaseFirestore.getInstance();
// todo: RecipesRating
CollectionReference dbRecipes = db.collection("Recipes");
tv1 = findViewById(R.id.textRating1);
tv2 = findViewById(R.id.textRating2);
tv3 = findViewById(R.id.textRating3);
card1 = findViewById(R.id.cardRating1);
card2 = findViewById(R.id.cardRating2);
card3 = findViewById(R.id.cardRating3);
float avgRating = 0f;
// working update code
// DatabaseReference testRef = FirebaseDatabase.getInstance().getReference().child("Recipes").child("0");
// testRef.child("numClicked").setValue(ServerValue.increment(1));
// working update code
/* DatabaseReference testRef = FirebaseDatabase.getInstance().getReference().child("Recipes").child("0");
testRef.addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot snapshot)
{
//for (DataSnapshot ds: snapshot.getChildren())
//{
Long s = (Long) snapshot.child("week").getValue();
Log.i("test", String.valueOf(s));
if (s < 1000)
{
snapshot.child("week").getRef().setValue(1000);
snapshot.child("numClicked").getRef().setValue(1);
}
else
{
snapshot.child("numClicked").getRef().setValue(ServerValue.increment(1));
}
//}
}
@Override
public void onCancelled(@NonNull DatabaseError error)
{
}
});*/
// order by numClicks where week equalTo 1000
/*DatabaseReference queryRef = FirebaseDatabase.getInstance().getReference().child("Recipes");
queryRef.orderByChild("week").equalTo(1000).orderByChild("numClicked").addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot snapshot)
{
Log.i("t", "t");
}
@Override
public void onCancelled(@NonNull DatabaseError error)
{
}
});*/
/*DatabaseReference queryRef = FirebaseDatabase.getInstance().getReference().child("Recipes");
queryRef.child("week").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>()
{
@Override
public void onComplete(@NonNull Task<DataSnapshot> task)
{
Log.i("test", "week new : " + String.valueOf(task.getResult().getValue()));
if ((int) task.getResult().getValue() != 1000)
{
}
}
});*/
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
String currentWeek = String.valueOf(cal.getTimeInMillis());
Long currentTimeLong = cal.getTimeInMillis();
String removeLastWeek = String.valueOf(cal.getTimeInMillis() - 1);
// WORKING 5/8/22
DatabaseReference testRef = FirebaseDatabase.getInstance().getReference().child("Recipes").child(currentWeek).child(recipeId);
testRef.child("numClicked").setValue(ServerValue.increment(1));
// querying code that wipes database if current week isnt active
// WORKING 5/8/22
DatabaseReference queryRef = FirebaseDatabase.getInstance().getReference().child("Recipes");
queryRef.keepSynced(true);
queryRef.orderByChild("week").startAt(0).endAt(currentTimeLong - 1).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// If a week exists in the database and it isn't this week, delete all data
if (snapshot.getValue() != null) {
for (DataSnapshot ds : snapshot.getChildren()) {
queryRef.child(ds.getKey()).removeValue();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
/*queryRef.child(currentWeek).limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot snapshot)
{
if (snapshot.getValue() == null)
{
Log.i("a", "snapshot was null");
queryRef.removeValue();
}
else
{
Log.i("a", "snapshot was NOT null");
}
}
@Override
public void onCancelled(@NonNull DatabaseError error)
{
}
});*/
/*DatabaseReference queryRef = FirebaseDatabase.getInstance().getReference().child("Recipes");
queryRef.startAt(0).endAt(1).addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot snapshot)
{
}
@Override
public void onCancelled(@NonNull DatabaseError error)
{
}
});*/
// Log.i("week value", String.valueOf(testRef.child("week").get().getResult().getValue()));
/*realtimeDb.orderByChild("recipeId").equalTo("0").addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot snapshot)
{
for (DataSnapshot ds: snapshot.getChildren())
{
String week = (String) ds.child("week").getValue();
Log.i("a", "week + " + week);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error)
{
throw error.toException();
}
});*/
// todo: RecipesRating
db.collection("Recipes").document(recipeId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
Glide.with(getApplicationContext()).load(Uri.parse(task.getResult().getString("imageUrl"))).into(imageRecipe);
txtRecipeTitle.setText(task.getResult().getString("title"));
categories = (ArrayList<String>) task.getResult().get("categories");
directions = (ArrayList<String>) task.getResult().get("directions");
ingredients = (ArrayList<String>) task.getResult().get("ingredients");
calories = (String) task.getResult().get("calories");
protein = (String) task.getResult().get("protein");
carbohydrates = (String) task.getResult().get("carbohydrates");
fat = (String) task.getResult().get("fat");
cholesterol = (String) task.getResult().get("cholesterol");
sodium = (String) task.getResult().get("sodium");
// (ArrayList<String>) task.getResult().get("nutrition");
nutrition = new ArrayList<>();
nutrition.add("Calories - " + calories);
nutrition.add("Protein - " + protein);
nutrition.add("Carbohydrates - " + carbohydrates);
nutrition.add("Fat - " + fat);
nutrition.add("Cholesterol - " + cholesterol);
nutrition.add("Sodium - " + sodium);
imageUrl = task.getResult().getString("imageUrl");
title = task.getResult().getString("title");
countOfRatings = task.getResult().getDouble("countRating");
totalRatingFirebase = task.getResult().getDouble("rating");
highlyRated = task.getResult().getBoolean("highlyRated");
Double avgRating;
if (countOfRatings != null) {
avgRating = totalRatingFirebase / countOfRatings;
} else {
countOfRatings = 0.0;
avgRating = 0.0;
}
RatingBar rbRecipeIndicator = findViewById(R.id.rbRecipeIndicator);
if (Double.isNaN(avgRating)) {
rbRecipeIndicator.setVisibility(View.INVISIBLE);
avgRating = 0.0;
} else {
float avgRatingFloat = avgRating.floatValue();
rbRecipeIndicator.setRating(avgRatingFloat);
}
Integer totalRating = countOfRatings.intValue();
Map<String, Long> firebaseTextRatingsMap = (Map<String, Long>) task.getResult().get("textRatings");
// (Arrays.asList(findViewById(R.id.cardRating1), findViewById(R.id.cardRating2), findViewById(R.id.cardRating3)));
List<CardView> textRatingCardViews = new ArrayList<CardView>();
// (Arrays.asList(findViewById(R.id.textRating1), findViewById(R.id.textRating2), findViewById(R.id.textRating3)));
List<TextView> textRatingTextViews = new ArrayList<TextView>();
List<CardView> textRatingCardViewsInvisible = new ArrayList<CardView>();
List<TextView> textRatingTextViewsInvisible = new ArrayList<TextView>();
List<String> finalRatingList = new ArrayList<String>();
if (firebaseTextRatingsMap != null) {
// sort the list in reverse order to get top 3 ratings (we only display the top three bubbles)
Map<String, Long> reverseSortedByNumberOfRatings = new TreeMap<>(Collections.reverseOrder());
reverseSortedByNumberOfRatings.putAll(firebaseTextRatingsMap);
Iterator<Map.Entry<String, Long>> iterator = reverseSortedByNumberOfRatings.entrySet().iterator();
finalRatingList = sortTextRatingsByLength(iterator);
if (finalRatingList.size() >= 3) {
textRatingCardViews = new ArrayList<CardView>(Arrays.asList(findViewById(R.id.cardRating1), findViewById(R.id.cardRating2), findViewById(R.id.cardRating3)));
textRatingTextViews = new ArrayList<TextView>(Arrays.asList(findViewById(R.id.textRating1), findViewById(R.id.textRating2), findViewById(R.id.textRating3)));
updateLessThanThreeTextRatings(textRatingCardViews, textRatingTextViews, finalRatingList);
textRatingCardViewsInvisible = new ArrayList<CardView>(Arrays.asList(findViewById(R.id.cardRating4), findViewById(R.id.cardRating5)));
textRatingTextViewsInvisible = new ArrayList<TextView>(Arrays.asList(findViewById(R.id.textRating4), findViewById(R.id.textRating5)));
} else {
textRatingCardViews = new ArrayList<CardView>(Arrays.asList(findViewById(R.id.cardRating4), findViewById(R.id.cardRating5)));
textRatingTextViews = new ArrayList<TextView>(Arrays.asList(findViewById(R.id.textRating4), findViewById(R.id.textRating5)));
textRatingCardViewsInvisible = new ArrayList<CardView>(Arrays.asList(findViewById(R.id.cardRating1), findViewById(R.id.cardRating2), findViewById(R.id.cardRating3)));
textRatingTextViewsInvisible = new ArrayList<TextView>(Arrays.asList(findViewById(R.id.textRating1), findViewById(R.id.textRating2), findViewById(R.id.textRating3)));
updateLessThanThreeTextRatings(textRatingCardViews, textRatingTextViews, finalRatingList);
}
for (int i = 0; i < textRatingCardViewsInvisible.size(); i++) {
textRatingCardViewsInvisible.get(i).setVisibility(View.INVISIBLE);
textRatingTextViewsInvisible.get(i).setVisibility(View.INVISIBLE);
}
/*for (int i = 0; i < 3; i++)
{
if (i < finalRatingList.size())
{
textRatingTextViews.get(i).setText(finalRatingList.get(i));
}
else
{
textRatingTextViews.get(i).setVisibility(View.INVISIBLE);
textRatingCardViews.get(i).setVisibility(View.INVISIBLE);
}
}*/
} else {
// all cards and textviews are marked to be made invisible
textRatingCardViewsInvisible = new ArrayList<CardView>(Arrays.asList(findViewById(R.id.cardRating1), findViewById(R.id.cardRating2), findViewById(R.id.cardRating3), findViewById(R.id.cardRating4), findViewById(R.id.cardRating5)));
textRatingTextViewsInvisible = new ArrayList<TextView>(Arrays.asList(findViewById(R.id.textRating1), findViewById(R.id.textRating2), findViewById(R.id.textRating3), findViewById(R.id.textRating4), findViewById(R.id.textRating5)));
}
for (int i = 0; i < textRatingCardViewsInvisible.size(); i++) {
textRatingCardViewsInvisible.get(i).setVisibility(View.INVISIBLE);
textRatingTextViewsInvisible.get(i).setVisibility(View.INVISIBLE);
}
}
});
FragmentManager fragmentManager = getSupportFragmentManager();
vpRecipe = findViewById(R.id.vpRecipe);
tabRecipe = findViewById(R.id.tabRecipe);
// todo: find out what this actually does... and if we need it or not
vpRecipe.requestDisallowInterceptTouchEvent(true);
vpAdapter = new RecipeActivityViewPagerAdapter(fragmentManager, getLifecycle(), directions, nutrition, ingredients, recipeId);
vpRecipe.setAdapter(vpAdapter);
btnAddToMyRecipes = findViewById(R.id.btnAddToMyRecipes);
// if recipe already exists in user's My Recipes, hide the add recipe button
if (sqlDb.testDao().isRecipeExists(recipeId)) {
btnAddToMyRecipes.setEnabled(false);
btnAddToMyRecipes.setVisibility(View.GONE);
}
btnAddToMyRecipes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CollectionReference dbItems = db.collection("Items");
// Item item = new Item(ingredients.get(i), null, email);
// prevent user from adding same list of ingredients twice
// .whereEqualTo(ingredients.get(i), null).get().addOnCompleteListener(
// todo: RecipesRating
db.collection("Recipes").document(recipeId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
// find largest list between categories, directions, ingredients, and nutrition
int maxSize = Collections.max(Arrays.asList(categories.size(), directions.size(), ingredients.size(), nutrition.size()));
EZMealDatabase sqlDb = Room.databaseBuilder(getApplicationContext(), EZMealDatabase.class, "user").allowMainThreadQueries().fallbackToDestructiveMigration().build();
// uncomment to nuke the users database
// sqlDb.testDao().BOOM();
// sqlDb.testDao().BOOOOOOOM();
Recipe newRecipe = new Recipe(imageUrl, title, recipeId);
sqlDb.testDao().insert(newRecipe);
// would result in out of bound errors
for (int x = 0; x < maxSize; x++) {
String cat;
String dir;
String ing;
String nut;
if (x < categories.size()) {
cat = categories.get(x);
} else {
cat = null;
}
if (x < directions.size()) {
dir = directions.get(x);
} else {
dir = null;
}
if (x < ingredients.size()) {
ing = ingredients.get(x);
} else {
ing = null;
}
if (x < nutrition.size()) {
nut = nutrition.get(x);
} else {
nut = null;
}
CategoryEntity item = new CategoryEntity(recipeId, cat, nut, dir, ing);
sqlDb.testDao().insertItem(item);
}
Toast.makeText(getApplicationContext(), "Recipe added!", Toast.LENGTH_SHORT).show();
// disable add recipe button so that user cannot attempt to add same recipe twice
btnAddToMyRecipes.setEnabled(false);
btnAddToMyRecipes.setVisibility(View.GONE);
// mAuth = FirebaseAuth.getInstance();
// FirebaseUser mCurrentUser = mAuth.getCurrentUser();
// String email = mCurrentUser.getEmail();
// UserRecipe savedRecipe = new UserRecipe(categories, directions, ingredients, nutrition, imageUrl, title, recipeId);
// CollectionReference dbRecipes = db.collection("UserRecipes");
// ArrayList<UserRecipe> userRecipeList = new ArrayList<UserRecipe>();
// userRecipeList.add(savedRecipe);
// getContext().deleteDatabase("EZMealDatabase");
/*db.collection("Recipes").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>()
{
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task)
{
for (QueryDocumentSnapshot document : task.getResult())
{
Log.i("retrieve", document.getId() + "=> " + document.getData());
String title = document.getString("title");
Uri uri = Uri.parse(document.getString("imageUrl"));
//findRecipesModel.addItem(title, uri);
//findRecipesAdapter.notifyDataSetChanged();
//recipeId.add(document.getId());
}
}
}).addOnFailureListener(new OnFailureListener()
{
@Override
public void onFailure(@NonNull Exception e)
{
}
});*/
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
});
/*
String recipeId = null;
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null)
{
// retrieve category name from the Intent
recipeId = extras.getString("id");
}
*/
/*
if (savedInstanceState == null)
{
getParentFragmentManager().beginTransaction().setReorderingAllowed(true).add(R.id.fragmentContainerView, RecipeInstructionsFragment.class, null)
.commit();
}
*/
nestedScrollView = findViewById(R.id.nestedScrollNutrition);
TextView txt = (TextView) LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_name, null);
new TabLayoutMediator(tabRecipe, vpRecipe, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
switch(position) {
case 0:
// tab.setText("Ingredients");
TextView txtIngredients = (TextView) LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_name, null);
txtIngredients.setText("Ingredients");
nestedScrollView = findViewById(R.id.nestedScrollIngredients);
tab.setCustomView(txtIngredients);
break;
case 1:
// tab.setText("Directions");
TextView txtDirections = (TextView) LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_name, null);
txtDirections.setText("Directions");
nestedScrollView = findViewById(R.id.nestedScrollDirections);
tab.setCustomView(txtDirections);
break;
case 2:
// tab.setText("Nutrition");
TextView txtNutrition = (TextView) LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_name, null);
txtNutrition.setText("Nutrition");
nestedScrollView = findViewById(R.id.nestedScrollNutrition);
tab.setCustomView(txtNutrition);
break;
case 3:
TextView txtRatings = (TextView) LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_name, null);
txtRatings.setText("Ratings");
nestedScrollView = findViewById(R.id.nestedScrollRatings);
tab.setCustomView(txtRatings);
break;
}
}
}).attach();
}
use of com.example.ezmeal.roomDatabase.Recipe in project EZMeal by Jake-Sokol2.
the class CategoryFragmentRepository method readRecipes.
public void readRecipes(RecipeCallback callback, String category, RetrievedRecipeLists recipeLists) {
int numRecipesToQuery;
int recipeSearchStartId;
// the rest will be queried later
if (recipeLists.getNumVerticalToQuery() == recipeLists.getNumRemainingVerticalRecipes()) {
numRecipesToQuery = recipeLists.getNumVerticalToQuery() / 2;
recipeSearchStartId = recipeLists.getRandomQueryId();
} else // if this isn't the first time through, just query the rest of the remaining recipes starting where the first query ended
// doing this guarantees that we will find all of the recipes we need
{
numRecipesToQuery = recipeLists.getNumRemainingVerticalRecipes();
recipeSearchStartId = recipeLists.getVerticalEndId();
}
dbRecipes.whereArrayContains("categories", category).whereGreaterThanOrEqualTo("recipeId", recipeSearchStartId).orderBy("recipeId").limit(numRecipesToQuery).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
List<VerticalRecipe> verticalList = new ArrayList<>();
List<HorizontalRecipe> horizontalList = new ArrayList<>();
List<RecyclerRecipe2> recyclerRecipe2List = new ArrayList<>();
List<RecyclerRecipe2> horizontalRecyclerRecipe2List = new ArrayList<>();
int startId = 0;
int endId = 0;
int i = 0;
// todo: change for loop format, enhanced for isn't right for this
for (QueryDocumentSnapshot document : task.getResult()) {
double recipeIdDouble = document.getDouble("recipeId");
int recipeIdInt = (int) recipeIdDouble;
if (i == 0) {
// keep track of first recipeId for later queries
startId = recipeIdInt;
} else {
// keep track of last recipeId for later queries
endId = recipeIdInt;
}
String imageUrl = document.getString("imageUrl");
String title = document.getString("title");
String recipeIdString = document.getId();
boolean highlyRated = document.getBoolean("highlyRated");
Double countRating = document.getDouble("countRating");
Double avgRating;
if (countRating != null) {
avgRating = document.getDouble("rating") / countRating;
} else {
countRating = 0.0;
avgRating = 0.0;
}
if (Double.isNaN(avgRating)) {
avgRating = 0.0;
}
Integer totalRating = countRating.intValue();
int sizeOfSet = recipeLists.getSetOfUniqueVerticalRecipes().size();
recipeLists.addToSetOfUniqueVerticalRecipes(recipeIdInt);
// duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
if (recipeLists.getSetOfUniqueVerticalRecipes().size() != sizeOfSet) {
if (// (viewModel.getNumOfRetrievedHighRatedRecipes() >= (halfMaxNumberOfHighRatedRecipes * 2)))
(!highlyRated) || ((recipeLists.getHorizontalList().size()) >= recipeLists.getNumHorizontalToQuery())) {
recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumRemainingVerticalRecipes() - 1);
RecyclerRecipe2 recyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "vertical", false, totalRating);
recyclerRecipe2List.add(recyclerRecipe2);
VerticalRecipe newRecipe = new VerticalRecipe(title, imageUrl, recipeIdString, avgRating, totalRating);
verticalList.add(newRecipe);
// /verticalRecipeIdList.add(recipeIdString);
// todo: may need to uncomment and convert this for onClick
// recipeId.add(recipeIdString);
} else // add to horizontal highly rated list instead of vertical recyclerview
{
// Set<Integer> setOfUniqueHighRatedRecipes = viewModel.getSetOfUniqueHighRatedRecipes();
int sizeOfHighRatedSetBefore = recipeLists.getSetOfUniqueHorizontalRecipes().size();
recipeLists.addToSetOfUniqueHorizontalRecipes(recipeIdInt);
// duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
if (sizeOfHighRatedSetBefore != recipeLists.getSetOfUniqueHorizontalRecipes().size()) {
// viewModel.incrementNumOfRetrievedHighRatedRecipes(1);
// todo: may need to uncomment and convert, adding new private member to the class
// numOfRetrievedHighRatedRecipes++;
// highRatedTitles.add(title);
// highRatedImages.add(imageUrl);
// highRatedRecipeIdList.add(recipeIdString);
// highRatedRatings.add(avgRating);
HorizontalRecipe newRecipe = new HorizontalRecipe(title, imageUrl, recipeIdString, avgRating);
horizontalList.add(newRecipe);
// horizontalLists.get(horizontalLists.size() - 1).add(newRecipe);
// /horizontalRecipeIdList.add(recipeIdString);
RecyclerRecipe2 horizontalRecyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "Popular Recipe", true, totalRating);
horizontalRecyclerRecipe2List.add(horizontalRecyclerRecipe2);
// sqlDb.testDao().insertRecyclerRecipe2(recyclerRecipePopular2);
}
}
}
i++;
}
// recipeLists.appendVerticalList(verticalList);
// recipeLists.appendHorizontalList(horizontalList);
// recipeLists.setVerticalStartId(startId);
// recipeLists.setVerticalEndId(endId);
// todo: uncomment
// callback.onCallback(verticalList, horizontalList, startId, endId);
recipeLists.setVerticalStartId(startId);
recipeLists.setVerticalEndId(endId);
recipeLists.appendVerticalList(verticalList);
recipeLists.appendHorizontalList(horizontalList);
// recipeLists.setNumRemainingVerticalRecipes(verticalList.size() - recipeLists.getNumRemainingVerticalRecipes());
// try to query all remaining vertical recipes in the opposite direction. This could still fail to return all vertical recipes
dbRecipes.whereArrayContains("categories", category).whereLessThan("recipeId", recipeLists.getRandomQueryId()).orderBy("recipeId").limit(recipeLists.getNumRemainingVerticalRecipes()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
// int numRetrievedRecipes = numOfRetrievedRecipes; //viewModel.getNumOfRetrievedRecipes();
List<VerticalRecipe> verticalList = new ArrayList<>();
List<HorizontalRecipe> horizontalList = new ArrayList<>();
int startId = 0;
// todo: change for loop format, enhanced for isn't right for this
for (QueryDocumentSnapshot document : task.getResult()) {
double recipeIdDouble = document.getDouble("recipeId");
int recipeIdInt = (int) recipeIdDouble;
// here, startId refers to the entire query's start. It is the left bound of all searched recipeId's
startId = recipeIdInt;
String imageUrl = document.getString("imageUrl");
String title = document.getString("title");
String recipeIdString = document.getId();
boolean highlyRated = document.getBoolean("highlyRated");
Double countRating = document.getDouble("countRating");
Double avgRating;
if (countRating != null) {
avgRating = document.getDouble("rating") / countRating;
} else {
countRating = 0.0;
avgRating = 0.0;
}
if (Double.isNaN(avgRating)) {
avgRating = 0.0;
}
Integer totalRating = countRating.intValue();
// Set<Integer> setOfUniqueRecipes = viewModel.getSetOfUniqueRecipes();
int sizeOfSet = recipeLists.getSetOfUniqueVerticalRecipes().size();
recipeLists.addToSetOfUniqueVerticalRecipes(recipeIdInt);
// duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
if (recipeLists.getSetOfUniqueVerticalRecipes().size() != sizeOfSet) {
// only add recipe to the vertical recycler if its not highly rated or we've already filled the horizontal with the max number of recipes
if (// (viewModel.getNumOfRetrievedHighRatedRecipes() >= (halfMaxNumberOfHighRatedRecipes * 2)))
(!highlyRated) || ((recipeLists.getHorizontalList().size()) >= recipeLists.getNumHorizontalToQuery())) {
// viewModel.incrementNumOfRetrievedRecipesBy(1);
recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumRemainingVerticalRecipes() - 1);
// ratings.add(avgRating);
// totalRatingsCountList.add(totalRating);
RecyclerRecipe2 recyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "vertical", false, totalRating);
// recyclerRecipeList2.add(recyclerRecipe2);
recyclerRecipe2List.add(recyclerRecipe2);
// categoryFragmentModel.addItem(title, imageUrl, avgRating, totalRating);
VerticalRecipe newRecipe = new VerticalRecipe(title, imageUrl, recipeIdString, avgRating, totalRating);
verticalList.add(newRecipe);
// /verticalRecipeIdList.add(recipeIdString);
// verticalRecipes.add(newRecipe);
// todo: may need to uncomment and convert this for onClick
// recipeId.add(recipeIdString);
} else // add to horizontal highly rated list instead of vertical recyclerview
{
// Set<Integer> setOfUniqueHighRatedRecipes = viewModel.getSetOfUniqueHighRatedRecipes();
int sizeOfHighRatedSetBefore = recipeLists.getSetOfUniqueHorizontalRecipes().size();
recipeLists.addToSetOfUniqueHorizontalRecipes(recipeIdInt);
// duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
if (sizeOfHighRatedSetBefore != recipeLists.getSetOfUniqueHorizontalRecipes().size()) {
// viewModel.incrementNumOfRetrievedHighRatedRecipes(1);
// todo: may need to uncomment and convert, adding new private member to the class
// numOfRetrievedHighRatedRecipes++;
// highRatedTitles.add(title);
// highRatedImages.add(imageUrl);
// highRatedRecipeIdList.add(recipeIdString);
// highRatedRatings.add(avgRating);
HorizontalRecipe newRecipe = new HorizontalRecipe(title, imageUrl, recipeIdString, avgRating);
horizontalList.add(newRecipe);
// /horizontalRecipeIdList.add(recipeIdString);
// horizontalLists.get(horizontalLists.size() - 1).add(newRecipe);
RecyclerRecipe2 horizontalRecyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "Popular Recipe", true, totalRating);
horizontalRecyclerRecipe2List.add(horizontalRecyclerRecipe2);
// sqlDb.testDao().insertRecyclerRecipe2(recyclerRecipePopular2);
}
}
}
}
recipeLists.setVerticalStartId(startId);
recipeLists.appendVerticalList(verticalList);
recipeLists.appendHorizontalList(horizontalList);
// query the rest of the vertical recipes if necessary
if ((recipeLists.getNumRemainingVerticalRecipes() > 0) && (recipeLists.getNumRemainingVerticalRecipes() < recipeLists.getNumVerticalToQuery())) {
int numRecipesToQuery;
int recipeSearchStartId;
// the rest will be queried later
if (recipeLists.getNumVerticalToQuery() == recipeLists.getNumRemainingVerticalRecipes()) {
numRecipesToQuery = recipeLists.getNumVerticalToQuery() / 2;
recipeSearchStartId = recipeLists.getRandomQueryId();
} else // if this isn't the first time through, just query the rest of the remaining recipes starting where the first query ended
// doing this guarantees that we will find all of the recipes we need
{
numRecipesToQuery = recipeLists.getNumRemainingVerticalRecipes();
recipeSearchStartId = recipeLists.getVerticalEndId();
}
dbRecipes.whereArrayContains("categories", category).whereGreaterThanOrEqualTo("recipeId", recipeSearchStartId).orderBy("recipeId").limit(numRecipesToQuery).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
// int numRetrievedRecipes = numOfRetrievedRecipes; //viewModel.getNumOfRetrievedRecipes();
List<VerticalRecipe> verticalList = new ArrayList<>();
List<HorizontalRecipe> horizontalList = new ArrayList<>();
int startId = 0;
int endId = 0;
int i = 0;
// todo: change for loop format, enhanced for isn't right for this
for (QueryDocumentSnapshot document : task.getResult()) {
double recipeIdDouble = document.getDouble("recipeId");
int recipeIdInt = (int) recipeIdDouble;
if (i == 0) {
// keep track of first recipeId for later queries
startId = recipeIdInt;
} else {
// keep track of last recipeId for later queries
endId = recipeIdInt;
}
String imageUrl = document.getString("imageUrl");
String title = document.getString("title");
String recipeIdString = document.getId();
boolean highlyRated = document.getBoolean("highlyRated");
Double countRating = document.getDouble("countRating");
Double avgRating;
if (countRating != null) {
avgRating = document.getDouble("rating") / countRating;
} else {
countRating = 0.0;
avgRating = 0.0;
}
if (Double.isNaN(avgRating)) {
avgRating = 0.0;
}
Integer totalRating = countRating.intValue();
// Set<Integer> setOfUniqueRecipes = viewModel.getSetOfUniqueRecipes();
int sizeOfSet = recipeLists.getSetOfUniqueVerticalRecipes().size();
recipeLists.addToSetOfUniqueVerticalRecipes(recipeIdInt);
// duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
if (recipeLists.getSetOfUniqueVerticalRecipes().size() != sizeOfSet) {
// or we aren't in our first query (accounting for high rated recipes in the third query would force us to do recursion to ensure we get enough vertical recipes)
if (// (viewModel.getNumOfRetrievedHighRatedRecipes() >= (halfMaxNumberOfHighRatedRecipes * 2)))
(!highlyRated) || ((recipeLists.getHorizontalList().size()) >= recipeLists.getNumHorizontalToQuery()) || (numRecipesToQuery <= 0)) {
// viewModel.incrementNumOfRetrievedRecipesBy(1);
recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumRemainingVerticalRecipes() - 1);
// ratings.add(avgRating);
// totalRatingsCountList.add(totalRating);
RecyclerRecipe2 recyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "vertical", false, totalRating);
recyclerRecipe2List.add(recyclerRecipe2);
// categoryFragmentModel.addItem(title, imageUrl, avgRating, totalRating);
VerticalRecipe newRecipe = new VerticalRecipe(title, imageUrl, recipeIdString, avgRating, totalRating);
verticalList.add(newRecipe);
// /verticalRecipeIdList.add(recipeIdString);
// verticalRecipes.add(newRecipe);
// todo: may need to uncomment and convert this for onClick
// recipeId.add(recipeIdString);
} else // add to horizontal highly rated list instead of vertical recyclerview
{
// Set<Integer> setOfUniqueHighRatedRecipes = viewModel.getSetOfUniqueHighRatedRecipes();
int sizeOfHighRatedSetBefore = recipeLists.getSetOfUniqueHorizontalRecipes().size();
recipeLists.addToSetOfUniqueHorizontalRecipes(recipeIdInt);
// duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
if (sizeOfHighRatedSetBefore != recipeLists.getSetOfUniqueHorizontalRecipes().size()) {
// viewModel.incrementNumOfRetrievedHighRatedRecipes(1);
// todo: may need to uncomment and convert, adding new private member to the class
// numOfRetrievedHighRatedRecipes++;
// highRatedTitles.add(title);
// highRatedImages.add(imageUrl);
// highRatedRecipeIdList.add(recipeIdString);
// highRatedRatings.add(avgRating);
HorizontalRecipe newRecipe = new HorizontalRecipe(title, imageUrl, recipeIdString, avgRating);
horizontalList.add(newRecipe);
// /horizontalRecipeIdList.add(recipeIdString);
// horizontalLists.get(horizontalLists.size() - 1).add(newRecipe);
RecyclerRecipe2 horizontalRecyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "Popular Recipe", true, totalRating);
horizontalRecyclerRecipe2List.add(horizontalRecyclerRecipe2);
// sqlDb.testDao().insertRecyclerRecipe2(recyclerRecipePopular2);
}
}
}
i++;
}
recipeLists.setVerticalEndId(endId);
recipeLists.appendVerticalList(verticalList);
recipeLists.appendHorizontalList(horizontalList);
// recipeLists.appendVerticalRecipeIdList(verticalRecipeIdList);
// recipeLists.appendHorizontalRecipeIdList(horizontalRecipeIdList);
recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumRemainingVerticalRecipes() - verticalList.size());
List<RecyclerRecipe2> tempList = new ArrayList<>();
// recyclerRecipe2List.addAll(horizontalRecyclerRecipe2List);
tempList.addAll(recyclerRecipe2List);
tempList.addAll(horizontalRecyclerRecipe2List);
roomRepository.insertAllRecyclerRecipe2(recyclerRecipe2List);
roomRepository.insertAllRecyclerRecipe2(horizontalRecyclerRecipe2List);
if (recipeLists.getHorizontalList().size() < recipeLists.getNumHorizontalToQuery()) {
// search to the left of the left bound
dbRecipes.whereArrayContains("categories", category).whereGreaterThan("recipeId", recipeLists.getVerticalStartId()).limit(recipeLists.getNumHorizontalToQuery() - recipeLists.getHorizontalList().size()).get().addOnCompleteListener(taskHorizontal -> {
Log.i("queries", "queried outer");
List<HorizontalRecipe> retrievedHorizontalList = retrieveHorizontal(recipeLists, category, "Popular Recipe", taskHorizontal);
recipeLists.appendHorizontalList(retrievedHorizontalList);
int numLeftToRetrieve = recipeLists.getNumHorizontalToQuery() - recipeLists.getHorizontalList().size();
if (numLeftToRetrieve > 0) {
// search to the right of the right bound
dbRecipes.whereArrayContains("categories", category).whereLessThan("recipeId", recipeLists.getVerticalEndId()).limit(numLeftToRetrieve).get().addOnCompleteListener(taskSecondHorizontal -> {
Log.i("queries", "queried inner");
List<HorizontalRecipe> retrievedListInner = retrieveHorizontal(recipeLists, category, "Popular Recipe", taskSecondHorizontal);
recipeLists.appendHorizontalList(retrievedListInner);
callback.onCallback(recipeLists);
// liveDataHorizontal.setValue(horizontalLists);
});
} else {
callback.onCallback(recipeLists);
}
});
} else {
}
}
});
} else {
if (recipeLists.getHorizontalList().size() < recipeLists.getNumHorizontalToQuery()) {
// search to the left of the left bound
dbRecipes.whereArrayContains("categories", category).whereGreaterThan("recipeId", recipeLists.getVerticalStartId()).limit(recipeLists.getNumHorizontalToQuery()).get().addOnCompleteListener(taskHorizontal -> {
Log.i("queries", "queried outer");
List<HorizontalRecipe> retrievedHorizontalList = retrieveHorizontal(recipeLists, category, "Popular Recipe", taskHorizontal);
recipeLists.appendHorizontalList(retrievedHorizontalList);
int numLeftToRetrieve = recipeLists.getNumHorizontalToQuery() - recipeLists.getHorizontalList().size();
if (numLeftToRetrieve > 0) {
// search to the right of the right bound
dbRecipes.whereArrayContains("categories", category).whereLessThan("recipeId", recipeLists.getVerticalEndId()).limit(numLeftToRetrieve).get().addOnCompleteListener(taskSecondHorizontal -> {
Log.i("queries", "queried inner");
List<HorizontalRecipe> retrievedListInner = retrieveHorizontal(recipeLists, category, "Popular Recipe", taskSecondHorizontal);
recipeLists.appendHorizontalList(retrievedListInner);
callback.onCallback(recipeLists);
// liveDataHorizontal.setValue(horizontalLists);
});
} else {
callback.onCallback(recipeLists);
}
});
}
}
// recipeLists.appendVerticalList(verticalList);
// recipeLists.appendHorizontalList(horizontalList);
// recipeLists.setVerticalStartId(startId);
// recipeLists.setVerticalEndId(endId);
// callback.onCallback(verticalList, horizontalList, startId);
// currentNumOfQueries = currentNumOfQueries + task.getResult().size() - 1;
// number of reads to firebase - for preventing excessive and expensive reads
// Log.i("number of queries", String.valueOf(currentNumOfQueries));
// todo: change this to retrieveAndSaveRandomRecipesLessThan to improve randomness. Make sure new functions does NOT create a new random number! Pass in current random number instead
// retrieveAndSaveRandomRecipesGreaterThanQuery(rand, numOfRecipes, halfMaxNumberOfHighRatedRecipes, individualQueryVerticalRecipeLimit, category, finalTotalRecursions);
// todo: delete
// categoryFragmentAdapter.notifyDataSetChanged();
}
});
// currentNumOfQueries = currentNumOfQueries + task.getResult().size() - 1;
// number of reads to firebase - for preventing excessive and expensive reads
// Log.i("number of queries", String.valueOf(currentNumOfQueries));
// todo: change this to retrieveAndSaveRandomRecipesLessThan to improve randomness. Make sure new functions does NOT create a new random number! Pass in current random number instead
// retrieveAndSaveRandomRecipesGreaterThanQuery(rand, numOfRecipes, halfMaxNumberOfHighRatedRecipes, individualQueryVerticalRecipeLimit, category, finalTotalRecursions);
// todo: delete
// categoryFragmentAdapter.notifyDataSetChanged();
}
});
}
Aggregations