Activity not stopping for response - java

I am new to app development (android studio).
I have two classes one is main and the other class (database) which connects to firebase and checks if the user exists or not and replies true or false respectively and also prints out some statements.
The problem is the android studio does not wait for a response even if the task is successful and replies a false.
print statement I should be getting in the logcat should be
"here 1", "here 2", and then "here 3". but it gives me "here 2", "here 3" and then "here 1".
I know it has to do something with threading or something like that.
public class loginpage extends AppCompatActivity {
private Button Login;
private EditText user_email_txt;
private EditText user_password_txt;
private ProgressBar wait_bar;
private String[] user_name_password ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_all_views();
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getuser_login_details();
disable_all_views();
Activate_wait_bar();
final Database login = new Database();
boolean decision = login.sign_in(user_name_password[0], user_name_password[1]);
System.out.println("here 3");
}
});
}
private void find_all_views() {
user_email_txt = findViewById(R.id.UserName);
user_password_txt = findViewById(R.id.Password);
Login = findViewById(R.id.submit_button);
wait_bar = findViewById(R.id.wait_bar);
}
private void getuser_login_details() {
user_name_password = new String[2];
user_name_password[0] = user_email_txt.getText().toString();
user_name_password[1] = user_password_txt.getText().toString();
}
private void disable_all_views() {
user_email_txt.setVisibility(View.INVISIBLE);
user_password_txt.setVisibility(View.INVISIBLE);
Login.setVisibility(View.INVISIBLE);
}
private void Activate_wait_bar() {
wait_bar.setVisibility(View.VISIBLE);
}
}
public class Database {
private FirebaseAuth connect_databse;
private boolean authorisation;
public Database() {}
public boolean sign_in(String user_name, String Password) {
authorisation = false;
connect_databse = FirebaseAuth.getInstance();
connect_databse.signInWithEmailAndPassword(user_name, Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = connect_databse.getCurrentUser();
authorisation = true;
System.out.println("here 1");
}
}
});
System.out.println("here 2");
return authorisation;
}
}
if the task is successful it should return authorization = true with print statements "here 1", "here 2", and then "here 3" in order.

create a new file:
interface OnCompleteListener {
void onComplete();
}
In Database class:
public class Database {
private FirebaseAuth connect_databse;
private boolean authorisation;
public Database() {
}
public void sign_in(String user_name, String Password,final OnCompleteListener listener) {
authorisation = false;
connect_databse = FirebaseAuth.getInstance();
connect_databse.signInWithEmailAndPassword(user_name, Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = connect_databse.getCurrentUser();
authorisation = true;
System.out.println("here 1");
listener.onComplete();
System.out.println("here 2");
}
}
});
}
In Activity:
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getuser_login_details();
disable_all_views();
Activate_wait_bar();
final Database login = new Database();
boolean decision = login.sign_in(user_name_password[0], user_name_password[1], new OnCompleteListener{
#Override
public void onComplete(){
System.out.println("here 3");
}
});
}
});

When you work with Network Connection or Call an API to get data from a server, you must use Background Thread and after the task completed, your code in OnComplete run. but main Thread doesn't stop for your task and run all code out of OnComplete method sequentially.
In this situation, you can use CallBackMethod.

Related

How to set Callbacks on PhoneAuthOptions in Firebase PhoneAuth?

"I just started learning Firebase"
I did set callbacks in PhoneAuthOptions yet I keep getting the error:
java.lang.NullPointerException: You must specify callbacks on your PhoneAuthOptions. Please call #setCallbacks().
This is my first activity, from which I am getting user's phone number and passing it to second activity:
public class SendOTPActivity extends AppCompatActivity {
private EditText mPhoneNumber;
private Button mBtnSendOtp;
String phoneNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_o_t_p);
mPhoneNumber = findViewById(R.id.phone_number);
mBtnSendOtp = findViewById(R.id.btn_send_otp);
phoneNumber = mPhoneNumber.getText().toString();
mBtnSendOtp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),VerifyOTPActivity.class);
intent.putExtra("PHONE_NUMBER",phoneNumber);
startActivity(intent);
mBtnSendOtp.setEnabled(false);
}
});
}
}
This is second activity (Verification Activity):
public class VerifyOTPActivity extends AppCompatActivity {
private EditText mOtpCode;
private Button mBtnVerifyOtp;
private TextView textView;
private ProgressBar progressBar;
private String phoneNumber;
private String code;
private FirebaseAuth mAuth;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_o_t_p);
mAuth = FirebaseAuth.getInstance();
mOtpCode = findViewById(R.id.otp_code);
mBtnVerifyOtp = findViewById(R.id.btn_verify_otp);
textView = findViewById(R.id.text_view);
progressBar = findViewById(R.id.progress_bar);
phoneNumber = getIntent().getStringExtra("PHONE_NUMBER");
code = mOtpCode.getText().toString();
textView.setText("An OTP has been sent to +91 "+phoneNumber);
startPhoneNumberVerification(phoneNumber);
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code!=null){
progressBar.setVisibility(View.VISIBLE);
}
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
Toast.makeText(VerifyOTPActivity.this, "Provided phone number might not be correct", Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
Toast.makeText(VerifyOTPActivity.this, "Some error has occurred please try again later!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = s;
mResendToken = token;
}
};
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
mAuth.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
FirebaseUser user = task.getResult().getUser();
// Update UI
} else {
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(VerifyOTPActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
// The verification code entered was invalid
}
}
}
});
}
private void startPhoneNumberVerification(String phoneNumber){
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+91"+phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(mCallbacks)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
In onCreate you call startPhoneNumberVerification(phoneNumber); before you create your OnVerificationStateChangedCallbacks. Try to move startPhoneNumberVerification(phoneNumber); below the block where you create your callback. That should get rid of the NullPointerException.

How do i get an OTP the second time after I've logged out the first time?

After I log in the first time and log out, the next time I log in I don't get an OTP.
How do I solve this problem??
The code works fine if I enter the phone number for the first time. Second time onwards I am not getting OTP number. In order to get the OTP number, I need to restart my phone each time. If I close and reopen the app then it's not helping me too.
VerifyPhoneActivity
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
editText = findViewById(R.id.editTextCode);
progressBar =findViewById(R.id.progressbar);
String phonenumber = getIntent().getStringExtra("phonenumber");
setVerificationCode(phonenumber);
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String code = editText.getText().toString().trim();
if(code.isEmpty() || code.length()< 6){
editText.setError("Enter code");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
SignInWithCredential(credential);
}
private void SignInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
private void setVerificationCode(String number){
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code =phoneAuthCredential.getSmsCode();
if(code != null){
editText.setText(code);
SignInWithCredential(phoneAuthCredential);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
You should read docs if mobile gets registered on firebase it won't send OTP all time, maybe few times.
Once mobile is registered you will get success and then you can verify.

How to sign in a token using firebase?

In my app there's a signup option, there a user can input his data, after user put input they can get a token, then they can sign in with that token,every user get a unique token and sign in with this unique token.how can I do it with firebase?
Here is the firebase database:
https://i.pinimg.com/originals/40/47/18/404718948df116f257abe31fa8cc98e7.png
Here is the sample code:
public class MainActivity extends AppCompatActivity {
//for sign in
EditText edtUser,edtPwd;
//for sign up
EditText edtNewUser,edtnewPassword,edtnewPhnNum,edtnewEmail;
Button signIn,signUp;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtUser = findViewById(R.id.signinUserEdit);
edtPwd = findViewById(R.id.signinUserPwd);
signIn = findViewById(R.id.signinBtn);
signUp = findViewById(R.id.signUpBtn);
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signUpDilog();
}
});
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signInMethod(edtUser.getText().toString(),edtPwd.getText().toString());
}
});
}
private void signInMethod(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user).exists()){
if (!user.isEmpty()){
SignInUpModel login = dataSnapshot.child(user).getValue(SignInUpModel.class);
if (login.getPassword().equals(pwd)){
Toast.makeText(MainActivity.this,"Login ok!",Toast.LENGTH_LONG).show();
Intent home = new Intent(MainActivity.this,HomeActivity.class);
CommonModel.currentUser = login;
startActivity(home);
finish();
}
else
Toast.makeText(MainActivity.this,"Wrong Password",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Please enter your user name",Toast.LENGTH_LONG).show();
}
}
else
Toast.makeText(MainActivity.this,"User is not exists",Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void signUpDilog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign Up");
alertDialog.setMessage("Please fill your information");
LayoutInflater inflater = this.getLayoutInflater();
View signUpLayout = inflater.inflate(R.layout.signuplayout,null);
edtNewUser = signUpLayout.findViewById(R.id.signUpEdit);
edtnewEmail = signUpLayout.findViewById(R.id.signoutemailEdit);
edtnewPhnNum = signUpLayout.findViewById(R.id.signupphnEdit);
edtnewPassword = signUpLayout.findViewById(R.id.signUpPwd);
alertDialog.setView(signUpLayout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final SignInUpModel user = new SignInUpModel(edtNewUser.getText().toString(),edtnewEmail.getText().toString(),
edtnewPhnNum.getText().toString(),edtnewPassword.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user.getUserName()).exists()){
Toast.makeText(MainActivity.this,"User already exists",Toast.LENGTH_LONG).show();
}else{
users.child(user.getUserName()).setValue(user);
Toast.makeText(MainActivity.this,"User registration success!",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
I expect when the user put his/her details and complete signup then he/she gets a token and put this token and complete his signing and goes to the next activity. How can I do that using firebase? thank u
Try this for SignUp
TextView mailSignup = findViewById(R.id.mailSignup);
String Email = mailSignup.getText().toString();
TextView passwordSignup = findViewById(R.id.passwordSignup);
String Password = passwordSignup.getText().toString();
TextView nameSignup = findViewById(R.id.nameSignup);
String Name = nameSignup.getText().toString();
TextView ErrorText = findViewById(R.id.errortext);
TextView confirmPassSignup = findViewById(R.id.confirmpassSignup);
String Verification = confirmPassSignup.getText().toString();
if (!(Password.isEmpty()) && !(Email.isEmpty()) && !(Name.isEmpty()) && Password.equals(Verification) && Password.length() > 5) {
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(Email, Password).addOnCompleteListener(SignUp.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
mDatabase = FirebaseDatabase.getInstance().getReference("users");
String UserUid = mAuth.getCurrentUser().getUid();
user User = new user(UserUid,Name,Email);
mDatabase.child(UserUid).setValue(User);
// Toast.makeText(SignUp.this, "Save Done", Toast.LENGTH_SHORT).show();
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
progressDialog.dismiss();
}
}, 1000);
// If sign in fails, display a message to the user.
Toast.makeText(SignUp.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
And this for Login
EditText mailLogin = findViewById(R.id.mailLogin);
String Email = mailLogin.getText().toString();
EditText passwordLogin = findViewById(R.id.passwordLogin);
String Password = passwordLogin.getText().toString();
if (!(Email.isEmpty()) && !(Password.isEmpty())){
mAuth.signInWithEmailAndPassword(Email,Password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent goToHome = new Intent(LoginActivity.this, Home.class);
startActivity(goToHome);
}
else{
Toast.makeText(getApplicationContext(),"Wrong Credentials",Toast.LENGTH_LONG).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 1000);
}
}
});
}
}

How to make simple user sign in with just username (firebase)

I am completely noob (again sorry about my ignorance in this field I relly need help) in java and I need to make an app with firebase. Here is my register account code(its all the code I have copied from GitHub :P) I want to make it just to register with username, the register with email and password functionality and the verification sending future completely to be disabled , also I need to make it to go on a different activity or simply to login the user and show the posts feed. I hope someone could help me:
public class SignupActivity extends BaseActivity {
private static final String TAG = "SignupActivity";
private Context mContext = SignupActivity.this;
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FireBaseMethods fireBaseMethods;
private String email, handleName, password;
private EditText mHandleName, mEmail, mPassword;
private Button mButtonRegister;
private TextView loadingPleaseWait;
private ProgressBar mProgressBar;
//firebase Database
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
boolean isExisted;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
fireBaseMethods = new FireBaseMethods(mContext);
Log.d(TAG, "onCreate: started");
initWidgets();
setupFirebaseAuth();
init();
}
#Override
protected void performOnCreate(Bundle state) {
}
private void init() {
mButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleName = mHandleName.getText().toString();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(mEmail.getText().toString());
stringBuilder.append("");
email = stringBuilder.toString();
password = mPassword.getText().toString();
if (validate()) {
mProgressBar.setVisibility(View.VISIBLE);
loadingPleaseWait.setVisibility(View.VISIBLE);
fireBaseMethods.registerNewEmail(handleName, email, password);
}
}
});
}
/*
Initialize the activity widgets
*/
private void initWidgets() {
Log.d(TAG, "initWidgets: Initialize Widgets");
mHandleName = findViewById(R.id.handle_name);
mEmail = findViewById(R.id.input_email_signup);
mPassword = findViewById(R.id.input_password_signup);
mButtonRegister = findViewById(R.id.btn_signup);
mProgressBar = findViewById(R.id.progressBar);
loadingPleaseWait = findViewById(R.id.loading_signup);
mProgressBar.setVisibility(View.GONE);
loadingPleaseWait.setVisibility(View.GONE);
}
public boolean validate() {
boolean valid = true;
if (handleName.isEmpty() || handleName.length() < 3) {
mHandleName.setError("Внесете најмалку 3 карактери");
valid = false;
} else {
mHandleName.setError(null);
}
if (email.isEmpty()) {
mEmail.setError("Внесете валидна електронска пошта");
valid = false;
} else {
mEmail.setError(null);
}
if (password.isEmpty() || password.length() < 4) {
mPassword.setError("помеѓу 4 и 10 карактери");
valid = false;
} else {
mPassword.setError(null);
}
return valid;
}
/*
------------------------------------- Firebase ---------------------------------------------------
*/
/**
* Set up firebase auth object
*/
private void setupFirebaseAuth() {
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: make sure handle name is not ready in use
if (fireBaseMethods.checkIfHandleNameAlreadyExists(handleName, dataSnapshot)) {
mHandleName.setError("Тој ник веќе постои");
isExisted = true;
}
//add new user to the database
fireBaseMethods.addNewUser(handleName, email);
Toast.makeText(mContext, "Регистрирањето беше успешно.Ви пративме верификација на email", Toast.LENGTH_SHORT).show();
mAuth.signOut();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
finish();
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
I do NOT advise the ability to sign up with ONLY a username. You lose the ability to recover an account.
However, you may take the username given to you, and append #fakeemail.com to the end of it and continue to use the email/password method.

(Android, Firebase) databasereference.push().setValue() not working even though log says otherwise

I'm testing Firebase by building an app that simply puts a message in the Database (authorisations are set to true for the test), it worked only once, and now nothing is pushed to the database. But as you can see I put logs everywhere to see where the problem is and surprisingly the onChildEventListener() seems to notice a change.
Here is the code for my main activity :
public class MainActivity extends AppCompatActivity {
public final static String TAG = "Main Activity";
public final int[] id = {0};
Button sendButton;
EditText messageEditText;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id[0] = 0;
sendButton = findViewById(R.id.send_message);
messageEditText = findViewById(R.id.message_text);
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("test/geomessage/");
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message = messageEditText.getText().toString();
Log.e(TAG, "Test 1");
GeoMessage currentGeomessage = new GeoMessage(id[0], message);
Log.e(TAG, "Test 2");
databaseReference.child("children").push().setValue(currentGeomessage).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.e(TAG, "Success !");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "FAIL");
}
}).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.e(TAG, "Complete");
}
});
Log.e(TAG, "Test 3");
}
});
databaseReference.child("children").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("101", "Child Added !");
id[0] = (int) dataSnapshot.getChildrenCount();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e("101", "Child CHanged !");
id[0] = (int) dataSnapshot.getChildrenCount();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private static class GeoMessage {
int id;
String content;
public GeoMessage() {};
public GeoMessage(int id, String content) {
this.id = id;
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
}
Here are the logs when I click on the "Send" Button :
11-03 19:02:13.338 7440-7440/com.example.brumor.geofiretest E/Main Activity: Test 1
11-03 19:02:13.338 7440-7440/com.example.brumor.geofiretest E/Main Activity: Test 2
11-03 19:02:13.340 7440-7440/com.example.brumor.geofiretest E/Main Activity: Test 3
11-03 19:02:13.420 7440-7440/com.example.brumor.geofiretest E/101: Child Added !
The observed behavior occurs when the device does not have a connection to the Firebase servers. Calls to setValue() change the DB cache held locally in the client. This causes listeners for the changed location to fire. But the completion listeners for setValue() do not fire until the update to the Firebase server completes successfully or fails.
Check that your device has a network connection. You can detect the Firebase connection status using the example here.
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message = messageEditText.getText().toString();
GeoMessage currentGeomessage = new GeoMessage(id[0], message);
databaseReference.child("children").push().setValue(currentGeomessage);
}
});
No need to use addonSuccessListener to store data. Also it is not even entering the method addonSuccessListener , so its skipping the whole method and then it prints the Log for you, but nothing is entering the database. Usually onSuccessListener is used for firebase storage, to see if the task is successful or not.
Also according to this page: https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/tasks/Task
public abstract Task<T> addOnSuccessListener (OnSuccessListener<? super T> listener)
The above method is deprecated.
You have to use this now:
public abstract Task<T> addOnSuccessListener (Executor executor, OnSuccessListener<? super T> listener)

Categories