Search in sources :

Example 1 with CollectionReference

use of com.google.firebase.firestore.CollectionReference 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 CollectionReference

use of com.google.firebase.firestore.CollectionReference in project EZMeal by Jake-Sokol2.

the class RecipeIngredientsFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_recipe_ingredients, container, false);
    rvIngredients = (RecyclerView) view.findViewById(R.id.rvIngredientList);
    recipeIngredientsFragmentRecyclerAdapter = new RecipeIngredientsFragmentRecyclerAdapter(recipeIngredientsFragmentModel.getIngredients());
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
    rvIngredients.setAdapter(recipeIngredientsFragmentRecyclerAdapter);
    rvIngredients.setLayoutManager(layoutManager);
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rvIngredients.getContext(), DividerItemDecoration.VERTICAL);
    rvIngredients.addItemDecoration(dividerItemDecoration);
    Bundle extras = getArguments();
    String recipeId = extras.getString("id");
    // todo: RecipesRating
    db.collection("Recipes").document(recipeId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            ingredients = (ArrayList<String>) task.getResult().get("ingredients");
            for (int i = 0; i < ingredients.size(); i++) {
                if (!Objects.equals(ingredients.get(i), "")) {
                    recipeIngredientsFragmentModel.addItem(ingredients.get(i));
                } else {
                    i = ingredients.size();
                }
            }
            recipeIngredientsFragmentRecyclerAdapter.notifyDataSetChanged();
        }
    });
    // ingredientsArray = extras.getStringArrayList("ingredients");
    /*EZMealDatabase sqlDb = Room.databaseBuilder(getActivity().getApplicationContext(), EZMealDatabase.class, "user")
                .allowMainThreadQueries().fallbackToDestructiveMigration().build();

        ingredients = sqlDb.testDao().getIngredients(recipeId);

        for (int i = 0; i < ingredients.size(); i++)
        {
            if (ingredients.get(i) != null)
            {
                ingredientsModel.addItem(ingredients.get(i));
            }
            else
            {
                i = ingredients.size();
            }
        }
        ingredientsRecyclerAdapter.notifyDataSetChanged();*/
    // add all ingredients for this recipe to the user's Item collection in Firestore
    EZMealDatabase sqlDb = Room.databaseBuilder(getActivity().getApplicationContext(), EZMealDatabase.class, "user").allowMainThreadQueries().fallbackToDestructiveMigration().build();
    // add all ingredients for this recipe to the user's Item collection in Firestore
    btnAddToList = view.findViewById(R.id.btnAddToList);
    btnAddToList.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // in case user edited ingredient list, re-read ingredients from database
            // ingredients = sqlDb.testDao().getIngredients(recipeId);
            FirebaseUser mCurrentUser = mAuth.getCurrentUser();
            String email = mCurrentUser.getEmail();
            for (int i = 0; i < ingredients.size(); i++) {
                if (ingredients.get(i) != null) {
                    mAuth = FirebaseAuth.getInstance();
                    CollectionReference dbItems = db.collection("Items");
                    Item item = new Item(ingredients.get(i), null, email);
                    // prevent user from adding same list of ingredients twice
                    dbItems.whereEqualTo("name", ingredients.get(i)).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.getResult().isEmpty()) {
                                dbItems.add(item).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {

                                    @Override
                                    public void onSuccess(DocumentReference documentReference) {
                                        // keep track that an item was added so we can tell the user with a toast later
                                        itemAdded = true;
                                        Toast.makeText(getContext(), "Item added", Toast.LENGTH_SHORT).show();
                                    }
                                }).addOnFailureListener(new OnFailureListener() {

                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        e.printStackTrace();
                                    }
                                });
                                // if any items were actually added, tell the user
                                if (itemAdded) {
                                    Toast.makeText(getContext(), "Item added", Toast.LENGTH_SHORT).show();
                                }
                            }
                        /*if (task.isSuccessful())
                                {
                                    for (DocumentSnapshot document : task.getResult())
                                    {
                                        // if ingredient isn't already added to database, add it now
                                        if (!document.exists())
                                        {
                                            dbItems.add(item).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                                                @Override
                                                public void onSuccess(DocumentReference documentReference) {
                                                    // keep track that an item was added so we can tell the user with a toast later
                                                    itemAdded = true;

                                                }
                                            }).addOnFailureListener(new OnFailureListener()
                                            {
                                                @Override
                                                public void onFailure(@NonNull Exception e)
                                                {
                                                    e.printStackTrace();
                                                }
                                            });
                                        }
                                    }

                                    // if any items were actually added, tell the user
                                    if (itemAdded)
                                    {
                                        Toast.makeText(getContext(), "Item added", Toast.LENGTH_SHORT).show();
                                    }
                                }
                                else
                                {
                                    Log.i("q", "task not successful");
                                }*/
                        }
                    }).addOnFailureListener(new OnFailureListener() {

                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.i("q", "get failed");
                        }
                    });
                } else {
                    // escape loop if rest of ingredients list is null (nulls are a symptom of database insertion)
                    i = ingredients.size();
                }
            }
            btnAddToList.setEnabled(false);
            btnAddToList.setTextColor(Color.parseColor("#808080"));
        }
    });
    return view;
}
Also used : EZMealDatabase(com.example.ezmeal.roomDatabase.EZMealDatabase) ArrayList(java.util.ArrayList) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) CollectionReference(com.google.firebase.firestore.CollectionReference) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) Item(com.example.ezmeal.GroupLists.Model.Item) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) NonNull(androidx.annotation.NonNull) DocumentReference(com.google.firebase.firestore.DocumentReference) RecipeIngredientsFragmentRecyclerAdapter(com.example.ezmeal.MyRecipes.RecipeAdapters.RecipeIngredientsFragmentRecyclerAdapter) Bundle(android.os.Bundle) FirebaseUser(com.google.firebase.auth.FirebaseUser) DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) RecyclerView(androidx.recyclerview.widget.RecyclerView) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 3 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project EZMeal by Jake-Sokol2.

the class GroupListsFragmentModel method removeItem.

public void removeItem(int position) {
    itemName = shoppingList.get(position).get(0);
    brandName = shoppingList.get(position).get(1);
    String groupName = "Tristan";
    shoppingList.remove(position);
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser mCurrentUser = mAuth.getCurrentUser();
    String email = mCurrentUser.getEmail();
    /*
        CollectionReference dbItems = db.collection("Items");
        dbItems.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if(task.isSuccessful()) {
                    for(QueryDocumentSnapshot document : task.getResult()) {
                        Log.d("Hoyah", document.getId() + " => " + document.getData());
                        if(Objects.equals(itemName, document.getString("name")) &&
                        Objects.equals(document.getString("user"), email))
                        {
                            docID = document.getId();
                            dbItems.document(docID).delete();
                        } //end if
                    }// end for loop
                } //end task successful
            } //end onComplete

        });
        */
    CollectionReference dbItems = db.collection("Groups");
    dbItems.whereEqualTo("ListName", groupName).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                if (task.getResult().getDocuments().size() > 0) {
                    DocumentSnapshot tmpDoc = task.getResult().getDocuments().get(0);
                    String tmpDocName = tmpDoc.getId();
                    CollectionReference dbShoppingList = db.collection("Groups").document(tmpDocName).collection("Items");
                    dbShoppingList.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                for (QueryDocumentSnapshot aDoc : task.getResult()) {
                                    if (Objects.equals(itemName, aDoc.getString("name"))) {
                                        docID = aDoc.getId();
                                        dbShoppingList.document(docID).delete();
                                    }
                                }
                            }
                        }
                    });
                }
            }
        }
    });
}
Also used : QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) Task(com.google.android.gms.tasks.Task) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) NonNull(androidx.annotation.NonNull) FirebaseUser(com.google.firebase.auth.FirebaseUser) CollectionReference(com.google.firebase.firestore.CollectionReference) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot)

Example 4 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project EZMeal by Jake-Sokol2.

the class GroupListsViewModel method fillShoppingList.

public List<List<String>> fillShoppingList() {
    // String currentListName = groupList.get(getCurrentSelected());
    String currentListName = "Tristan";
    List<List<String>> tmpListOfLists = new ArrayList<>();
    String email = mAuth.getCurrentUser().getEmail();
    db.collection("Groups").whereEqualTo("ListName", currentListName).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                if (task.getResult().getDocuments().size() > 0) {
                    DocumentSnapshot tmpDoc = task.getResult().getDocuments().get(0);
                    String tmpDocName = tmpDoc.getId();
                    CollectionReference dbShoppingList = db.collection("Groups").document(tmpDocName).collection("Items");
                    dbShoppingList.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                for (QueryDocumentSnapshot docBoi : task.getResult()) {
                                    List<String> tmpList = new ArrayList<>();
                                    brandName = docBoi.getString("brand");
                                    itemName = docBoi.getString("name");
                                    tmpList.add(itemName);
                                    tmpList.add(brandName);
                                    tmpList.add("1");
                                    tmpListOfLists.add(tmpList);
                                }
                                Log.i("Query", "Finished filling shopping list");
                            }
                        }
                    });
                }
            }
        }
    });
    return tmpListOfLists;
}
Also used : Task(com.google.android.gms.tasks.Task) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) ArrayList(java.util.ArrayList) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) CollectionReference(com.google.firebase.firestore.CollectionReference) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) NonNull(androidx.annotation.NonNull) ArrayList(java.util.ArrayList) List(java.util.List)

Example 5 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project EZMeal by Jake-Sokol2.

the class GroupListsViewModel method removeItem.

public void removeItem(int position) {
    List<List<String>> tmp = new ArrayList<List<String>>();
    tmp = shoppingList.getValue();
    itemName = tmp.get(position).get(0);
    brandName = tmp.get(position).get(1);
    tmp.remove(position);
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser mCurrentUser = mAuth.getCurrentUser();
    String email = mCurrentUser.getEmail();
    CollectionReference dbItems = db.collection("Items");
    dbItems.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Log.d("Hoyah", document.getId() + " => " + document.getData());
                    if (Objects.equals(itemName, document.getString("name")) && Objects.equals(document.getString("user"), email)) {
                        docID = document.getId();
                        dbItems.document(docID).delete();
                    }
                // end if
                }
            // end for loop
            }
        // end task successful
        }
    });
}
Also used : QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) FirebaseUser(com.google.firebase.auth.FirebaseUser) CollectionReference(com.google.firebase.firestore.CollectionReference) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot)

Aggregations

CollectionReference (com.google.firebase.firestore.CollectionReference)43 QuerySnapshot (com.google.firebase.firestore.QuerySnapshot)15 Intent (android.content.Intent)14 QueryDocumentSnapshot (com.google.firebase.firestore.QueryDocumentSnapshot)14 View (android.view.View)13 DocumentSnapshot (com.google.firebase.firestore.DocumentSnapshot)13 NonNull (androidx.annotation.NonNull)10 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)10 DocumentReference (com.google.firebase.firestore.DocumentReference)10 FirebaseFirestoreException (com.google.firebase.firestore.FirebaseFirestoreException)10 ArrayList (java.util.ArrayList)8 Bundle (android.os.Bundle)7 ListView (android.widget.ListView)7 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)7 AdapterView (android.widget.AdapterView)6 TextView (android.widget.TextView)6 OnCompleteListener (com.google.android.gms.tasks.OnCompleteListener)5 Task (com.google.android.gms.tasks.Task)5 List (java.util.List)5 RecyclerView (androidx.recyclerview.widget.RecyclerView)4