Search in sources :

Example 1 with Rating

use of com.example.ezmeal.roomDatabase.Rating 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();
}
Also used : EZMealDatabase(com.example.ezmeal.roomDatabase.EZMealDatabase) Recipe(com.example.ezmeal.roomDatabase.Recipe) Rating(com.example.ezmeal.roomDatabase.Rating) ArrayList(java.util.ArrayList) TabLayoutMediator(com.google.android.material.tabs.TabLayoutMediator) DataSnapshot(com.google.firebase.database.DataSnapshot) CollectionReference(com.google.firebase.firestore.CollectionReference) RecipeActivityViewPagerAdapter(com.example.ezmeal.FindRecipes.FindRecipesAdapters.RecipeActivityViewPagerAdapter) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) NonNull(androidx.annotation.NonNull) Iterator(java.util.Iterator) TextView(android.widget.TextView) List(java.util.List) ArrayList(java.util.ArrayList) ImageView(android.widget.ImageView) ValueEventListener(com.google.firebase.database.ValueEventListener) CategoryEntity(com.example.ezmeal.roomDatabase.CategoryEntity) DatabaseReference(com.google.firebase.database.DatabaseReference) Bundle(android.os.Bundle) Calendar(java.util.Calendar) CardView(androidx.cardview.widget.CardView) RatingBar(android.widget.RatingBar) NestedScrollView(androidx.core.widget.NestedScrollView) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) CardView(androidx.cardview.widget.CardView) TextView(android.widget.TextView) FragmentManager(androidx.fragment.app.FragmentManager) DatabaseError(com.google.firebase.database.DatabaseError) Map(java.util.Map) TreeMap(java.util.TreeMap) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 2 with Rating

use of com.example.ezmeal.roomDatabase.Rating in project EZMeal by Jake-Sokol2.

the class RecipeRatingsFragment method onStop.

@Override
public void onStop() {
    super.onStop();
    MutableLiveData<List<String>> test = vmRateRecipeBubble.getRatingBubbleList();
    chosenBubbles = test.getValue();
    // even though it is initialized in the ViewModel, getRatingBubbleList will return null if a value has not been set yet by the user
    if (chosenBubbles == null) {
        chosenBubbles = new ArrayList<String>();
    }
    // Room db insert/update expects 3 bubble selections when creating the record, so give it nulls for any missing ratings in case the user only selected 0-2 text ratings
    if (chosenBubbles.size() < 3) {
        for (int i = chosenBubbles.size(); i < 3; i++) {
            chosenBubbles.add(null);
        }
    }
    // get change in rating compared to user's previous rating (if one exists)
    float oldRating = sqlDb.testDao().getSpecificRating(recipeId);
    float newRating = rateRecipe.getRating();
    float changeInRating = newRating - oldRating;
    Rating r1 = sqlDb.testDao().getSpecificRatingObject(recipeId);
    Rating r2 = sqlDb.testDao().getAllTheThings();
    // if rating is different than it was when the user entered the recipe, they added / updated their rating, so update both database entries
    if (changeInRating != 0) {
        db = FirebaseFirestore.getInstance();
        // todo: RecipesRating
        CollectionReference dbRecipes = db.collection("Recipes");
        // if user has never left a review on this recipe before, increment number of ratings in firestore
        if (oldRating == 0) {
            dbRecipes.document(recipeId).update("countRating", FieldValue.increment(1)).addOnSuccessListener(new OnSuccessListener<Void>() {

                @Override
                public void onSuccess(Void unused) {
                    Log.i("rating", "numRating updated");
                }
            });
            // add a new entry to Room so their rating displays correctly next time they return to the recipe
            Rating newRatingEntry = new Rating(recipeId, newRating, chosenBubbles);
            sqlDb.testDao().insert(newRatingEntry);
            // increment count of Ratings so onStop() knows how to calculate the correct final average rating after new rating is written to firebase
            countOfRatings++;
        } else // if newRating is not 0, they changed their rating, so update existing Room entry
        if (newRating != 0) {
            // update their existing Room entry with the correct new rating
            Rating newRatingEntry = new Rating(recipeId, newRating, chosenBubbles);
            // decrement counters in firebase for any old text rating's that the user may have chosen on their last review
            decrementTextRatingsInFirebase();
            sqlDb.testDao().updateRating(newRating, recipeId);
            sqlDb.testDao().updateTextRatings(chosenBubbles.get(0), chosenBubbles.get(1), chosenBubbles.get(2), recipeId);
        }
        // if user added or changed their rating, update the total rating score in firestore
        if (newRating != 0) {
            // increment counters in firebase for text ratings
            // using chosenBubbles global list
            incrementTextRatingsInFirebase();
            // increment or decrement (depending on if changeInRating is positive or negative) Firestore rating by new value
            dbRecipes.document(recipeId).update("rating", FieldValue.increment(changeInRating)).addOnSuccessListener(new OnSuccessListener<Void>() {

                @Override
                public void onSuccess(Void unused) {
                    Log.i("rating", "rating updated");
                }
            });
        }
        // new rating pushed Recipe above the highly rated threshold - notify firebase
        if ((highlyRated == false) && ((changeInRating + totalRatingFirebase) / countOfRatings) >= 4) {
            dbRecipes.document(recipeId).update("highlyRated", true).addOnSuccessListener(new OnSuccessListener<Void>() {

                @Override
                public void onSuccess(Void unused) {
                    Log.i("rating", "highlyRated updated");
                }
            });
        } else // new rating dropped Recipe beneath the highly rated threshold - notify firebase
        if ((highlyRated) && ((changeInRating + totalRatingFirebase) / countOfRatings) < 4) {
            dbRecipes.document(recipeId).update("highlyRated", false).addOnSuccessListener(new OnSuccessListener<Void>() {

                @Override
                public void onSuccess(Void unused) {
                    Log.i("rating", "highlyRated updated");
                }
            });
        }
        if (sqlDb.isOpen()) {
            sqlDb.close();
        }
    }
}
Also used : Rating(com.example.ezmeal.roomDatabase.Rating) List(java.util.List) ArrayList(java.util.ArrayList) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) CollectionReference(com.google.firebase.firestore.CollectionReference)

Aggregations

Rating (com.example.ezmeal.roomDatabase.Rating)2 CollectionReference (com.google.firebase.firestore.CollectionReference)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Bundle (android.os.Bundle)1 View (android.view.View)1 ImageView (android.widget.ImageView)1 RatingBar (android.widget.RatingBar)1 TextView (android.widget.TextView)1 NonNull (androidx.annotation.NonNull)1 CardView (androidx.cardview.widget.CardView)1 NestedScrollView (androidx.core.widget.NestedScrollView)1 FragmentManager (androidx.fragment.app.FragmentManager)1 RecyclerView (androidx.recyclerview.widget.RecyclerView)1 RecipeActivityViewPagerAdapter (com.example.ezmeal.FindRecipes.FindRecipesAdapters.RecipeActivityViewPagerAdapter)1 CategoryEntity (com.example.ezmeal.roomDatabase.CategoryEntity)1 EZMealDatabase (com.example.ezmeal.roomDatabase.EZMealDatabase)1 Recipe (com.example.ezmeal.roomDatabase.Recipe)1 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)1 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)1