Search in sources :

Example 1 with RetrievedRecipeLists

use of com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists in project EZMeal by Jake-Sokol2.

the class CategoryFragment 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_find_recipes_category, container, false);
    viewModel = new ViewModelProvider(requireActivity()).get(CategoryFragmentViewModel.class);
    rvFindRecipes = (RecyclerView) view.findViewById(R.id.rvFindRecipes);
    StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    rvFindRecipes.setLayoutManager(staggeredGridLayoutManager);
    rvFindRecipes.suppressLayout(true);
    categoryFragmentAdapter = new CategoryFragmentAdapter(verticalRecipes, horizontalLists);
    rvFindRecipes.setAdapter(categoryFragmentAdapter);
    categoryFragmentAdapter.setOnItemClickListener(new CategoryFragmentAdapter.MainAdapterListener() {

        @Override
        public void onItemClick(int position, boolean isClickable) {
            // certain positions may be an entire horizontal recyclerview - only allow clicking for positions that are actual individual recipes, not holders for horizontal rv's
            if (isClickable) {
                Intent intent = new Intent(getContext(), RecipeActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("id", recipeIdList.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }
    });
    rvFindRecipes.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            rvFindRecipes.setVisibility(View.VISIBLE);
            rvFindRecipes.suppressLayout(false);
            rvFindRecipes.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
    sqlDb = Room.databaseBuilder(getActivity().getApplicationContext(), EZMealDatabase.class, "user").allowMainThreadQueries().fallbackToDestructiveMigration().enableMultiInstanceInvalidation().build();
    Bundle extras = getArguments();
    if (extras != null) {
        category = extras.getString("cat");
    }
    swipeLayout = view.findViewById(R.id.swipeCategory);
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            // clear all category recipes from Room, to be overwritten with new ones
            deleteEntireCategory(category);
            verticalRecipes.clear();
            horizontalLists.clear();
            categoryFragmentAdapter.notifyDataSetChanged();
            viewModel.setDataOther(category);
            // turn off refreshing logo
            swipeLayout.setRefreshing(false);
        }
    });
    // Observers
    viewModel.getIsPopulated().observe(getViewLifecycleOwner(), returnIsPopulated -> {
        isPopulated = returnIsPopulated;
    });
    viewModel.getDataOther().observe(getViewLifecycleOwner(), new Observer<RetrievedRecipeLists>() {

        @Override
        public void onChanged(RetrievedRecipeLists retrievedRecipeLists) {
            if (// && list.size() > 0)
            retrievedRecipeLists != null) {
                horizontalLists.clear();
                verticalRecipes.clear();
                horizontalLists.add(retrievedRecipeLists.getHorizontalList());
                List<VerticalRecipe> tempVerticalList = new ArrayList<>();
                tempVerticalList = retrievedRecipeLists.getVerticalList();
                for (int i = 0; i < tempVerticalList.size(); i++) {
                    verticalRecipes.add(tempVerticalList.get(i));
                    recipeIdList.add(tempVerticalList.get(i).getRecipeId());
                }
                categoryFragmentAdapter.notifyDataSetChanged();
            }
        }
    });
    viewModel.getLastCategory().observe(getViewLifecycleOwner(), returnedCategory -> {
        lastCategory = returnedCategory;
    });
    return view;
}
Also used : CategoryFragmentAdapter(com.example.ezmeal.FindRecipes.FindRecipesAdapters.CategoryFragmentAdapter) EZMealDatabase(com.example.ezmeal.roomDatabase.EZMealDatabase) Bundle(android.os.Bundle) StaggeredGridLayoutManager(androidx.recyclerview.widget.StaggeredGridLayoutManager) Intent(android.content.Intent) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) CategoryFragmentViewModel(com.example.ezmeal.FindRecipes.FindRecipesViewModels.CategoryFragmentViewModel) RetrievedRecipeLists(com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists) ArrayList(java.util.ArrayList) List(java.util.List) ViewTreeObserver(android.view.ViewTreeObserver) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Example 2 with RetrievedRecipeLists

use of com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists in project EZMeal by Jake-Sokol2.

the class CategoryFragmentRepository method readRecipes.

public void readRecipes(RecipeCallback callback, String category, RetrievedRecipeLists recipeLists) {
    int numRecipesToQuery;
    int recipeSearchStartId;
    // the rest will be queried later
    if (recipeLists.getNumVerticalToQuery() == recipeLists.getNumRemainingVerticalRecipes()) {
        numRecipesToQuery = recipeLists.getNumVerticalToQuery() / 2;
        recipeSearchStartId = recipeLists.getRandomQueryId();
    } else // if this isn't the first time through, just query the rest of the remaining recipes starting where the first query ended
    // doing this guarantees that we will find all of the recipes we need
    {
        numRecipesToQuery = recipeLists.getNumRemainingVerticalRecipes();
        recipeSearchStartId = recipeLists.getVerticalEndId();
    }
    dbRecipes.whereArrayContains("categories", category).whereGreaterThanOrEqualTo("recipeId", recipeSearchStartId).orderBy("recipeId").limit(numRecipesToQuery).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            List<VerticalRecipe> verticalList = new ArrayList<>();
            List<HorizontalRecipe> horizontalList = new ArrayList<>();
            List<RecyclerRecipe2> recyclerRecipe2List = new ArrayList<>();
            List<RecyclerRecipe2> horizontalRecyclerRecipe2List = new ArrayList<>();
            int startId = 0;
            int endId = 0;
            int i = 0;
            // todo: change for loop format, enhanced for isn't right for this
            for (QueryDocumentSnapshot document : task.getResult()) {
                double recipeIdDouble = document.getDouble("recipeId");
                int recipeIdInt = (int) recipeIdDouble;
                if (i == 0) {
                    // keep track of first recipeId for later queries
                    startId = recipeIdInt;
                } else {
                    // keep track of last recipeId for later queries
                    endId = recipeIdInt;
                }
                String imageUrl = document.getString("imageUrl");
                String title = document.getString("title");
                String recipeIdString = document.getId();
                boolean highlyRated = document.getBoolean("highlyRated");
                Double countRating = document.getDouble("countRating");
                Double avgRating;
                if (countRating != null) {
                    avgRating = document.getDouble("rating") / countRating;
                } else {
                    countRating = 0.0;
                    avgRating = 0.0;
                }
                if (Double.isNaN(avgRating)) {
                    avgRating = 0.0;
                }
                Integer totalRating = countRating.intValue();
                int sizeOfSet = recipeLists.getSetOfUniqueVerticalRecipes().size();
                recipeLists.addToSetOfUniqueVerticalRecipes(recipeIdInt);
                // duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
                if (recipeLists.getSetOfUniqueVerticalRecipes().size() != sizeOfSet) {
                    if (// (viewModel.getNumOfRetrievedHighRatedRecipes() >= (halfMaxNumberOfHighRatedRecipes * 2)))
                    (!highlyRated) || ((recipeLists.getHorizontalList().size()) >= recipeLists.getNumHorizontalToQuery())) {
                        recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumRemainingVerticalRecipes() - 1);
                        RecyclerRecipe2 recyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "vertical", false, totalRating);
                        recyclerRecipe2List.add(recyclerRecipe2);
                        VerticalRecipe newRecipe = new VerticalRecipe(title, imageUrl, recipeIdString, avgRating, totalRating);
                        verticalList.add(newRecipe);
                    // /verticalRecipeIdList.add(recipeIdString);
                    // todo: may need to uncomment and convert this for onClick
                    // recipeId.add(recipeIdString);
                    } else // add to horizontal highly rated list instead of vertical recyclerview
                    {
                        // Set<Integer> setOfUniqueHighRatedRecipes = viewModel.getSetOfUniqueHighRatedRecipes();
                        int sizeOfHighRatedSetBefore = recipeLists.getSetOfUniqueHorizontalRecipes().size();
                        recipeLists.addToSetOfUniqueHorizontalRecipes(recipeIdInt);
                        // duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
                        if (sizeOfHighRatedSetBefore != recipeLists.getSetOfUniqueHorizontalRecipes().size()) {
                            // viewModel.incrementNumOfRetrievedHighRatedRecipes(1);
                            // todo: may need to uncomment and convert, adding new private member to the class
                            // numOfRetrievedHighRatedRecipes++;
                            // highRatedTitles.add(title);
                            // highRatedImages.add(imageUrl);
                            // highRatedRecipeIdList.add(recipeIdString);
                            // highRatedRatings.add(avgRating);
                            HorizontalRecipe newRecipe = new HorizontalRecipe(title, imageUrl, recipeIdString, avgRating);
                            horizontalList.add(newRecipe);
                            // horizontalLists.get(horizontalLists.size() - 1).add(newRecipe);
                            // /horizontalRecipeIdList.add(recipeIdString);
                            RecyclerRecipe2 horizontalRecyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "Popular Recipe", true, totalRating);
                            horizontalRecyclerRecipe2List.add(horizontalRecyclerRecipe2);
                        // sqlDb.testDao().insertRecyclerRecipe2(recyclerRecipePopular2);
                        }
                    }
                }
                i++;
            }
            // recipeLists.appendVerticalList(verticalList);
            // recipeLists.appendHorizontalList(horizontalList);
            // recipeLists.setVerticalStartId(startId);
            // recipeLists.setVerticalEndId(endId);
            // todo: uncomment
            // callback.onCallback(verticalList, horizontalList, startId, endId);
            recipeLists.setVerticalStartId(startId);
            recipeLists.setVerticalEndId(endId);
            recipeLists.appendVerticalList(verticalList);
            recipeLists.appendHorizontalList(horizontalList);
            // recipeLists.setNumRemainingVerticalRecipes(verticalList.size() - recipeLists.getNumRemainingVerticalRecipes());
            // try to query all remaining vertical recipes in the opposite direction.  This could still fail to return all vertical recipes
            dbRecipes.whereArrayContains("categories", category).whereLessThan("recipeId", recipeLists.getRandomQueryId()).orderBy("recipeId").limit(recipeLists.getNumRemainingVerticalRecipes()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    // int numRetrievedRecipes = numOfRetrievedRecipes; //viewModel.getNumOfRetrievedRecipes();
                    List<VerticalRecipe> verticalList = new ArrayList<>();
                    List<HorizontalRecipe> horizontalList = new ArrayList<>();
                    int startId = 0;
                    // todo: change for loop format, enhanced for isn't right for this
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        double recipeIdDouble = document.getDouble("recipeId");
                        int recipeIdInt = (int) recipeIdDouble;
                        // here, startId refers to the entire query's start.  It is the left bound of all searched recipeId's
                        startId = recipeIdInt;
                        String imageUrl = document.getString("imageUrl");
                        String title = document.getString("title");
                        String recipeIdString = document.getId();
                        boolean highlyRated = document.getBoolean("highlyRated");
                        Double countRating = document.getDouble("countRating");
                        Double avgRating;
                        if (countRating != null) {
                            avgRating = document.getDouble("rating") / countRating;
                        } else {
                            countRating = 0.0;
                            avgRating = 0.0;
                        }
                        if (Double.isNaN(avgRating)) {
                            avgRating = 0.0;
                        }
                        Integer totalRating = countRating.intValue();
                        // Set<Integer> setOfUniqueRecipes = viewModel.getSetOfUniqueRecipes();
                        int sizeOfSet = recipeLists.getSetOfUniqueVerticalRecipes().size();
                        recipeLists.addToSetOfUniqueVerticalRecipes(recipeIdInt);
                        // duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
                        if (recipeLists.getSetOfUniqueVerticalRecipes().size() != sizeOfSet) {
                            // only add recipe to the vertical recycler if its not highly rated or we've already filled the horizontal with the max number of recipes
                            if (// (viewModel.getNumOfRetrievedHighRatedRecipes() >= (halfMaxNumberOfHighRatedRecipes * 2)))
                            (!highlyRated) || ((recipeLists.getHorizontalList().size()) >= recipeLists.getNumHorizontalToQuery())) {
                                // viewModel.incrementNumOfRetrievedRecipesBy(1);
                                recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumRemainingVerticalRecipes() - 1);
                                // ratings.add(avgRating);
                                // totalRatingsCountList.add(totalRating);
                                RecyclerRecipe2 recyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "vertical", false, totalRating);
                                // recyclerRecipeList2.add(recyclerRecipe2);
                                recyclerRecipe2List.add(recyclerRecipe2);
                                // categoryFragmentModel.addItem(title, imageUrl, avgRating, totalRating);
                                VerticalRecipe newRecipe = new VerticalRecipe(title, imageUrl, recipeIdString, avgRating, totalRating);
                                verticalList.add(newRecipe);
                            // /verticalRecipeIdList.add(recipeIdString);
                            // verticalRecipes.add(newRecipe);
                            // todo: may need to uncomment and convert this for onClick
                            // recipeId.add(recipeIdString);
                            } else // add to horizontal highly rated list instead of vertical recyclerview
                            {
                                // Set<Integer> setOfUniqueHighRatedRecipes = viewModel.getSetOfUniqueHighRatedRecipes();
                                int sizeOfHighRatedSetBefore = recipeLists.getSetOfUniqueHorizontalRecipes().size();
                                recipeLists.addToSetOfUniqueHorizontalRecipes(recipeIdInt);
                                // duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
                                if (sizeOfHighRatedSetBefore != recipeLists.getSetOfUniqueHorizontalRecipes().size()) {
                                    // viewModel.incrementNumOfRetrievedHighRatedRecipes(1);
                                    // todo: may need to uncomment and convert, adding new private member to the class
                                    // numOfRetrievedHighRatedRecipes++;
                                    // highRatedTitles.add(title);
                                    // highRatedImages.add(imageUrl);
                                    // highRatedRecipeIdList.add(recipeIdString);
                                    // highRatedRatings.add(avgRating);
                                    HorizontalRecipe newRecipe = new HorizontalRecipe(title, imageUrl, recipeIdString, avgRating);
                                    horizontalList.add(newRecipe);
                                    // /horizontalRecipeIdList.add(recipeIdString);
                                    // horizontalLists.get(horizontalLists.size() - 1).add(newRecipe);
                                    RecyclerRecipe2 horizontalRecyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "Popular Recipe", true, totalRating);
                                    horizontalRecyclerRecipe2List.add(horizontalRecyclerRecipe2);
                                // sqlDb.testDao().insertRecyclerRecipe2(recyclerRecipePopular2);
                                }
                            }
                        }
                    }
                    recipeLists.setVerticalStartId(startId);
                    recipeLists.appendVerticalList(verticalList);
                    recipeLists.appendHorizontalList(horizontalList);
                    // query the rest of the vertical recipes if necessary
                    if ((recipeLists.getNumRemainingVerticalRecipes() > 0) && (recipeLists.getNumRemainingVerticalRecipes() < recipeLists.getNumVerticalToQuery())) {
                        int numRecipesToQuery;
                        int recipeSearchStartId;
                        // the rest will be queried later
                        if (recipeLists.getNumVerticalToQuery() == recipeLists.getNumRemainingVerticalRecipes()) {
                            numRecipesToQuery = recipeLists.getNumVerticalToQuery() / 2;
                            recipeSearchStartId = recipeLists.getRandomQueryId();
                        } else // if this isn't the first time through, just query the rest of the remaining recipes starting where the first query ended
                        // doing this guarantees that we will find all of the recipes we need
                        {
                            numRecipesToQuery = recipeLists.getNumRemainingVerticalRecipes();
                            recipeSearchStartId = recipeLists.getVerticalEndId();
                        }
                        dbRecipes.whereArrayContains("categories", category).whereGreaterThanOrEqualTo("recipeId", recipeSearchStartId).orderBy("recipeId").limit(numRecipesToQuery).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                            @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                // int numRetrievedRecipes = numOfRetrievedRecipes; //viewModel.getNumOfRetrievedRecipes();
                                List<VerticalRecipe> verticalList = new ArrayList<>();
                                List<HorizontalRecipe> horizontalList = new ArrayList<>();
                                int startId = 0;
                                int endId = 0;
                                int i = 0;
                                // todo: change for loop format, enhanced for isn't right for this
                                for (QueryDocumentSnapshot document : task.getResult()) {
                                    double recipeIdDouble = document.getDouble("recipeId");
                                    int recipeIdInt = (int) recipeIdDouble;
                                    if (i == 0) {
                                        // keep track of first recipeId for later queries
                                        startId = recipeIdInt;
                                    } else {
                                        // keep track of last recipeId for later queries
                                        endId = recipeIdInt;
                                    }
                                    String imageUrl = document.getString("imageUrl");
                                    String title = document.getString("title");
                                    String recipeIdString = document.getId();
                                    boolean highlyRated = document.getBoolean("highlyRated");
                                    Double countRating = document.getDouble("countRating");
                                    Double avgRating;
                                    if (countRating != null) {
                                        avgRating = document.getDouble("rating") / countRating;
                                    } else {
                                        countRating = 0.0;
                                        avgRating = 0.0;
                                    }
                                    if (Double.isNaN(avgRating)) {
                                        avgRating = 0.0;
                                    }
                                    Integer totalRating = countRating.intValue();
                                    // Set<Integer> setOfUniqueRecipes = viewModel.getSetOfUniqueRecipes();
                                    int sizeOfSet = recipeLists.getSetOfUniqueVerticalRecipes().size();
                                    recipeLists.addToSetOfUniqueVerticalRecipes(recipeIdInt);
                                    // duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
                                    if (recipeLists.getSetOfUniqueVerticalRecipes().size() != sizeOfSet) {
                                        // or we aren't in our first query (accounting for high rated recipes in the third query would force us to do recursion to ensure we get enough vertical recipes)
                                        if (// (viewModel.getNumOfRetrievedHighRatedRecipes() >= (halfMaxNumberOfHighRatedRecipes * 2)))
                                        (!highlyRated) || ((recipeLists.getHorizontalList().size()) >= recipeLists.getNumHorizontalToQuery()) || (numRecipesToQuery <= 0)) {
                                            // viewModel.incrementNumOfRetrievedRecipesBy(1);
                                            recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumRemainingVerticalRecipes() - 1);
                                            // ratings.add(avgRating);
                                            // totalRatingsCountList.add(totalRating);
                                            RecyclerRecipe2 recyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "vertical", false, totalRating);
                                            recyclerRecipe2List.add(recyclerRecipe2);
                                            // categoryFragmentModel.addItem(title, imageUrl, avgRating, totalRating);
                                            VerticalRecipe newRecipe = new VerticalRecipe(title, imageUrl, recipeIdString, avgRating, totalRating);
                                            verticalList.add(newRecipe);
                                        // /verticalRecipeIdList.add(recipeIdString);
                                        // verticalRecipes.add(newRecipe);
                                        // todo: may need to uncomment and convert this for onClick
                                        // recipeId.add(recipeIdString);
                                        } else // add to horizontal highly rated list instead of vertical recyclerview
                                        {
                                            // Set<Integer> setOfUniqueHighRatedRecipes = viewModel.getSetOfUniqueHighRatedRecipes();
                                            int sizeOfHighRatedSetBefore = recipeLists.getSetOfUniqueHorizontalRecipes().size();
                                            recipeLists.addToSetOfUniqueHorizontalRecipes(recipeIdInt);
                                            // duplicates cannot be added to Sets - only go ahead if we haven't found a duplicate recipe
                                            if (sizeOfHighRatedSetBefore != recipeLists.getSetOfUniqueHorizontalRecipes().size()) {
                                                // viewModel.incrementNumOfRetrievedHighRatedRecipes(1);
                                                // todo: may need to uncomment and convert, adding new private member to the class
                                                // numOfRetrievedHighRatedRecipes++;
                                                // highRatedTitles.add(title);
                                                // highRatedImages.add(imageUrl);
                                                // highRatedRecipeIdList.add(recipeIdString);
                                                // highRatedRatings.add(avgRating);
                                                HorizontalRecipe newRecipe = new HorizontalRecipe(title, imageUrl, recipeIdString, avgRating);
                                                horizontalList.add(newRecipe);
                                                // /horizontalRecipeIdList.add(recipeIdString);
                                                // horizontalLists.get(horizontalLists.size() - 1).add(newRecipe);
                                                RecyclerRecipe2 horizontalRecyclerRecipe2 = new RecyclerRecipe2(category, recipeIdString, title, imageUrl, avgRating, "Popular Recipe", true, totalRating);
                                                horizontalRecyclerRecipe2List.add(horizontalRecyclerRecipe2);
                                            // sqlDb.testDao().insertRecyclerRecipe2(recyclerRecipePopular2);
                                            }
                                        }
                                    }
                                    i++;
                                }
                                recipeLists.setVerticalEndId(endId);
                                recipeLists.appendVerticalList(verticalList);
                                recipeLists.appendHorizontalList(horizontalList);
                                // recipeLists.appendVerticalRecipeIdList(verticalRecipeIdList);
                                // recipeLists.appendHorizontalRecipeIdList(horizontalRecipeIdList);
                                recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumRemainingVerticalRecipes() - verticalList.size());
                                List<RecyclerRecipe2> tempList = new ArrayList<>();
                                // recyclerRecipe2List.addAll(horizontalRecyclerRecipe2List);
                                tempList.addAll(recyclerRecipe2List);
                                tempList.addAll(horizontalRecyclerRecipe2List);
                                roomRepository.insertAllRecyclerRecipe2(recyclerRecipe2List);
                                roomRepository.insertAllRecyclerRecipe2(horizontalRecyclerRecipe2List);
                                if (recipeLists.getHorizontalList().size() < recipeLists.getNumHorizontalToQuery()) {
                                    // search to the left of the left bound
                                    dbRecipes.whereArrayContains("categories", category).whereGreaterThan("recipeId", recipeLists.getVerticalStartId()).limit(recipeLists.getNumHorizontalToQuery() - recipeLists.getHorizontalList().size()).get().addOnCompleteListener(taskHorizontal -> {
                                        Log.i("queries", "queried outer");
                                        List<HorizontalRecipe> retrievedHorizontalList = retrieveHorizontal(recipeLists, category, "Popular Recipe", taskHorizontal);
                                        recipeLists.appendHorizontalList(retrievedHorizontalList);
                                        int numLeftToRetrieve = recipeLists.getNumHorizontalToQuery() - recipeLists.getHorizontalList().size();
                                        if (numLeftToRetrieve > 0) {
                                            // search to the right of the right bound
                                            dbRecipes.whereArrayContains("categories", category).whereLessThan("recipeId", recipeLists.getVerticalEndId()).limit(numLeftToRetrieve).get().addOnCompleteListener(taskSecondHorizontal -> {
                                                Log.i("queries", "queried inner");
                                                List<HorizontalRecipe> retrievedListInner = retrieveHorizontal(recipeLists, category, "Popular Recipe", taskSecondHorizontal);
                                                recipeLists.appendHorizontalList(retrievedListInner);
                                                callback.onCallback(recipeLists);
                                            // liveDataHorizontal.setValue(horizontalLists);
                                            });
                                        } else {
                                            callback.onCallback(recipeLists);
                                        }
                                    });
                                } else {
                                }
                            }
                        });
                    } else {
                        if (recipeLists.getHorizontalList().size() < recipeLists.getNumHorizontalToQuery()) {
                            // search to the left of the left bound
                            dbRecipes.whereArrayContains("categories", category).whereGreaterThan("recipeId", recipeLists.getVerticalStartId()).limit(recipeLists.getNumHorizontalToQuery()).get().addOnCompleteListener(taskHorizontal -> {
                                Log.i("queries", "queried outer");
                                List<HorizontalRecipe> retrievedHorizontalList = retrieveHorizontal(recipeLists, category, "Popular Recipe", taskHorizontal);
                                recipeLists.appendHorizontalList(retrievedHorizontalList);
                                int numLeftToRetrieve = recipeLists.getNumHorizontalToQuery() - recipeLists.getHorizontalList().size();
                                if (numLeftToRetrieve > 0) {
                                    // search to the right of the right bound
                                    dbRecipes.whereArrayContains("categories", category).whereLessThan("recipeId", recipeLists.getVerticalEndId()).limit(numLeftToRetrieve).get().addOnCompleteListener(taskSecondHorizontal -> {
                                        Log.i("queries", "queried inner");
                                        List<HorizontalRecipe> retrievedListInner = retrieveHorizontal(recipeLists, category, "Popular Recipe", taskSecondHorizontal);
                                        recipeLists.appendHorizontalList(retrievedListInner);
                                        callback.onCallback(recipeLists);
                                    // liveDataHorizontal.setValue(horizontalLists);
                                    });
                                } else {
                                    callback.onCallback(recipeLists);
                                }
                            });
                        }
                    }
                // recipeLists.appendVerticalList(verticalList);
                // recipeLists.appendHorizontalList(horizontalList);
                // recipeLists.setVerticalStartId(startId);
                // recipeLists.setVerticalEndId(endId);
                // callback.onCallback(verticalList, horizontalList, startId);
                // currentNumOfQueries = currentNumOfQueries + task.getResult().size() - 1;
                // number of reads to firebase - for preventing excessive and expensive reads
                // Log.i("number of queries", String.valueOf(currentNumOfQueries));
                // todo: change this to retrieveAndSaveRandomRecipesLessThan to improve randomness.  Make sure new functions does NOT create a new random number!  Pass in current random number instead
                // retrieveAndSaveRandomRecipesGreaterThanQuery(rand, numOfRecipes, halfMaxNumberOfHighRatedRecipes, individualQueryVerticalRecipeLimit, category, finalTotalRecursions);
                // todo: delete
                // categoryFragmentAdapter.notifyDataSetChanged();
                }
            });
        // currentNumOfQueries = currentNumOfQueries + task.getResult().size() - 1;
        // number of reads to firebase - for preventing excessive and expensive reads
        // Log.i("number of queries", String.valueOf(currentNumOfQueries));
        // todo: change this to retrieveAndSaveRandomRecipesLessThan to improve randomness.  Make sure new functions does NOT create a new random number!  Pass in current random number instead
        // retrieveAndSaveRandomRecipesGreaterThanQuery(rand, numOfRecipes, halfMaxNumberOfHighRatedRecipes, individualQueryVerticalRecipeLimit, category, finalTotalRecursions);
        // todo: delete
        // categoryFragmentAdapter.notifyDataSetChanged();
        }
    });
}
Also used : VerticalRecipe(com.example.ezmeal.FindRecipes.FindRecipesModels.VerticalRecipe) MutableLiveData(androidx.lifecycle.MutableLiveData) NonNull(androidx.annotation.NonNull) HorizontalRecipe(com.example.ezmeal.FindRecipes.FindRecipesModels.HorizontalRecipe) Random(java.util.Random) Callable(java.util.concurrent.Callable) Task(com.google.android.gms.tasks.Task) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) A(org.checkerframework.checker.units.qual.A) Recipe(com.example.ezmeal.roomDatabase.Recipe) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) VerticalRecipe(com.example.ezmeal.FindRecipes.FindRecipesModels.VerticalRecipe) CollectionReference(com.google.firebase.firestore.CollectionReference) Log(android.util.Log) ExecutorService(java.util.concurrent.ExecutorService) CategoryFragmentViewModel(com.example.ezmeal.FindRecipes.FindRecipesViewModels.CategoryFragmentViewModel) RetrievedRecipeLists(com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists) Set(java.util.Set) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) Executors(java.util.concurrent.Executors) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) TimeUnit(java.util.concurrent.TimeUnit) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Application(android.app.Application) RecyclerRecipe2(com.example.ezmeal.roomDatabase.RecyclerRecipe2) Task(com.google.android.gms.tasks.Task) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) ArrayList(java.util.ArrayList) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) NonNull(androidx.annotation.NonNull) ArrayList(java.util.ArrayList) List(java.util.List) HorizontalRecipe(com.example.ezmeal.FindRecipes.FindRecipesModels.HorizontalRecipe) RecyclerRecipe2(com.example.ezmeal.roomDatabase.RecyclerRecipe2)

Example 3 with RetrievedRecipeLists

use of com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists in project EZMeal by Jake-Sokol2.

the class CategoryFragmentRoomRepository method queryCategoriesWithRecipes.

public void queryCategoriesWithRecipes() {
    ExecutorService es = Executors.newSingleThreadExecutor();
    es.submit((Callable<Void>) () -> {
        RetrievedRecipeLists tempRecipeList = new RetrievedRecipeLists();
        List<HorizontalRecipe> tempHorizontalList = new ArrayList<>();
        List<VerticalRecipe> tempVerticalList = new ArrayList<>();
        List<String> tempRecipeIdList = new ArrayList<>();
        if (savedRecipeList == null) {
            savedRecipeList = new ArrayList<>();
        } else {
            List<RecyclerRecipe2> tempRecyclerRecipeList = savedRecipeList.get(0).recyclerRecipe2List;
            for (int i = 0; i < tempRecyclerRecipeList.size(); i++) {
                if (tempRecyclerRecipeList.get(i).isHorizontal) {
                    HorizontalRecipe tempHorizontalRecipe = new HorizontalRecipe(tempRecyclerRecipeList.get(i).getTitle(), tempRecyclerRecipeList.get(i).getImageUrl(), tempRecyclerRecipeList.get(i).getRecipeId(), tempRecyclerRecipeList.get(i).getAverageRating());
                    tempHorizontalList.add(tempHorizontalRecipe);
                } else {
                    VerticalRecipe tempVerticalRecipe = new VerticalRecipe(tempRecyclerRecipeList.get(i).getTitle(), tempRecyclerRecipeList.get(i).getImageUrl(), tempRecyclerRecipeList.get(i).getRecipeId(), tempRecyclerRecipeList.get(i).getAverageRating(), tempRecyclerRecipeList.get(i).getTotalRatings());
                    tempVerticalList.add(tempVerticalRecipe);
                }
                tempRecipeIdList.add(tempRecyclerRecipeList.get(i).getRecipeId());
            }
            tempRecipeList.appendRecipeIdList(tempRecipeIdList);
            tempRecipeList.appendHorizontalList(tempHorizontalList);
            tempRecipeList.appendVerticalList(tempVerticalList);
        }
        returnRecipes.setValue(tempRecipeList);
        return null;
    });
}
Also used : VerticalRecipe(com.example.ezmeal.FindRecipes.FindRecipesModels.VerticalRecipe) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) RetrievedRecipeLists(com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists) ArrayList(java.util.ArrayList) List(java.util.List) HorizontalRecipe(com.example.ezmeal.FindRecipes.FindRecipesModels.HorizontalRecipe)

Example 4 with RetrievedRecipeLists

use of com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists in project EZMeal by Jake-Sokol2.

the class CategoryFragmentRepository method setDataOther.

public void setDataOther(String category) {
    recipeLists = new RetrievedRecipeLists();
    // MutableLiveData<RetrievedRecipeLists> returnLists = new MutableLiveData<>();
    Random rand = new Random();
    recipeLists.setRandomQueryId(rand.nextInt(Integer.MAX_VALUE - 2));
    // todo: stop hardcoding this
    int numRecipes = 10;
    // String category = "Cookies";
    roomRepository.deleteFromCategory2SpecificCategory(category);
    roomRepository.deleteFromRecyclerRecipe2SpecificCategory(category);
    MutableLiveData<List<HorizontalRecipe>> liveDataHorizontal = new MutableLiveData<>();
    // query 20 vertical recipes
    recipeLists.setNumVerticalToQuery(20);
    recipeLists.setNumHorizontalToQuery(10);
    // total number remaining
    recipeLists.setNumRemainingVerticalRecipes(recipeLists.getNumVerticalToQuery());
    // sqlDb.testDao().insertRecyclerRecipe2(recipe);
    readRecipes(new RecipeCallback() {

        @Override
        public void onCallback(RetrievedRecipeLists retrievedRecipeLists) {
            recipeLists = retrievedRecipeLists;
            Log.i("a", "a");
            returnLists.setValue(recipeLists);
        }
    }, category, recipeLists);
}
Also used : Random(java.util.Random) MutableLiveData(androidx.lifecycle.MutableLiveData) RetrievedRecipeLists(com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

RetrievedRecipeLists (com.example.ezmeal.FindRecipes.FindRecipesModels.RetrievedRecipeLists)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 MutableLiveData (androidx.lifecycle.MutableLiveData)2 HorizontalRecipe (com.example.ezmeal.FindRecipes.FindRecipesModels.HorizontalRecipe)2 VerticalRecipe (com.example.ezmeal.FindRecipes.FindRecipesModels.VerticalRecipe)2 CategoryFragmentViewModel (com.example.ezmeal.FindRecipes.FindRecipesViewModels.CategoryFragmentViewModel)2 Random (java.util.Random)2 ExecutorService (java.util.concurrent.ExecutorService)2 Application (android.app.Application)1 Intent (android.content.Intent)1 Bundle (android.os.Bundle)1 Log (android.util.Log)1 View (android.view.View)1 ViewTreeObserver (android.view.ViewTreeObserver)1 NonNull (androidx.annotation.NonNull)1 ViewModelProvider (androidx.lifecycle.ViewModelProvider)1 RecyclerView (androidx.recyclerview.widget.RecyclerView)1 StaggeredGridLayoutManager (androidx.recyclerview.widget.StaggeredGridLayoutManager)1 SwipeRefreshLayout (androidx.swiperefreshlayout.widget.SwipeRefreshLayout)1