Search in sources :

Example 1 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot in project NotiSender by choiman1559.

the class MainPreference method onCreatePreferences.

@SuppressLint("HardwareIds")
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.root_preferences, rootKey);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
    mGoogleSignInClient = GoogleSignIn.getClient(mContext, gso);
    mAuth = FirebaseAuth.getInstance();
    mFirebaseFirestore = FirebaseFirestore.getInstance();
    prefs = mContext.getSharedPreferences("com.noti.main_preferences", MODE_PRIVATE);
    logPrefs = mContext.getSharedPreferences("com.noti.main_logs", MODE_PRIVATE);
    mFirebaseFirestore.collection("ApiKey").get().addOnCompleteListener(task -> {
        if (task.isSuccessful() && task.getResult() != null) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                prefs.edit().putString("Latest_Version_Play", document.getString("Version_Play")).putString("ApiKey_FCM", document.getString("FCM")).putString("ApiKey_Pushy", document.getString("Pushy")).putString("ApiKey_Billing", document.getString("Billing")).apply();
            }
        } else {
            new MaterialAlertDialogBuilder(mContext).setTitle("Error occurred!").setMessage("Error occurred while initializing client token.\nplease check your internet connection and try again.").setPositiveButton("OK", (dialog, which) -> mContext.finishAndRemoveTask()).setCancelable(false);
        }
    });
    if (prefs.getString("FirebaseIIDPrefix", "").isEmpty()) {
        FirebaseInstallations.getInstance().getId().addOnCompleteListener(task -> {
            if (task.isSuccessful())
                prefs.edit().putString("FirebaseIIDPrefix", task.getResult()).apply();
        });
    }
    if (prefs.getString("AndroidIDPrefix", "").isEmpty()) {
        prefs.edit().putString("AndroidIDPrefix", Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID)).apply();
    }
    if (prefs.getString("GUIDPrefix", "").isEmpty()) {
        prefs.edit().putString("GUIDPrefix", UUID.randomUUID().toString()).apply();
    }
    if (prefs.getString("MacIDPrefix", "").isEmpty()) {
        String interfaceName = "wlan0";
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                if (!intf.getName().equalsIgnoreCase(interfaceName))
                    continue;
                byte[] mac = intf.getHardwareAddress();
                if (mac == null) {
                    prefs.edit().putString("MacIDPrefix", "unknown").apply();
                    break;
                }
                StringBuilder buf = new StringBuilder();
                for (byte b : mac) buf.append(String.format("%02X:", b));
                if (buf.length() > 0)
                    buf.deleteCharAt(buf.length() - 1);
                prefs.edit().putString("MacIDPrefix", buf.toString()).apply();
                break;
            }
        } catch (Exception e) {
            prefs.edit().putString("MacIDPrefix", "unknown").apply();
        }
    }
    Login = findPreference("Login");
    TestRun = findPreference("testNoti");
    Service = findPreference("service");
    ServiceToggle = findPreference("serviceToggle");
    Server = findPreference("server");
    Subscribe = findPreference("Subscribe");
    ServerInfo = findPreference("ServerInfo");
    ForWearOS = findPreference("forWear");
    FindPhone = findPreference("findPhone");
    pairDevice = findPreference("pairDevice");
    mBillingHelper = BillingHelper.initialize(mContext, new BillingHelper.BillingCallback() {

        @Override
        public void onPurchased(String productId) {
            switch(productId) {
                case BillingHelper.SubscribeID:
                    ToastHelper.show(mContext, "Thanks for purchase!", "OK", ToastHelper.LENGTH_SHORT);
                    ServiceToggle.setEnabled(!prefs.getString("UID", "").equals(""));
                    ServiceToggle.setSummary("");
                    Subscribe.setVisible(false);
                    new RegisterForPushNotificationsAsync().execute();
                    break;
                case BillingHelper.DonateID:
                    MaterialAlertDialogBuilder dialog = new MaterialAlertDialogBuilder(new ContextThemeWrapper(mContext, R.style.MaterialAlertDialog_Material3));
                    dialog.setTitle("Thank you for your donation!");
                    dialog.setMessage("This donation will be used to improve Noti Sender!");
                    dialog.setIcon(R.drawable.ic_fluent_gift_24_regular);
                    dialog.setCancelable(false);
                    dialog.setPositiveButton("Close", (dialogInterface, i) -> {
                    });
                    dialog.show();
                    break;
            }
        }

        @Override
        public void onUpdatePrice(Double priceValue) {
        }
    });
    if (mBillingHelper.isSubscribed()) {
        new RegisterForPushNotificationsAsync().execute();
    }
    boolean ifUIDBlank = prefs.getString("UID", "").equals("");
    if (!ifUIDBlank) {
        Login.setSummary("Logined as " + prefs.getString("Email", ""));
        Login.setTitle(R.string.Logout);
        if (prefs.getString("Email", "").equals("") && mAuth.getCurrentUser() != null)
            prefs.edit().putString("Email", mAuth.getCurrentUser().getEmail()).apply();
        if (prefs.getString("server", "Firebase Cloud Message").equals("Pushy")) {
            if (mBillingHelper.isSubscribed()) {
                Subscribe.setVisible(false);
                ServiceToggle.setEnabled(true);
            } else {
                Subscribe.setVisible(true);
                ServiceToggle.setEnabled(false);
                ServiceToggle.setSummary("Needs subscribe to use Pushy server");
            }
        } else {
            Subscribe.setVisible(false);
            ServiceToggle.setEnabled(true);
        }
    } else {
        ServiceToggle.setEnabled(false);
        if (prefs.getString("server", "Firebase Cloud Message").equals("Pushy") && !mBillingHelper.isSubscribed()) {
            Subscribe.setVisible(true);
            ServiceToggle.setSummary("Needs subscribe to use Pushy server");
        } else
            Subscribe.setVisible(false);
    }
    prefs.registerOnSharedPreferenceChangeListener((p, k) -> {
        if (k.equals("serviceToggle")) {
            ((SwitchPreference) ServiceToggle).setChecked(prefs.getBoolean("serviceToggle", false));
        }
    });
    Service.setSummary("Now : " + prefs.getString("service", "not selected"));
    Service.setOnPreferenceChangeListener((p, n) -> {
        p.setSummary("Now : " + n.toString());
        return true;
    });
    Server.setSummary("Now : " + prefs.getString("server", "Firebase Cloud Message"));
    Server.setOnPreferenceChangeListener((p, n) -> {
        p.setSummary("Now : " + n.toString());
        if (n.toString().equals("Pushy")) {
            if (mBillingHelper.isSubscribed())
                ServiceToggle.setEnabled(true);
            else {
                Subscribe.setVisible(true);
                ServiceToggle.setEnabled(false);
                ServiceToggle.setSummary("Needs subscribe to use Pushy server");
            }
        } else {
            ServiceToggle.setEnabled(!prefs.getString("UID", "").equals(""));
            ServiceToggle.setSummary("");
            Subscribe.setVisible(false);
        }
        return true;
    });
    try {
        mContext.getPackageManager().getPackageInfo("com.google.android.wearable.app", 0);
    } catch (PackageManager.NameNotFoundException e) {
        ForWearOS.setVisible(false);
    }
    migrationHistory();
}
Also used : Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) NonNull(androidx.annotation.NonNull) Date(java.util.Date) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder) Uri(android.net.Uri) GoogleSignInClient(com.google.android.gms.auth.api.signin.GoogleSignInClient) GoogleAuthProvider(com.google.firebase.auth.GoogleAuthProvider) GoogleSignIn(com.google.android.gms.auth.api.signin.GoogleSignIn) GoogleSignInResult(com.google.android.gms.auth.api.signin.GoogleSignInResult) View(android.view.View) GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) Log(android.util.Log) AppInfoActivity(com.noti.main.ui.AppInfoActivity) ConnectivityManager(android.net.ConnectivityManager) SettingsActivity.mBillingHelper(com.noti.main.SettingsActivity.mBillingHelper) SettingsActivity(com.noti.main.SettingsActivity) SwitchPreference(androidx.preference.SwitchPreference) NetworkInterface(java.net.NetworkInterface) NetworkInfo(android.net.NetworkInfo) UUID(java.util.UUID) ViewGroup(android.view.ViewGroup) List(java.util.List) Nullable(androidx.annotation.Nullable) ActivityResultContracts(androidx.activity.result.contract.ActivityResultContracts) ToastHelper(com.noti.main.ui.ToastHelper) MonetCompat(com.kieronquinn.monetcompat.core.MonetCompat) Context(android.content.Context) Intent(android.content.Intent) HistoryActivity(com.noti.main.ui.prefs.HistoryActivity) PairMainActivity(com.noti.main.ui.pair.PairMainActivity) PreferenceFragmentCompat(androidx.preference.PreferenceFragmentCompat) FragmentActivity(androidx.fragment.app.FragmentActivity) SuppressLint(android.annotation.SuppressLint) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) MODE_PRIVATE(android.content.Context.MODE_PRIVATE) Settings(android.provider.Settings) Notify(com.application.isradeleon.notify.Notify) Auth(com.google.android.gms.auth.api.Auth) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) FirebaseInstallations(com.google.firebase.installations.FirebaseInstallations) ActivityResultLauncher(androidx.activity.result.ActivityResultLauncher) LayoutInflater(android.view.LayoutInflater) BillingHelper(com.noti.main.utils.BillingHelper) FirebaseMessaging(com.google.firebase.messaging.FirebaseMessaging) Preference(androidx.preference.Preference) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) AuthCredential(com.google.firebase.auth.AuthCredential) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) OptionActivity(com.noti.main.ui.OptionActivity) R(com.noti.main.R) SharedPreferences(android.content.SharedPreferences) Pushy(me.pushy.sdk.Pushy) Activity(android.app.Activity) Collections(java.util.Collections) AsyncTask(com.noti.main.utils.AsyncTask) GoogleSignInOptions(com.google.android.gms.auth.api.signin.GoogleSignInOptions) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) SwitchPreference(androidx.preference.SwitchPreference) NetworkInterface(java.net.NetworkInterface) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) PackageManager(android.content.pm.PackageManager) GoogleSignInOptions(com.google.android.gms.auth.api.signin.GoogleSignInOptions) SuppressLint(android.annotation.SuppressLint)

Example 2 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot in project KDU-Attendance_and_Medical_Tracking_app by Sandul-Jayakody.

the class TrackMedical method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_track_medical);
    a = findViewById(R.id.ma);
    a.setMovementMethod(new ScrollingMovementMethod());
    b = findViewById(R.id.hod);
    // b.setMovementMethod(new ScrollingMovementMethod());
    c = findViewById(R.id.ar);
    // c.setMovementMethod(new ScrollingMovementMethod());
    d = findViewById(R.id.dean);
    // d.setMovementMethod(new ScrollingMovementMethod());
    fauth = FirebaseAuth.getInstance();
    fstore = FirebaseFirestore.getInstance();
    subject = fauth.getCurrentUser().getUid();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String currentuid = user.getUid();
    // DocumentReference documentReference=fstore.collection("medical").document(currentuid);
    // documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
    // @Override
    // public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
    // a.setText(value.getString("MA"));
    // b.setText(value.getString("HOD"));
    // c.setText(value.getString("AR"));
    // d.setText(value.getString("Dean"));
    notebookRef.document(currentuid).collection("Child Notes").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {

        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            String data = "";
            String data2 = "";
            for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                Note note = documentSnapshot.toObject(Note.class);
                note.setDocumentId(documentSnapshot.getId());
                String documentId = note.getDean();
                data += "\n" + documentId;
                // note.setDocumentId(documentSnapshot.getId());
                String documentId2 = note.getHOD();
                data2 += "\n" + documentId2;
            /*   for (String tag : note.getTags().keySet()) {
                                data += "\n-" + tag;
                            }
                            data += "\n\n";*/
            }
            a.setText(data);
            b.setText(data2);
        // textViewData.setText(data2);
        }
    });
}
Also used : QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) FirebaseUser(com.google.firebase.auth.FirebaseUser) ScrollingMovementMethod(android.text.method.ScrollingMovementMethod) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot)

Example 3 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot in project MDA_APP_RESTAURANTE by karlaogh99.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    // System.out.println("Usuario logeado: " + user.getEmail());
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    setSupportActionBar(binding.appBarMain.toolbar);
    binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
        }
    });
    DrawerLayout drawer = binding.drawerLayout;
    NavigationView navigationView = binding.navView;
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow).setOpenableLayout(drawer).build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);
    // Esto es poner en el nav el nombre del usuario
    View headerView = navigationView.getHeaderView(0);
    TextView navUsername = (TextView) headerView.findViewById(R.id.usernameTextView);
    navUsername.setText(user.getEmail());
    // Insertar menu de BD
    recycler_menu = (RecyclerView) findViewById(R.id.menu);
    recycler_menu.setHasFixedSize(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recycler_menu.setLayoutManager(layoutManager);
    System.out.print("f");
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    // Read from the database
    listCategory = new ArrayList<>();
    db.collection("Category").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Category cat = new Category("", "");
                    cat.setName((String) document.get("Nombre"));
                    cat.setImage((String) document.get("Image"));
                    listCategory.add(cat);
                }
                AdapterCategory adapter = new AdapterCategory(listCategory, new AdapterCategory.OnItemClickListener() {

                    @Override
                    public void onItemClick(Category cat) {
                        moveToDescription(cat);
                    }
                });
                recycler_menu.setAdapter(adapter);
            }
        }
    });
}
Also used : NavigationView(com.google.android.material.navigation.NavigationView) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) Category(com.example.app_restaurante.Model.Category) AdapterCategory(com.example.app_restaurante.Adapter.AdapterCategory) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) NavController(androidx.navigation.NavController) AdapterCategory(com.example.app_restaurante.Adapter.AdapterCategory) FirebaseUser(com.google.firebase.auth.FirebaseUser) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) NavigationView(com.google.android.material.navigation.NavigationView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) TextView(android.widget.TextView) DrawerLayout(androidx.drawerlayout.widget.DrawerLayout) AppBarConfiguration(androidx.navigation.ui.AppBarConfiguration)

Example 4 with QueryDocumentSnapshot

use of com.google.firebase.firestore.QueryDocumentSnapshot 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 5 with QueryDocumentSnapshot

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

the class GroupListsFragmentModel method removeItem.

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

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

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

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

Aggregations

QueryDocumentSnapshot (com.google.firebase.firestore.QueryDocumentSnapshot)73 QuerySnapshot (com.google.firebase.firestore.QuerySnapshot)33 ArrayList (java.util.ArrayList)30 View (android.view.View)22 NonNull (androidx.annotation.NonNull)19 Task (com.google.android.gms.tasks.Task)18 OnCompleteListener (com.google.android.gms.tasks.OnCompleteListener)17 Intent (android.content.Intent)16 CollectionReference (com.google.firebase.firestore.CollectionReference)13 AdapterView (android.widget.AdapterView)12 FirebaseFirestore (com.google.firebase.firestore.FirebaseFirestore)12 TextView (android.widget.TextView)10 Bundle (android.os.Bundle)9 ListView (android.widget.ListView)9 DocumentSnapshot (com.google.firebase.firestore.DocumentSnapshot)9 FirebaseFirestoreException (com.google.firebase.firestore.FirebaseFirestoreException)8 UsersDataModel (com.example.first_responder_app.dataModels.UsersDataModel)7 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)6 FirebaseUser (com.google.firebase.auth.FirebaseUser)6 DocumentReference (com.google.firebase.firestore.DocumentReference)6