In a BaseDrawerActivity I have inside an onNavigationItemSelected if (!(this instanceof…
- User
In a BaseDrawerActivity I have inside an onNavigationItemSelected if (!(this instanceof BaseDrawerActivity) && id == R.id.home) { Toast.makeText(BaseDrawerActivity.this, "Home pressed", Toast.LENGTH_SHORT).show(); finish(); } else if (!(this instanceof LeaderboardActivity) && id == R.id.leaderboard) { Toast.makeText(BaseDrawerActivity.this, "Leaderboard pressed", Toast.LENGTH_SHORT).show();
if (MainActivity.changedSinceSynced) { MainActivity.changedSinceSynced = false; //sync is done here, not using onStop MainActivity.saveToDB(false, new MainActivity.DbOperationCompleteListener() { @Override public void onDbOperationComplete() { openLeaderboardActivity(); } }); } else { openLeaderboardActivity(); }When I go to LeaderboardActivity from MainActivity, then press the Home button inside LeaderboardActivity, it does nothing! Why this could be? I can provide any further information to you if you need
- Assistant
- User
I want to make a unitily class for Firebase Authentication. I'm currently here: package com.HidiStudios.BeST.Utilities;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser;
public class FirebaseAuthUtil { public static FirebaseAuth mAuth;
public static void initializeFirebase(){ mAuth = FirebaseAuth.getInstance(); FirebaseUser currentUser = mAuth.getCurrentUser(); //if user is signed in returns UID, else null updateUI(currentUser); //if userID is null, generated. } private void updateUI(FirebaseUser user) { if (user==null) { //if there's no user signed in mAuth.signInAnonymously().addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser user = mAuth.getCurrentUser(); saveToDB(true,null); } else { updateUI(null); } } }); } } - Assistant
- Assistant
It seems like your message didn't come through. If you have any further questions or any specific aspects you would like to discuss or need additional information about, please let me know! I'm here to help.
- User
- Assistant
- User
Now, I want to add readFromDB to this utility class. How should I do it?
Here's the original from MainActivity:
private void readFromDB(boolean isSyncingWithProvider) { String userId = mAuth.getUid(); // Get the current authenticated user’s ID if (userId == null) { // Handle the case where there is no authenticated user Log.w("TagDB", "User ID is null, can’t fetch data."); //updateUI(null); return; } DocumentReference docRef = usersRef.document(userId); docRef.get() .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists()) { // Retrieves the score from the document Long score = documentSnapshot.getLong("score"); if (Math.toIntExact(score) != amount && !isSyncingWithProvider) { amount = Math.toIntExact(score); updateCoins(); Toast.makeText(MainActivity.this, "Local coin amount overridden by Firebase score.", Toast.LENGTH_SHORT).show(); } else if (isSyncingWithProvider){ amount += Math.toIntExact(score); updateCoins(); Toast.makeText(MainActivity.this, "Coin amounts have been merged", Toast.LENGTH_SHORT).show(); saveToDB(false, null); } changedSinceSynced = false; //false when sync, because local and cloud values match Log.d("TagDB", "User Firebase score: " + score); }else { Log.d("TagDB", "No such document!"); saveToDB(true, null); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w("TagDB", "Error fetching document", e); } }); } - Assistant
- User
Ok, I made this into FirebaseDatabaseUtil (did not used your previous recommendations): public static void readFromDB(boolean isSyncingWithProvider) { String userId = FirebaseAuthUtil.mAuth.getUid(); // Get the current authenticated user’s ID if (userId == null) { // Handle the case where there is no authenticated user Log.w("TagDB", "User ID is null, can’t fetch data."); //updateUI(null); return; }
- Assistant
The error you're encountering occurs because you're trying to reference
MainActivity.thisfrom a static context, which is not allowed. Thethiskeyword in Java refers to the current instance of the class. SinceMainActivity.thisimplies referencing an instance, and utility classes are meant to be used without instantiating objects, you should find an alternative way to show theToast.To resolve this issue, you can modify the
readFromDBmethod to accept aContextas a parameter, and use thatContextto show theToast. Here's how you can adjust the method accordingly: - User
Thanks, it solved my problem.
Now, I have another problem.
In MainActivity, I have these functions related to coins:
private void loadCoins(){ loadCoinAmount(); //this is local save FirebaseDatabaseUtil.readFromDB(MainActivity.this, false); setCoins(); } private void loadCoinAmount() { SharedPreferences sharedPreferences = getSharedPreferences("UserPreferences", MODE_PRIVATE); amount = sharedPreferences.getInt("coinsAmount", 0); } private void saveCoinAmount() { SharedPreferences sharedPreferences = getSharedPreferences("UserPreferences", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("coinsAmount", amount); editor.apply(); } private void setCoins() { TextView mTextView = findViewById(R.id.Coins); String text = getResources().getString(R.string.coins_message, amount); mTextView.setText(text); } private void updateCoins(){ saveCoinAmount(); setCoins(); }readFromDB in FirebaseDatabaseUtil has this problem: 'updateCoins()' has private access in 'com.HidiStudios.BeST.MainActivity'
How can I solve this?
- Assistant
- User
Isn't it possible to solve this without these listeners? So for example by making the Coin related functions in MainActivity public or something like this?
- Assistant
Yes, you can solve this by making the coin-related functions
publicorpackage-private(with no access modifier). However, this approach can result in a less modular and less encapsulated design. If you're looking for a quick fix and are not too concerned about design principles at this moment, you can modify the access level of the method to or package-private. Here's how you would do it: - User
Non-static method 'updateCoins()' cannot be referenced from a static context
- Assistant
- User
- Assistant