Search in sources :

Example 1 with EZMealDatabase

use of com.example.ezmeal.roomDatabase.EZMealDatabase 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 EZMealDatabase

use of com.example.ezmeal.roomDatabase.EZMealDatabase 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 EZMealDatabase

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

the class CategoryFragmentAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    final int itemType = getItemViewType(position);
    if (position == 6) {
        db = FirebaseFirestore.getInstance();
        // todo: RecipesRating
        dbRecipes = db.collection("Recipes");
        StaggeredGridLayoutManager.LayoutParams staggeredLayout = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
        staggeredLayout.setFullSpan(true);
        holder.itemView.setLayoutParams(staggeredLayout);
        HorizontalViewHolder horizontalHolder = (HorizontalViewHolder) holder;
        horizontalHolder.horizontalRecipes.setBackgroundColor(Color.parseColor("#ffffffff"));
        RecyclerView.LayoutManager horizontalManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        horizontalHolder.childHorizontalRecyclerView.setHasFixedSize(true);
        horizontalHolder.childHorizontalRecyclerView.setLayoutManager(horizontalManager);
        EZMealDatabase sqlDb = Room.databaseBuilder(holder.itemView.getContext(), EZMealDatabase.class, "user").allowMainThreadQueries().fallbackToDestructiveMigration().build();
        CategoryFragmentChildHorizontalRecyclerModel horizontalModel;
        horizontalModel = new CategoryFragmentChildHorizontalRecyclerModel(popularRecipesTitleList, popularRecipesImageList, avgPopularRatingList);
        CategoryFragmentChildHorizontalRecylerAdapter highRatedRecipesAdapter = new CategoryFragmentChildHorizontalRecylerAdapter(horizontalLists.get(0));
        /*CategoryFragmentChildHorizontalRecylerAdapter highRatedRecipesAdapter = new CategoryFragmentChildHorizontalRecylerAdapter(horizontalModel.getRecipeList(),
                    horizontalModel.getUriList(), horizontalHolder.childHorizontalRecyclerView.getContext(), horizontalModel.getAvgRatingList());*/
        highRatedRecipesAdapter.setOnItemClickListener(new CategoryFragmentChildHorizontalRecylerAdapter.MainAdapterListener() {

            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(holder.itemView.getContext(), RecipeActivity.class);
                Bundle bundle = new Bundle();
                // highRatedRecipeIdList.get(position));
                bundle.putString("id", horizontalLists.get(0).get(position).getRecipeId());
                intent.putExtras(bundle);
                holder.itemView.getContext().startActivity(intent);
            }
        });
        horizontalHolder.childHorizontalRecyclerView.setAdapter(highRatedRecipesAdapter);
    } else {
        MainViewHolder verticalHolder = (MainViewHolder) holder;
        StaggeredGridLayoutManager.LayoutParams staggeredLayout = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
        staggeredLayout.setFullSpan(false);
        holder.itemView.setLayoutParams(staggeredLayout);
        String recipeTitle = verticalRecipes.get(position).getTitle();
        uri = verticalRecipes.get(position).getImage();
        verticalHolder.txtTitle.setText(recipeTitle);
        Glide.with(verticalHolder.itemView.getContext()).load(uri).into(verticalHolder.recipeImage);
        Double avgRatingDouble = verticalRecipes.get(position).getAvgRating();
        float avgRatingFloat = avgRatingDouble.floatValue();
        if (verticalRecipes.get(position).getTotalCountOfRatings() >= COUNT_THRESHOLD_TO_SHOW_RECIPES) {
            // todo: there is an underlying issue here - we shouldn't need to set this to VISIBLE as it should never be set INVISIBLE.  For some reason the recyclerview sets it invisible anyway
            verticalHolder.ratingBar.setVisibility(View.VISIBLE);
            verticalHolder.ratingBar.setRating(avgRatingFloat);
        } else {
            verticalHolder.ratingBar.setVisibility(View.INVISIBLE);
        }
    }
}
Also used : EZMealDatabase(com.example.ezmeal.roomDatabase.EZMealDatabase) Bundle(android.os.Bundle) StaggeredGridLayoutManager(androidx.recyclerview.widget.StaggeredGridLayoutManager) Intent(android.content.Intent) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) CategoryFragmentChildHorizontalRecyclerModel(com.example.ezmeal.FindRecipes.FindRecipesModels.CategoryFragmentChildHorizontalRecyclerModel) RecipeActivity(com.example.ezmeal.FindRecipes.RecipeActivity) RecyclerView(androidx.recyclerview.widget.RecyclerView)

Example 4 with EZMealDatabase

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

the class CategoryFragmentFeaturedRecyclerAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    final int itemType = getItemViewType(position);
    db = FirebaseFirestore.getInstance();
    // todo: RecipesRating
    dbRecipes = db.collection("Recipes");
    StaggeredGridLayoutManager.LayoutParams staggeredLayout = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
    staggeredLayout.setFullSpan(true);
    holder.itemView.setLayoutParams(staggeredLayout);
    HorizontalViewHolder horizontalHolder = (HorizontalViewHolder) holder;
    horizontalHolder.horizontalRecipes.setBackgroundColor(Color.parseColor("#ffffffff"));
    RecyclerView.LayoutManager horizontalManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
    horizontalHolder.childHorizontalRecyclerView.setHasFixedSize(true);
    horizontalHolder.childHorizontalRecyclerView.setLayoutManager(horizontalManager);
    EZMealDatabase sqlDb = Room.databaseBuilder(holder.itemView.getContext(), EZMealDatabase.class, "user").allowMainThreadQueries().fallbackToDestructiveMigration().build();
    CategoryFragmentChildHorizontalRecyclerModel horizontalModel;
    horizontalModel = new CategoryFragmentChildHorizontalRecyclerModel(popularRecipesTitleList, popularRecipesImageList, avgPopularRatingList);
    // CategoryFragmentChildHorizontalRecylerAdapter highRatedRecipesAdapter = new CategoryFragmentChildHorizontalRecylerAdapter(horizontalModel.getRecipeList(),
    // horizontalModel.getUriList(), horizontalHolder.childHorizontalRecyclerView.getContext(), horizontalModel.getAvgRatingList());
    horizontalHolder.txtTitle.setText(verticalTitleList.get(position));
    if (horizontalLists.size() > 0) {
        Log.i("active categories", "horizontalLists size > 0 inside vertical recyclerAdapter");
        Log.i("active categories", "size in vertical adapter - " + String.valueOf(horizontalLists.size()));
        for (int i = 0; i < horizontalLists.size(); i++) {
            Log.i("active categories", "looping list inside vertical adapter");
            Log.i("active categories", "\t" + i + ": " + String.valueOf(horizontalLists.get(i)));
        }
        CategoryFragmentChildHorizontalRecylerAdapter highRatedRecipesAdapter = new CategoryFragmentChildHorizontalRecylerAdapter(horizontalLists.get(position));
        highRatedRecipesAdapter.setOnItemClickListener(new CategoryFragmentChildHorizontalRecylerAdapter.MainAdapterListener() {

            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(holder.itemView.getContext(), RecipeActivity.class);
                Bundle bundle = new Bundle();
                // highRatedRecipeIdList.get(position));
                bundle.putString("id", horizontalLists.get(0).get(position).getRecipeId());
                intent.putExtras(bundle);
                holder.itemView.getContext().startActivity(intent);
            }
        });
        horizontalHolder.childHorizontalRecyclerView.setAdapter(highRatedRecipesAdapter);
    /*if (position == 0)
        {
            final int itemType = getItemViewType(position);

            db = FirebaseFirestore.getInstance();
            // todo: RecipesRating
            dbRecipes = db.collection("RecipesRatingBigInt");

            StaggeredGridLayoutManager.LayoutParams staggeredLayout = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
            staggeredLayout.setFullSpan(true);
            holder.itemView.setLayoutParams(staggeredLayout);

            HorizontalViewHolder horizontalHolder = (HorizontalViewHolder) holder;

            horizontalHolder.horizontalRecipes.setBackgroundColor(Color.parseColor("#ffffffff"));

            RecyclerView.LayoutManager horizontalManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
            horizontalHolder.childHorizontalRecyclerView.setHasFixedSize(true);

            horizontalHolder.childHorizontalRecyclerView.setLayoutManager(horizontalManager);

            EZMealDatabase sqlDb = Room.databaseBuilder(holder.itemView.getContext(), EZMealDatabase.class, "user")
                    .allowMainThreadQueries().fallbackToDestructiveMigration().build();

            CategoryFragmentChildHorizontalRecyclerModel horizontalModel;

            horizontalModel = new CategoryFragmentChildHorizontalRecyclerModel(popularRecipesTitleList, popularRecipesImageList, avgPopularRatingList);

            //CategoryFragmentChildHorizontalRecylerAdapter highRatedRecipesAdapter = new CategoryFragmentChildHorizontalRecylerAdapter(horizontalModel.getRecipeList(),
            //        horizontalModel.getUriList(), horizontalHolder.childHorizontalRecyclerView.getContext(), horizontalModel.getAvgRatingList());

            horizontalHolder.txtTitle.setText(verticalTitleList.get(position));

            if (horizontalLists.size() > 0)
            {
                Log.i("active categories", "horizontalLists size > 0 inside vertical recyclerAdapter");
                Log.i("active categories", "size in vertical adapter - " + String.valueOf(horizontalLists.size()));
                CategoryFragmentChildHorizontalRecylerAdapter highRatedRecipesAdapter = new CategoryFragmentChildHorizontalRecylerAdapter(horizontalLists.get(position));

                highRatedRecipesAdapter.setOnItemClickListener(new CategoryFragmentChildHorizontalRecylerAdapter.MainAdapterListener()
                {
                    @Override
                    public void onItemClick(int position)
                    {
                        Intent intent = new Intent(holder.itemView.getContext(), RecipeActivity.class);
                        Bundle bundle = new Bundle();

                        //bundle.putString("id", highRatedRecipeIdList.get(position));
                        //intent.putExtras(bundle);
                        //holder.itemView.getContext().startActivity(intent);
                    }
                });

                horizontalHolder.childHorizontalRecyclerView.setAdapter(highRatedRecipesAdapter);*/
    // }
    } else {
        CategoryFragmentChildHorizontalRecylerAdapter highRatedRecipesAdapter = new CategoryFragmentChildHorizontalRecylerAdapter(horizontalLists.get(position));
        highRatedRecipesAdapter.setOnItemClickListener(new CategoryFragmentChildHorizontalRecylerAdapter.MainAdapterListener() {

            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(holder.itemView.getContext(), RecipeActivity.class);
                Bundle bundle = new Bundle();
            // bundle.putString("id", highRatedRecipeIdList.get(position));
            // intent.putExtras(bundle);
            // holder.itemView.getContext().startActivity(intent);
            }
        });
        horizontalHolder.childHorizontalRecyclerView.setAdapter(highRatedRecipesAdapter);
    }
}
Also used : EZMealDatabase(com.example.ezmeal.roomDatabase.EZMealDatabase) Bundle(android.os.Bundle) StaggeredGridLayoutManager(androidx.recyclerview.widget.StaggeredGridLayoutManager) Intent(android.content.Intent) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) CategoryFragmentChildHorizontalRecyclerModel(com.example.ezmeal.FindRecipes.FindRecipesModels.CategoryFragmentChildHorizontalRecyclerModel) RecipeActivity(com.example.ezmeal.FindRecipes.RecipeActivity) RecyclerView(androidx.recyclerview.widget.RecyclerView)

Example 5 with EZMealDatabase

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

the class RecipeDirectionsFragment 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_directions, container, false);
    Bundle extras = getArguments();
    String recipeId = extras.getString("id");
    rvDirections = (RecyclerView) view.findViewById(R.id.rvDirection);
    recipeDirectionsFragmentRecyclerAdapter = new RecipeDirectionsFragmentRecyclerAdapter(recipeDirectionsFragmentModel.getDirectionList());
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
    rvDirections.setAdapter(recipeDirectionsFragmentRecyclerAdapter);
    rvDirections.setLayoutManager(layoutManager);
    // Recyclerview borders
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rvDirections.getContext(), DividerItemDecoration.VERTICAL);
    rvDirections.addItemDecoration(dividerItemDecoration);
    EZMealDatabase sqlDb = Room.databaseBuilder(getActivity().getApplicationContext(), EZMealDatabase.class, "user").allowMainThreadQueries().fallbackToDestructiveMigration().build();
    // retrieve directions for current recipe from Room and populate in recyclerview
    directions = sqlDb.testDao().getDirections(recipeId);
    // insert into recyclerview
    for (int i = 0; i < directions.size(); i++) {
        if (directions.get(i) != null) {
            recipeDirectionsFragmentModel.addItem(directions.get(i));
        } else {
            i = directions.size();
        }
    }
    recipeDirectionsFragmentRecyclerAdapter.notifyDataSetChanged();
    return view;
}
Also used : EZMealDatabase(com.example.ezmeal.roomDatabase.EZMealDatabase) Bundle(android.os.Bundle) RecipeDirectionsFragmentRecyclerAdapter(com.example.ezmeal.MyRecipes.RecipeAdapters.RecipeDirectionsFragmentRecyclerAdapter) RecyclerView(androidx.recyclerview.widget.RecyclerView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView)

Aggregations

Bundle (android.os.Bundle)10 EZMealDatabase (com.example.ezmeal.roomDatabase.EZMealDatabase)10 RecyclerView (androidx.recyclerview.widget.RecyclerView)9 View (android.view.View)8 LinearLayoutManager (androidx.recyclerview.widget.LinearLayoutManager)8 DividerItemDecoration (androidx.recyclerview.widget.DividerItemDecoration)5 NonNull (androidx.annotation.NonNull)4 TextView (android.widget.TextView)3 StaggeredGridLayoutManager (androidx.recyclerview.widget.StaggeredGridLayoutManager)3 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)3 CollectionReference (com.google.firebase.firestore.CollectionReference)3 DocumentSnapshot (com.google.firebase.firestore.DocumentSnapshot)3 ArrayList (java.util.ArrayList)3 Intent (android.content.Intent)2 ImageView (android.widget.ImageView)2 CardView (androidx.cardview.widget.CardView)2 NestedScrollView (androidx.core.widget.NestedScrollView)2 FragmentManager (androidx.fragment.app.FragmentManager)2 CategoryFragmentChildHorizontalRecyclerModel (com.example.ezmeal.FindRecipes.FindRecipesModels.CategoryFragmentChildHorizontalRecyclerModel)2 RecipeActivity (com.example.ezmeal.FindRecipes.RecipeActivity)2