I have the following simple leaderboard app: public class LeaderboardActivity extends…
- User
I have the following simple leaderboard app:
public class LeaderboardActivity extends AppCompatActivity {
DrawerLayout drawerLayout; NavigationView navigationView; ActionBarDrawerToggle drawerToggle; private FirebaseAuth mAuth; private FirebaseFirestore db = FirebaseFirestore.getInstance(); CollectionReference usersRef = db.collection("users"); Query leaderboardQuery = usersRef.orderBy("score", Query.Direction.DESCENDING).limit(10); Query leaderboardLastest = usersRef.orderBy("score", Query.Direction.ASCENDING).limit(1); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leaderboard); mAuth = FirebaseAuth.getInstance(); menuConfig(); leaderboard(); } //menu public void menuConfig() { drawerLayout = findViewById(R.id.drawer_layout); navigationView = findViewById(R.id.nav_view); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close); drawerLayout.addDrawerListener(drawerToggle); drawerToggle.syncState(); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); navigationView.bringToFront(); if (id == R.id.home) { Toast.makeText(LeaderboardActivity.this, "Home pressed", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(LeaderboardActivity.this, MainActivity.class); startActivity(intent); } else if (id == R.id.leaderboard) { Toast.makeText(LeaderboardActivity.this, "Contact pressed", Toast.LENGTH_SHORT).show(); } else if (id == R.id.gallery) { Toast.makeText(LeaderboardActivity.this, "Gallery pressed", Toast.LENGTH_SHORT).show(); } else if (id == R.id.about) { Toast.makeText(LeaderboardActivity.this, "About pressed", Toast.LENGTH_SHORT).show(); } else if (id == R.id.login) { Toast.makeText(LeaderboardActivity.this, "Login pressed", Toast.LENGTH_SHORT).show(); } else if (id == R.id.share) { Toast.makeText(LeaderboardActivity.this, "Share pressed", Toast.LENGTH_SHORT).show(); } else if (id == R.id.rate_us) { Toast.makeText(LeaderboardActivity.this, "Rate us pressed", Toast.LENGTH_SHORT).show(); } // Close drawer after item is selected. drawerLayout.closeDrawer(GravityCompat.START); return false; // return true if you want to indicate the item was selected. } }); AdView mAdView = findViewById(R.id.adView); AdRequest BannerAdRequest = new AdRequest.Builder().build(); mAdView.loadAd(BannerAdRequest); mAdView.setVisibility(View.VISIBLE); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) { return true; } // handle other menu items here if necessary return super.onOptionsItemSelected(item); } //FirebaseDB private void leaderboard() { leaderboardQuery.get().addOnCompleteListener(task -> { if (task.isSuccessful()) { LinearLayout leaderboardLayout = findViewById(R.id.leaderboardLayout); // Clear the layout if you rerun the query to prevent duplicating views leaderboardLayout.removeAllViews(); boolean currentUserIsInTop = false; // Flag to check if current user is in top leaderboard String currentUserId = mAuth.getUid(); // Get current user id int rank = 1; // Rank counter // Iterate through the leaderboard results for (QueryDocumentSnapshot document : task.getResult()) { String documentUserId = document.getId(); createLeaderboardEntry(document, leaderboardLayout, rank, currentUserId.equals(documentUserId)); rank++; // Increment rank number if (currentUserId.equals(documentUserId)) { currentUserIsInTop = true; // Current user is in the top leaderboard } } // Add the current user’s rank if they’re not in the top leaderboard if (!currentUserIsInTop && currentUserId != null) { usersRef.document(currentUserId).get().addOnSuccessListener(document -> { if (document.exists()) { placeholder(leaderboardLayout); createLeaderboardEntry(document, leaderboardLayout, -1, true); // Passing -1 as rank to indicate it’s not a part of the top } else { Log.d("Leaderboard", "Current user document does not exist."); // Handle case where current user does not have a score } }).addOnFailureListener(e -> Log.w("Leaderboard", "Error getting current user document", e)); } } else { Log.w("TagDB", "Error getting documents.", task.getException()); } }); } private void placeholder(LinearLayout leaderboardLayout) { TextView scoreView = new TextView(this); scoreView.setText("..."); scoreView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); scoreView.setGravity(Gravity.CENTER_HORIZONTAL); leaderboardLayout.addView(scoreView); } private void createLeaderboardEntry(DocumentSnapshot document, LinearLayout leaderboardLayout, int rank, boolean highlight) { TextView scoreView = new TextView(this); String nickname = document.getString("nickname"); String score = document.getLong("score").toString(); String text = rank > 0 ? rank + ". " : ""; // Add rank number if provided text += nickname != null ? nickname + " " + score : "Anonymous " + score; scoreView.setText(text); scoreView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); scoreView.setGravity(Gravity.CENTER_HORIZONTAL); if (highlight) { // Highlight the current user; for example, by changing the text color scoreView.setTextColor(ContextCompat.getColor(this, R.color.highlight_color)); // Make sure to define highlight_color in your colors.xml } leaderboardLayout.addView(scoreView); } - Assistant
- User
We have to fine-tune this! My first idea is: Is it a good idea to merge the queries to reduce the reads? Firebase allows a maximum of 50K reads/day. And I still have to determine the rank of the LowestScoreUser. Is it possible to determine this without reading all the users? Can't we just query the number count of documents in Firebase (as it would represent the number of users, and he rank of the last user.)
- Assistant
- User
- Assistant
- User
how many reads will be counted toward the daily limit with this function?
- Assistant
With the updated function that fetches all user data in a single query, the number of reads that will be counted toward your daily limit will be equal to the number of documents (users) that are returned by the query. Each document read from the database counts as one read.
Therefore, if you have, let's say, 100 users total in the
userscollection that your query returns, then executing this function once will result in 100 document reads being counted toward your daily limit. If you have 1,000 users, executing the function once will result in 1,000 document reads, and so on.Because the reads can add up quickly with this approach—especially as your user base grows—it's essential to consider both the frequency with which this function is called and the growth of your user collection. If you expect to have a large number of users or if this function will be called frequently (e.g., every time a user opens the leaderboard), this could consume your quota rapidly.
For experimental or development purposes with a small number of users, this approach may be acceptable. However, for production environments expecting higher volumes of users and reads, you'd typically want to implement a more scalable solution that minimizes the number of reads and optimizes usage of the database. This could involve pagination, caching data locally, or using a different architectural approach such as distributing data across separate collections/documents to avoid querying all user data in one go.
- User
Your private void leaderboard() { // Query to get all users ordered by score in descending order Query allUsersQuery = usersRef.orderBy(“score”, Query.Direction.DESCENDING);
allUsersQuery.get().addOnCompleteListener(task -> { if (task.isSuccessful()) { LinearLayout leaderboardLayout = findViewById(R.id.leaderboardLayout); leaderboardLayout.removeAllViews(); // Clear the layout String currentUserId = mAuth.getUid(); // Get current user id int rank = 1; // Start counting ranks from the top player boolean currentUserDisplayed = false; QueryDocumentSnapshot currentUserDoc = null; QueryDocumentSnapshot lastUserDoc = null; // Iterate through all documents to populate leaderboard and find current and last user for (QueryDocumentSnapshot document : task.getResult()) { // Display top 10 users if (rank <= 10) { createLeaderboardEntry(document, leaderboardLayout, rank, currentUserId.equals(document.getId())); } // Check if the current user is in the top 10 if (currentUserId.equals(document.getId())) { currentUserDisplayed = true; currentUserDoc = document; } // Keep track of the last user to display later lastUserDoc = document; rank++; } if (!currentUserDisplayed && currentUserDoc != null) { // If the current user is not in the top 10, display their rank placeholder(leaderboardLayout); createLeaderboardEntry(currentUserDoc, leaderboardLayout, rank - 1, true); // rank - 1 will be the rank of the current user } if (lastUserDoc != null) { // Display the last user with the worst score createLeaderboardEntry(lastUserDoc, leaderboardLayout, rank - 1, false); // rank - 1 will be the rank of the last user } } else { Log.w(“TagDB”, “Error getting documents.”, task.getException()); } }); - Assistant
- User
Your updated code does not run. At this line: createLeaderboardEntry(documentSnapshot, leaderboardLayout, currentUserRank, true); Variable used in lambda expression should be final or effectively final
- Assistant