Android Firebase logout app crashes AFTER I logout - java

I have my MainActivity in which I handle the logout. Problem is after I log out, the app crashes in verifyUserExistance() at line:
String userID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
Which gives :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.firebase.quickstart.auth, PID: 8459
java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at com.google.firebase.quickstart.auth.social.Main_Chat_Activity$3.lambda$null$1$Main_Chat_Activity$3(Main_Chat_Activity.java:372)
at com.google.firebase.quickstart.auth.social.-$$Lambda$Main_Chat_Activity$3$87CwjFnoJAhucBGNsLP_MxK833o.onComplete(Unknown Source:2)
at com.google.android.gms.tasks.zzj.run(com.google.android.gms:play-services-tasks##17.2.0:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Below is the code I use:
#Override
protected void onStart() {
super.onStart();
usersRef.child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.hasChild("name"))
{
sendUserToLoginActivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
if (mAuth == null || currentUser == null || mAuth.getCurrentUser().getUid() == null ){
finish();
sendUserToLoginActivity();
}
else {
if(mAuth.getCurrentUser().getProviderId() == "google.com"){
user.setmGoogleSignInClient(mGoogleSignInClient);
}
user.setMauth(mAuth);
if (loginOutFlag>-1)
verifyUserExistence();
}
checkLocation();
if (isNew!=null)
{
if (isNew.equals("true")){
sendUserToSettingsActivity();
}
}
}
The method verifyUserExistance is;
private void verifyUserExistence() {
if (!verified && loginOutFlag > -1) {
String currentUserID = mAuth.getCurrentUser().getUid();
try {
rootRef.child("Users").child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("name").exists()) {
loginOutFlag = 1;
Toast.makeText(Main_Chat_Activity.this, "Welcome" + dataSnapshot.child("name").getValue().toString(), Toast.LENGTH_SHORT).show();
Log.w("Reportname:", dataSnapshot.child("name").getValue().toString());
Calendar cal = Calendar.getInstance();
final String timeNDate = cal.getTime().toString();
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("connection", timeNDate);
rootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(task ->
{
if (task.isSuccessful()) {
Toast.makeText(Main_Chat_Activity.this, "Success ", Toast.LENGTH_SHORT).show();
verified = true;
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(task13 -> {
String userID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
if (!task13.isSuccessful()) {
Log.w("FCM", "Fetching FCM registration token failed", task13.getException());
return;
}
// Get new FCM registration token
String deviceToken = task13.getResult();
// Log and toast
Log.d("FCM", deviceToken);
Toast.makeText(Main_Chat_Activity.this, deviceToken, Toast.LENGTH_SHORT).show();
final int[] no = {0};
DatabaseReference tokens = usersRef.child(userID).child("device_tokens");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
no[0] = (int) snapshot.getChildrenCount();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
tokens.addListenerForSingleValueEvent(valueEventListener);
String devName = "device" + no[0];
String token = deviceToken.split(":")[1];
usersRef.child(userID).child("device_tokens").child(devName)
.setValue(token)
.addOnCompleteListener(task12 -> {
if (task12.isSuccessful()) {
Toast.makeText(Main_Chat_Activity.this, "Token updated succesfully.", Toast.LENGTH_LONG).show();
}
});
});
} else {
String errorMSG = Objects.requireNonNull(task.getException()).toString();
//user.setMauth(null);
Toast.makeText(Main_Chat_Activity.this, "Error : " + errorMSG, Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
catch (Exception e)
{
Log.d("EXCEPTION", e.toString());
}
}
}
and this is how I handle the logout;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_option) {
updateUserStatus("offline");
String currentUserID = mAuth.getCurrentUser().getUid();
rootRef.child("Users").child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("name").exists()) {
Calendar cal = Calendar.getInstance();
final String timeNDate = cal.getTime().toString();
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("connection", timeNDate);
rootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(task ->
{
if (task.isSuccessful()) {
loginOutFlag = -1;
} else {
String errorMSG = Objects.requireNonNull(task.getException()).toString();
Toast.makeText(Main_Chat_Activity.this, "This error : " + errorMSG, Toast.LENGTH_SHORT).show();
}
mGoogleSignInClient.signOut().addOnCompleteListener(task1 -> {
if (task1.isSuccessful()){
mAuth.signOut(); // very important if you are using firebase.
LoginManager.getInstance().logOut();
sendUserToLoginActivity();
finish();
}
});
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
sendUserToLoginActivity();
}
if (item.getItemId() == R.id.main_settings_option) {
sendUserToSettingsActivity();
}
if (item.getItemId() == R.id.main_find_friends_option) {
sendUserToFindFriendsActivity();
}
return true;
}

Problem is after I log out, the app crashes:
at line String userID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid()
When you log out, the mAuth objct becomes null. So calling getCurrentUser() on a such an object, instead of returning a FirebaseUser object, it will return null, hence the presence of the NullPointerExcepetion.
Returns the currently signed-in FirebaseUser or null if there is none.
So the solution for your problem is to wait for the asynchronous operation to finish, and right after that to sign out, otherwise, you'll always get NullPointerExcepetion.
Here is an example of you can wait until the data is finished loading from the Realtime Database:
How to return DataSnapshot value as a result of a method?

Related

Clicking on a button ends up making multiple instances of the Activity it navigates to

So I'm making an app in android studio, its like a fintech app. In one activity/page(SendMoney.java), you put in a number amount and tap the "Send Money" button, from here it goes to the page where you choose who you're sending this money to(SendReceiver.java). You select your desired recepient and tap on a second "Send Money" button, this then takes you to a success page that lists the amount sent and the username of the recepient(SendReceiverSuccessPage).
On the SendMoney page I need to get the amount inputted and pass that data to the SendReceiverSuccessPage, I've done this by using Intent and I've added this code to when the Send Money button is clicked, but in doing this what happens is that it for some reason creates multiple instances of the SendReceiver page it navigates to.
So on the SendReceiver page when I'm done and I hit the second "Send Money" button it just opens a new instance of SendReceiver whiles the SendReceiverSuccessPage is stuck in the background for some reason.
I need it to be one single smooth navigation flow where it goes from SendMoney to SendReceiver to SendReceiverSuccessPage without SendReceiver popping up multiple times and stacking ontop of the success page, all whiles being able to actively pass and retrieve the "AmountSent" data.
SendMoney.java
public class SendMoney extends AppCompatActivity {
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
Context context;
Double userAmountDouble;
MaterialButton sendMoneyButton;
ImageView backspace, back;
TextView amount, currentBalanceText, currency, one, two, three, four, five, six, seven, eight, nine, zero, dot;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_money);
this.context = getApplicationContext();
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
// Hooks
back = findViewById(R.id.back);
amount = findViewById(R.id.amount);
currency = findViewById(R.id.currency);
currentBalanceText = findViewById(R.id.current_balance);
one = findViewById(R.id.one);
two = findViewById(R.id.two);
three = findViewById(R.id.three);
four = findViewById(R.id.four);
five = findViewById(R.id.five);
six = findViewById(R.id.six);
seven = findViewById(R.id.seven);
eight = findViewById(R.id.eight);
nine = findViewById(R.id.nine);
zero = findViewById(R.id.zero);
dot = findViewById(R.id.dot);
backspace = findViewById(R.id.backspace);
sendMoneyButton = findViewById(R.id.send_money_button);
sendMoneyButton.setText("Send GH₵0");
// Display send amount on button, in realtime
amount.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//sendMoneyButton.setText("Send GH₵0");
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// This method is called whenever the text in the EditText changes
String userInputAmount = amount.getText().toString();
sendMoneyButton.setText("Send GH₵" + userInputAmount);
}
#Override
public void afterTextChanged(Editable editable) {
//
}
});
// Connect to the database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
// Get and show available balance
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
assert currentBalance != null;
currentBalanceText.setText("GH₵"+ currentBalance + " AVAILABLE");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
// Send Money Button
sendMoneyButton.setOnClickListener(v -> {
String userInputAmount = amount.getText().toString();
if (userInputAmount.equals("") || userInputAmount.equals("0")) {
Toast.makeText(getApplicationContext(),"Please enter an amount",Toast.LENGTH_SHORT).show();
} else {
userAmountDouble = Double.parseDouble(userInputAmount);
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
assert currentBalance != null;
double currentBalanceDouble = Double.parseDouble(currentBalance);
if (userAmountDouble > currentBalanceDouble) {
Toast.makeText(getApplicationContext(),"Insufficient Balance",Toast.LENGTH_SHORT).show();
} else {
// Create an Intent and include the value of userInputAmount
Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Start the SendReceiver activity
finish();
startActivity(sendReceiverIntent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
}
});
// Click Listeners
back.setOnClickListener(v -> finish());
zero.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("0");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "0");
}
});
one.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("1");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "1");
}
});
two.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("2");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "2");
}
});
three.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("3");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "3");
}
});
four.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("4");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "4");
}
});
five.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("5");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "5");
}
});
six.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("6");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "6");
}
});
seven.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("7");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "7");
}
});
eight.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("8");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "8");
}
});
nine.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("9");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "9");
}
});
dot.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText(".");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + ".");
}
});
backspace.setOnClickListener(v -> {
if (amount.getText().toString().equals("") | amount.getText().toString().equals("0")) {
amount.setText("0");
} else {
amount.setText(amount.getText().toString().substring(0, amount.getText().length() - 1));
}
});
}
}
SendReceiver.java
public class SendReceiver extends AppCompatActivity{
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
Context context;
ArrayList<SearchedUsersModel> searchedUsersModel;
RecyclerView searchedUsersRecycler;
SearchView svSearch;
MaterialButton finalSendBtn;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sendreceiver);
// Retrieve the value of userInputAmount from the Intent
Intent intent = getIntent();
String userInputAmount = intent.getStringExtra("USER_INPUT_AMOUNT");
this.context = getApplicationContext();
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
// Hooks
searchedUsersRecycler = findViewById(R.id.recyclerUsers);
svSearch = findViewById(R.id.svSearch);
finalSendBtn = findViewById(R.id.final_send_button);
// Set the hint for the search bar
svSearch.setQueryHint("Enter name or email of user");
// On click listener for when you hit the Send button
finalSendBtn.setOnClickListener(v -> {
DatabaseReference databaseReference = database.getReference("Users");
assert firebaseUser != null;
databaseReference.child(firebaseUser.getUid()).child("transactions").child("sendTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(userInputAmount);
// Get a reference to the "transactions" collection
DatabaseReference transactionsRef = database.getReference("Transactions");
// Get a reference to the "sendTransactions" sub-collection
DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");
// Generate a unique ID for the new transaction
String transactionUID = sendTransactionsRef.push().getKey();
// Add the new transaction to the "sendTransactions" sub-collection
assert transactionUID != null;
sendTransactionsRef.child(transactionUID).child("amount").setValue(userInputAmount);
// This deducts the same amount from the current users main balance
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
DecimalFormat df = new DecimalFormat("0.00");
assert currentBalance != null;
// The current balance minus the amount withdrawn
double amountToSubtract = Double.parseDouble(currentBalance) - Double.parseDouble(userInputAmount);
String newBalance = Double.toString(Double.parseDouble(df.format(amountToSubtract)));
// Write the new balance to the database
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").setValue(newBalance).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
System.out.println("Error updating user main balance: " + task.getException());
} else {
// Print an error message
System.out.println("Error updating user main balance: " + task.getException());
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
finish();
startActivity(new Intent(getApplicationContext(), SendReceiverSuccessPage.class));
});
// Connect to the database
if (svSearch != null) {
svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()) {
// Connect to the database
String currentUserId = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getEmail();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
searchedUsersModel = new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()) {
// Removes current user from list
SearchedUsersModel user = ds.getValue(SearchedUsersModel.class);
assert user != null;
if (!user.getMail().equals(currentUserId)) { // check if user's ID does not match current user's ID
searchedUsersModel.add(user); // add this user to the list of searched users
}
}
//Filter through the users based on Name or Email
ArrayList<SearchedUsersModel> myList = new ArrayList<>();
for(SearchedUsersModel object : searchedUsersModel) {
if(object.getMail().toLowerCase().contains(newText.toLowerCase())) {
myList.add(object);
}
else if(object.getName().toLowerCase().contains(newText.toLowerCase())) {
myList.add(object);
}
}
SearchedUsersAdapter searchedUsersAdapter = new SearchedUsersAdapter(myList, finalSendBtn, svSearch);
searchedUsersRecycler.setAdapter(searchedUsersAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else {
// Clear the data from the RecyclerView
searchedUsersModel = new ArrayList<>();
SearchedUsersAdapter searchedUsersAdapterClass = new SearchedUsersAdapter(searchedUsersModel, finalSendBtn, svSearch);
searchedUsersRecycler.setAdapter(searchedUsersAdapterClass);
//Set button to disabled
finalSendBtn.setEnabled(false);
}
return false;
}
});
return true;
}
});
}
}
}
SendReceiverSuccessPage
public class SendReceiverSuccessPage extends AppCompatActivity {
MaterialButton greatNextButton;
TextView sendSuccessText;
public static String usersName;
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sendreceiver_success_page);
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
greatNextButton = findViewById(R.id.great_next_button);
sendSuccessText = findViewById(R.id.send_success);
//Get sent amount from database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
DatabaseReference transactionsRef = databaseReference.child(firebaseUser.getUid()).child("transactions");
DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");
//
sendTransactionsRef.orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot transactionSnapshot : dataSnapshot.getChildren()) {
String lastTransactionKey = transactionSnapshot.getKey();
assert lastTransactionKey != null;
sendTransactionsRef.child(lastTransactionKey).child("amount").addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String sentAmount = snapshot.getValue(String.class);
sendSuccessText.setText("GH₵" + sentAmount + " has been sent to " + usersName);
//TODO This can also be where receiveTransactions document is created in the users database
// This sends the money to the chosen user by their name
databaseReference.orderByChild("name").equalTo(usersName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
// Get the main balance of the chosen user
String mainBalance = userSnapshot.child("userMainBalance").getValue(String.class);
DecimalFormat df = new DecimalFormat("0.00");
// Convert the main balance and amount sent to doubles
assert mainBalance != null;
double mainBalanceDouble = Double.parseDouble(mainBalance);
assert sentAmount != null;
double amountSentDouble = Double.parseDouble(sentAmount);
// Add the amount sent to the main balance
double updatedMainBalance = mainBalanceDouble + amountSentDouble;
// Convert the updated main balance back to a string
String updatedMainBalanceString = Double.toString(Double.parseDouble(df.format(updatedMainBalance)));
// Update the main balance in the database for the chosen user
userSnapshot.getRef().child("userMainBalance").setValue(updatedMainBalanceString);
userSnapshot.getRef().child("transactions").child("receivedTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(sentAmount);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Handle error
}
});
greatNextButton.setOnClickListener(v -> {
startActivity(new Intent(getApplicationContext(), MainDashboard.class));
});
}
}
There are also some Adapter classes I can add if needed.
I've been trying to figure it out with ChatGPT and have literally tried out everything.
Through testing I found out that anytime I take the
Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
lines out of the sendMoney button it ended up not creating multiple instances and working exactly like how I need it to. The only problem is that the amount sent that I need to pass to the success page isn't recoreded or passed. So ideally, if I could find a way or alternative to getting this data to the desired page without putting it into the button OnClick or having it create multiple instances of the activity.

Properly send value through many intents

I have tried all the good ole fashion ways of sending data through intents such as getExtra and putExtra. However, this certain piece of information will not travel through intents. The variable is initialized here (driverId):
private void findDriver() {
DatabaseReference drivers = FirebaseDatabase.getInstance().getReference(Common.driver_tbl);
GeoFire gfDrivers = new GeoFire(drivers);
GeoQuery geoQuery = gfDrivers.queryAtLocation(new GeoLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude()),radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
if(!Common.isDriverFound){
Common.isDriverFound = true;
Common.driverId = key;
btnPickupRequest.setText("CALL SUB");
Toast.makeText(Home.this,""+key, Toast.LENGTH_SHORT).show();
}
}
I then send the information for driverId when a button is clicked here:
Intent intent = new Intent(Home.this, CallDriver.class);
intent.putExtra("driverId",marker.getSnippet());
intent.putExtra("lat",mLastLocation.getLatitude());
intent.putExtra("lng",mLastLocation.getLongitude());
startActivity(intent);
I then call the information in the text intent like so:
if (driverId != null && !driverId.isEmpty())
if (getIntent() !=null) {
driverId = getIntent().getStringExtra("driverId");
}
sendRequestToDriver(driverId, mService, getBaseContext(), mLastLocation);
}
My send request to driver method is:
public static void sendRequestToDriver(String driverId,final IFCMService mService,final Context context,final Location currentLocation) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.token_tbl);
tokens.orderByKey().equalTo(driverId)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
{
Token token = postSnapShot.getValue(Token.class);
//String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()));
String riderToken = FirebaseInstanceId.getInstance().getToken();
Map<String,String> content = new HashMap<>();
content.put("customer", riderToken);
content.put("driverId",driverId);
content.put("lat",String.valueOf(currentLocation.getLatitude()));
content.put("lng",String.valueOf(currentLocation.getLongitude()));
DataMessage dataMessage = new DataMessage(token.getToken(),content);
Log.d(String.valueOf(dataMessage), "here big boy"+dataMessage);
mService.sendMessage(dataMessage).enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if(response.body().success == 1)
Toast.makeText(context, "Request Sent!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
Log.e("Error", t.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Now when I try to receive the information on the intent RateActivity, I get a null value. How can I make sure that the string driverId is properly initialized or the data stays throughout these intents?
try this intent.putExtra("driverId",marker.getSnippet().toString());
intent.putExtra("lat",mLastLocation.getLatitude().toString());
intent.putExtra("lng",mLastLocation.getLongitude().toString());

method int return wrong value [duplicate]

This question already has answers here:
How do i use a variable outside the onResponse in Android?
(4 answers)
Closed 4 years ago.
Greeting all, I am having the hard time to set int value for a variable in ValueEventListener and get that value outside ValueEventListener for the method to checking is value == 1, the method will return 1, else return 0
I have tried many way like save the value via SharedPreferences, set value to Textview and call from textview, but still, the method always return 0 as it cannot read the value that have been set in ValueEventListener. Any help are much appreciate. Thank you
Here my code
int status = 0;
protected void onCreate(Bundle savedInstanceState) {
...
btnSync_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getCustomerList() == 1) {
msg = msg + "Get customer success \n";
} else {
msg = msg + "Get customer unsuccessful \n";
}
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
}
The method that will return the int
private int getCustomerList() {
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
status = 1; //here my problem, value assign here is success
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
...
status = 0; // here if unsuccessful
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
...
}
});
if (status == 1) {
return 1;
} else {
return 0;
}
}
Even better way why dont't you display your AlertDialog inside getCustomerList() method
Call your getCustomerList() like this
btnSync_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCustomerList();
}
});
Then add your AlertDialog inside getCustomerList() like this
SAMPLE CODE
private void getCustomerList() {
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
msg = msg + "Get customer success \n";
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
...
msg = msg + "Get customer unsuccessful \n";
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
...
}
});
}

Check if is user first login on Android App using Firebase Auth and Database

I am making an chat app and I want to do the following:
When starting the MainActivity, check if the user is logged in. If not, start FirebaseAuthUI.
But FirebaseAuth only supports a few parameters and, to add more, I created a Database node do each user, which store other parameters.
To get this parameters, after finishing FirebaseAuth, the user is redirected to an Activity that get all extra information and store in the user's node in the Database. All of this is working just fine.
But after the user fill the information in this Info Activity and finish the register, it should go back to MainActivity and stay there. How can I do that?
I am trying it this way:
I added to each user a Boolean variable called userCompleted, which informs if the user have already gave their information. I check if this variable is false, and if so, I call the Info Activity intent and, in the when the user press the button to complete the registration in this Activity, it sets the userCompleted value to true in the user node in the Database and then start an intent that leads to MainActivity.
The problem is that in the Database, userCompleted is set to true and then immediately goes back to false, and I don't know why. Also, I guess I am having trouble on reading userCompleted from the Database, probably because I haven't worked much with asynchronous tasks.
I used a variable isUserCompleted declared in Main Activity to get track of the userCompleted value.
A way to check if is the first time the user is logging in would be useful too, although it wouldn't solve my whole problem.
This is my current code:
(if need more to try to understand the problem just ask in the comments)
Create AuthStateListener
public void setAuthStateListener(){
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
onSignInInitialize(user);
Log.d(TAG, "userUid = " + user.getUid());
Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
} else {
onSignOutCleanup();
startLoginUI();
}
}
};
}
onSignInInitialize()
public void onSignInInitialize(final FirebaseUser user){
mLoggedFBUser = user;
mUserReference = mUsersDatabaseReference.child(user.getUid());
mUserReference.child("uid").setValue(user.getUid());
mUserReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
isUserCompleted = user.isUserCompleted();
Log.d(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Log.d(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
if (!isUserCompleted) {
startCreateProfileActivity(user);
}
Log.d(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
mUserReference.child("username").setValue(user.getDisplayName());
mUserReference.child("email").setValue(user.getEmail());
attachChildEventListener();
}
Go back to Main Activity
mFinishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mUserDatabaseReference.child("userCompleted").setValue(true);
Intent intent = new Intent (CreateVolunteerProfile.this, SearchActivity.class);
startActivity(intent);
}
});
Entire MainActivity block (Actually it's called SearchActivity)
public class SearchActivity extends AppCompatActivity implements RecyclerAdapter.UserItemClickListener {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<User> users = new ArrayList<User>();
private String mLoggedUserId = "user2";
private String mLoggedUsername;
private User mLoggedUser;
private FirebaseUser mLoggedFBUser;
//private boolean isUserCompleted;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mPreferencesEditor;
private boolean firstTime = true;
private static final String TAG = "Search Activity";
private static final int USER_CLICK = 1;
private static final int RC_SIGN_IN = 1;
private static final int RC_CREATE_PROFILE = 2;
//Firebase
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mUsersDatabaseReference;
private DatabaseReference mUserReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
View loadingView = findViewById(R.id.cl_loading);
loadingView.setVisibility(View.VISIBLE);
//RecyclerView
recyclerView = findViewById(R.id.rv_users);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter(users, this);
recyclerView.setAdapter(adapter);
//Firebase
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mUsersDatabaseReference = mFirebaseDatabase.getReference().child("users");
setAuthStateListener();
loadingView.setVisibility(View.GONE);
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null)
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
detachChildEventListener();
clearAdapter();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.wtf(TAG, "onSaveInstanceState userId = "+ mLoggedUserId);
//Log.wtf(TAG, "UserCompleted (onSaveInstanceState) " + isUserCompleted);
outState.putString("userId", mLoggedUserId);
//outState.putBoolean("isUserCompleted", isUserCompleted);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mLoggedUserId = savedInstanceState.getString("userId");
//isUserCompleted = savedInstanceState.getBoolean("isUserCompleted");
//Log.wtf(TAG, "UserCompleted (onRestoreInstanceState) " + isUserCompleted);
Log.wtf(TAG, "onRestoreInstanceState userId = "+ mLoggedUserId);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if((requestCode == RC_SIGN_IN) && firstTime){
if (resultCode == RESULT_OK){
//Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED){
Toast.makeText(this, "Sign in canceled!", Toast.LENGTH_SHORT).show();
finish();
}
}
if((requestCode == RC_CREATE_PROFILE)){
if (resultCode == RESULT_OK){
//isUserCompleted = true;
}
}
}
#Override
public void onUserItemClick(int clickedUserIndex) {
Intent intent = new Intent (this, ChatActivity.class);
FirebaseUser user = mFirebaseAuth.getCurrentUser();
if(user != null) {
mLoggedUserId = user.getUid();
intent.putExtra("user1", mLoggedUserId);
String mUserRecieverId = users.get(clickedUserIndex).getUid();
intent.putExtra("user2", mUserRecieverId);
Log.wtf(TAG, "SearchActivity // user = " + users.get(clickedUserIndex));
Log.wtf("1", "SearchActivity // mLoggedUserId = " + mLoggedUserId + " // users.getUid() = " + users.get(clickedUserIndex).getUid());
startActivityForResult(intent, USER_CLICK);
}
else {
Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
}
}
public void setAuthStateListener(){
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
mUserReference = mUsersDatabaseReference.child(user.getUid());
onSignInInitialize(user);
Log.wtf(TAG, "userUid = " + user.getUid());
Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
} else {
onSignOutCleanup();
startLoginUI();
}
}
};
}
public void onSignInInitialize(final FirebaseUser user){
mLoggedFBUser = user;
mUserReference = mUsersDatabaseReference.child(user.getUid());
mUserReference.child("uid").setValue(user.getUid());
boolean isUserCompleted = false;
mUserReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
isUserCompleted = user.isUserCompleted();
Log.wtf(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Log.wtf(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
if (!isUserCompleted) {
startCreateProfileActivity(user);
}
Log.wtf(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
mUserReference.child("username").setValue(user.getDisplayName());
mUserReference.child("email").setValue(user.getEmail());
attachChildEventListener();
}
public void onSignOutCleanup(){
mLoggedUser = null;
mLoggedUserId = null;
mLoggedUsername = null;
detachChildEventListener();
clearAdapter();
}
public void attachChildEventListener(){
if (mChildEventListener == null){
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
User user = dataSnapshot.getValue(User.class);
users.add(user);
Log.d(TAG, "onChildAdded userId = "+ user.getUid());
//adapter.notifyItemInserted(users.size()-1);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) { }
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) { }
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) { }
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
};
}
mUsersDatabaseReference.addChildEventListener(mChildEventListener);
}
public void detachChildEventListener(){
if (mChildEventListener != null){
mUsersDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
public void clearAdapter() {
final int size = users.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
users.remove(0);
}
adapter.notifyItemRangeRemoved(0, size);
}
}
public void startCreateProfileActivity(FirebaseUser user){
mUsersDatabaseReference.child(user.getUid()).child("userCompleted").setValue(false);
Intent intent = new Intent(SearchActivity.this, CreateProfileActivity.class);
intent.putExtra("userId", user.getUid());
startActivityForResult(intent, RC_CREATE_PROFILE);
}
public void startLoginUI(){
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setLogo(R.mipmap.logo)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.GoogleBuilder().build(),
//new AuthUI.IdpConfig.FacebookBuilder().build(),
//new AuthUI.IdpConfig.TwitterBuilder().build(),
//new AuthUI.IdpConfig.GitHubBuilder().build(),
new AuthUI.IdpConfig.EmailBuilder().build()))
//new AuthUI.IdpConfig.PhoneBuilder().build(),
//new AuthUI.IdpConfig.AnonymousBuilder().build()))
.build(),
RC_SIGN_IN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_item:
AuthUI.getInstance().signOut(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I think the simplest way is if a user clicked on finish Btn successfully make a flag with true else make it false
in your MainActivity
firebase.auth().onAuthStateChanged(function(user) {
// User signed in and not registered
if (user&&!isPressedOnFinishBtn) {
// User is signed in.
}
user clicked on finish btn
else if(isPressedOnFinishBtn) {
// No user is signed in.
}
});
This is how you can do that .
Create a method inside your Login activity .
private void AllowUserToLogin() {
String userName = userEmail.getText().toString();
String userPass = userPassword.getText().toString();
if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass)) {
Toast.makeText(this, "Enter user Name / password first . . .", Toast.LENGTH_SHORT).show();
} else {
dialogBar.setTitle("Sign In ");
dialogBar.setMessage("Please Wait . . .");
dialogBar.setCanceledOnTouchOutside(true);
dialogBar.show();
mAuth.signInWithEmailAndPassword(userName, userPass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String currentUserID = mAuth.getCurrentUser().getUid();
String deviceToken = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
UsersRef.child(currentUserID).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserToMainActivity();
Toast.makeText(LoginPage.this, "Logged in Successfull . . . ", Toast.LENGTH_SHORT).show();
dialogBar.dismiss();
}
}
});
} else {
String error = task.getException().toString();
Toast.makeText(LoginPage.this, "Wrong Email or Password: " + error, Toast.LENGTH_SHORT).show();
dialogBar.dismiss();
}
}
});
}
}
and on ur onClick() method .
#Override
public void onClick(View v) {
if (v == needNewAccount) {
sendUserToRegisterActivity();
} else if (v == loginButton) {
AllowUserToLogin();
}else if(v == phone_button){
Intent phoneLoginIntent = new Intent(LoginPage.this , PhoneLoginActivity.class);
startActivity(phoneLoginIntent);
}
}
this is sendUserToRegisterActivity()
private void sendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginPage.this, RegisterationForm.class);
startActivity(registerIntent);
}
This is sendUserToMainActivity() .
private void sendUserToMainActivity() {
Intent mainIntent = new Intent(LoginPage.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}

how to get count of child inside the parent child

database rules
my database
I have a problem with writing data in firebase database
It must give an id for the data using method postId()
Sometimes its give me a right id and another time wrong id or updata data in an id was created
the id must be like this for all user post
[user1]
postId1
postId2
postId3
postId4
postId5
.
.
postId100000
[user2]
postId1
postId2
postId3
postId4
postId5
.
.
postId100000
........................................................................
if (auth.getCurrentUser() != null) {
mDatabase.child("AdUsersINFO").child(auth.getCurrentUser().getUid()).child(POSTID).setValue(adver,
new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Toast.makeText(getContext(), "Data is saved successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Data isn,t saved , please try again", Toast.LENGTH_LONG).show();
}
}
});
mAdUserDatabse = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO").child(auth.getCurrentUser().getUid()).child(POSTID);
mAdUserDatabse.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mAdUserDatabse.child("userid").setValue(auth.getCurrentUser().getUid());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void postId() {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild(auth.getCurrentUser().getUid())) {
// run some code
mAdUserDatabse = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO");
mAdUserDatabse.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.e(snap.getKey(), snap.getChildrenCount() + "");
if (snap.getChildrenCount() != 0) {
postId = "postId" + String.valueOf(snap.getChildrenCount() + 1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
please save my life
You're running a loop and overwriting value of postId again and again, so the postId is equal to the count of last child. So you're always getting the postId count for last user.
so have a look again at the part
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.e(snap.getKey(), snap.getChildrenCount() + "");
if (snap.getChildrenCount() != 0) {
postId = "postId" + String.valueOf(snap.getChildrenCount() + 1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
Consider using separate key for every user's postId or make a function to get key for one user something like this
public void getPostId(String userId) {
final String postId = "post";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO").child(userId);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
long c = snapshot.getChildrenCount();
if(c==) postId = postId+"1";
else postId = postId+ c+1;
},
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
};

Categories