Ok, here's my full MainActivity.java code, how and where should I put what to make Google Sign in work? For experimenting, let's use "confirmation.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});" as a sign in button.
Here's the code:
package com.HidiStudios.BeST;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.HidiStudios.BeST.R;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.auth.User;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class MainActivity extends BaseDrawerActivity {
//variables
private InterstitialAd mInterstitialAd;
private RewardedAd mRewardedAd;
private static FirebaseAuth mAuth;
private static FirebaseFirestore db = FirebaseFirestore.getInstance();
static CollectionReference usersRef = db.collection("users");
public static int amount = 0;
boolean state = false;
static boolean changedSinceSynced = true;
private TextView mTextView;
String text;
//stats
private static int bannerToggleCount = 0;
private static int interstitialWatchedCount = 0;
private static int interstitialClickedCount = 0;
private static int rewardedWatchedCount = 0;
private static int rewardedClickedCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// menuRelated
initializeDrawer();
/*
//Initialize AdMob
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(@NonNull InitializationStatus initializationStatus) {
}
});
*/
//RewardedAdRelated
loadRewardedAds();
Button rewardedButton = findViewById(R.id.RewardedbtnAds);
rewardedButton.setOnClickListener(view -> {
showRewardedAds();
});
//InterstitialAdRelated
loadInterstitialAd();
Button interstitialButton = findViewById(R.id.IntbtnAds);
interstitialButton.setOnClickListener(view -> {
showInterstitialAd();
});
//BannerAdRelated
Button bannerButton = findViewById(R.id.BannerbtnAds);
bannerButton.setOnClickListener(view -> {
bannerAd();
});
//ResetButtonRelated
resetButton();
//FirebaseAuth
mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser(); //if user is signed in returns UID, else null
updateUI(currentUser); //if userID is null, generated.
//CoinRelated
loadCoins();
//stats
loadStats();
setStats();
}
@Override
protected void onStop() {
super.onStop();
Log.d("TagDB", "onStopped");
if (changedSinceSynced) {
saveToDB(false, new DbOperationCompleteListener() {
@Override
public void onDbOperationComplete() {
changedSinceSynced = false;
Log.d("TagDB", "onStopped, synced to DB, changedSinceSynced set to false");
}
});
}
}
//bannerAds
private void bannerAd() {
AdView mAdView = findViewById(R.id.adView);
AdRequest BannerAdRequest = new AdRequest.Builder().build();
if (!state) {
mAdView.loadAd(BannerAdRequest);
mAdView.setVisibility(View.VISIBLE);
Log.d("TagDB", "Banner Toggled!");
amount += getResources().getInteger(R.integer.onBannerToggle);
updateCoins();
changedSinceSynced = true;
bannerToggleCount++;
updateStats();
state = true;
} else {
mAdView.setVisibility(View.GONE);
state = false;
}
}
//interstitialAds
private void loadInterstitialAd() {
AdRequest interstitialAdRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,getString(R.string.INTERSTITIAL_AD_UNIT_ID), interstitialAdRequest, new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
super.onAdLoaded(interstitialAd);
mInterstitialAd = interstitialAd;
interstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
@Override
public void onAdClicked() {
super.onAdClicked();
Log.d("TagDB", "Interstitial clicked!");
amount += getResources().getInteger(R.integer.onInterstitialClick);
updateCoins();
changedSinceSynced = true;
interstitialClickedCount++;
updateStats();
}
@Override
public void onAdDismissedFullScreenContent() {
mInterstitialAd = null;
loadInterstitialAd();
}
@Override
public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
mInterstitialAd = null;
}
});
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
//error message is managed in showInterstitialAds() function
}
});
}
private void showInterstitialAd() {
if (mInterstitialAd!=null) {
mInterstitialAd.show(MainActivity.this);
Log.d("TagDB", "Interstitial watched!");
amount += getResources().getInteger(R.integer.onInterstitialToggle);
updateCoins();
changedSinceSynced = true;
interstitialWatchedCount++;
updateStats();
} else {
Log.d("TagDB", "The interstitial ad is not ready yet. Try again!");
loadInterstitialAd(); // Try to load again if it wasn’t ready when the button was clicked
}
}
//rewardedAds
private void loadRewardedAds() {
AdRequest RewardedAdRequest = new AdRequest.Builder().build();
RewardedAd.load(this, getString(R.string.REWARDED_AD_UNIT_ID), RewardedAdRequest, new RewardedAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
super.onAdLoaded(rewardedAd);
mRewardedAd = rewardedAd;
rewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdClicked() {
super.onAdClicked();
Log.d("TagDB", "Rewarded clicked!");
amount += getResources().getInteger(R.integer.onRewardedClicked);
updateCoins();
changedSinceSynced = true;
rewardedClickedCount++;
updateStats();
}
@Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
loadRewardedAds();
}
@Override
public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
mRewardedAd = null;
}
});
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
mRewardedAd = null;
//error message is managed in showRewardedAds() function
}
});
}
private void showRewardedAds() {
if (mRewardedAd!=null) {
mRewardedAd.show(MainActivity.this, new OnUserEarnedRewardListener() {
@Override
public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
Log.d("TagDB", "Reward earned!");
amount += getResources().getInteger(R.integer.onRewardedToggle);
updateCoins();
changedSinceSynced = true;
rewardedWatchedCount++;
updateStats();
}
});
} else {
Toast.makeText(MainActivity.this,"Rewarded ad is not ready yet. Try again!", Toast.LENGTH_SHORT).show();
}
}
//coins
private void loadCoins(){
loadCoinAmount(); //this is local save
readFromDB();
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() {
mTextView=findViewById(R.id.Coins);
text = getResources().getString(R.string.coins_message, amount);
mTextView.setText(text);
}
private void updateCoins(){
saveCoinAmount();
setCoins();
}
//reset
private void resetButton(){
Button resetButton = findViewById(R.id.resetButton);
resetButton.setOnClickListener(view -> {
confirmResetCoins();
});
}
private void confirmResetCoins(){
AlertDialog.Builder confirmation = new AlertDialog.Builder(this);
confirmation.setTitle("Are you sure?");
confirmation.setMessage("Your stats and coin balance will be reset to 0.");
confirmation.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
resetCoinsAndStats();
}
});
confirmation.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
confirmation.create().show();
}
private void resetCoinsAndStats() {
amount = 0;
updateCoins();
bannerToggleCount = 0;
interstitialWatchedCount = 0;
interstitialClickedCount = 0;
rewardedWatchedCount = 0;
rewardedClickedCount = 0;
updateStats();
changedSinceSynced = true;
Toast.makeText(MainActivity.this, "Coins and stats have been reset!", Toast.LENGTH_SHORT).show();
}
//Stats
private void setStats(){
mTextView=findViewById(R.id.stats);
text = getResources().getString(R.string.stats_message, bannerToggleCount, interstitialWatchedCount, interstitialClickedCount, rewardedWatchedCount, rewardedClickedCount);
mTextView.setText(text);
}
private void loadStats(){
SharedPreferences sharedPreferences = getSharedPreferences("UserPreferences", MODE_PRIVATE);
bannerToggleCount = sharedPreferences.getInt("bannerToggleCount", 0);
interstitialWatchedCount = sharedPreferences.getInt("interstitialWatchedCount", 0);
interstitialClickedCount = sharedPreferences.getInt("interstitialClickedCount", 0);
rewardedWatchedCount = sharedPreferences.getInt("rewardedWatchedCount", 0);
rewardedClickedCount = sharedPreferences.getInt("rewardedClickedCount", 0);
}
private void saveStats(){
SharedPreferences sharedPreferences = getSharedPreferences("UserPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("bannerToggleCount", bannerToggleCount);
editor.putInt("interstitialWatchedCount", interstitialWatchedCount);
editor.putInt("interstitialClickedCount", interstitialClickedCount);
editor.putInt("rewardedWatchedCount", rewardedWatchedCount);
editor.putInt("rewardedClickedCount", rewardedClickedCount);
editor.apply();
}
private void updateStats(){
saveStats();
setStats();
}
//FirebaseAuth
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();
updateUI(user);
} else {
updateUI(null);
}
}
});
}
}
//Firebase DB
public static void saveToDB(boolean Create, @Nullable DbOperationCompleteListener listener) {
Map<String, Object> userdb = new HashMap<>();
userdb.put("score", amount);
OnSuccessListener<Void> successListener = new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unused) {
Log.d("TagDB", "Successfully saved to DB");
if (listener != null) {
listener.onDbOperationComplete();
}
}
};
OnFailureListener failureListener = new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w("TagDB","Error adding document", e);
}
};
if (Create) {
usersRef.document(Objects.requireNonNull(mAuth.getUid())).set(userdb) //update-set
.addOnSuccessListener(successListener)
.addOnFailureListener(failureListener);
} else {
usersRef.document(Objects.requireNonNull(mAuth.getUid())).update(userdb) //update-set
.addOnSuccessListener(successListener)
.addOnFailureListener(failureListener);
}
}
private void readFromDB() {
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.");
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) {
amount = Math.toIntExact(score);
updateCoins();
Toast.makeText(MainActivity.this, "Local coin amount overridden by Firebase score.", Toast.LENGTH_SHORT).show();
}
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);
}
});
}
public interface DbOperationCompleteListener {
void onDbOperationComplete();
}
}