Phone auth error - android

I wrote the code for firebase phone auth, and no error occured. But when i execute the app and entered the number ,i am getting as verification failed .pls help me out
I even connected to firebase proj and enables phone and also wrote SHA certificate
my code for main activity-
public class MainActivity extends AppCompatActivity {
EditText phone,vcode;
TextView msg;
Button getcode,verify;
private FirebaseAuth mAuth;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.phone);
vcode = findViewById(R.id.code);
getcode = findViewById(R.id.getcode);
verify = findViewById(R.id.verify);
msg = findViewById(R.id.msgtxt);
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Toast.makeText(MainActivity.this, "Verified", Toast.LENGTH_LONG).show();
vcode.setVisibility(View.GONE);
verify.setVisibility(View.GONE);
msg.setVisibility(View.VISIBLE);
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(MainActivity.this, "Login Failed", Toast.LENGTH_LONG).show();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
phone.setError("Invalid phone number");
} else if (e instanceof FirebaseTooManyRequestsException) {
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
}
};
}
public void GetCode(View view) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone.getText().toString(),
60,
TimeUnit.SECONDS,
this,
mCallbacks);
phone.setVisibility(View.GONE);
getcode.setVisibility(View.GONE);
vcode.setVisibility(View.VISIBLE);
verify.setVisibility(View.VISIBLE);
}
public void verify(View view) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, vcode.getText().toString());
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>
() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user=task.getResult().getUser();
startActivity(new Intent(MainActivity.this,MainActivity.class));
vcode.setVisibility(View.GONE);
verify.setVisibility(View.GONE);
msg.setVisibility(View.VISIBLE);
finish();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid code", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
For main2 activity-
public class Main2Activity extends AppCompatActivity {
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Main2Activity.this, MainActivity.class);
startActivity(i);
}
});
}
}

Related

How to associate each Firebase user with their own recyclerView Data

I'm creating an app that display notes list in a recyclerView. I connected the app with firebase authentication and realtime database.
The Realtime Database JSON tree looks like this:
The problem is that I want "Notes" to be part of "Users" which is not the case, because when I login to my app, I found the same Notes in every user account. I want the notes to be displayed for a specific user when they create them.
Here is my code:
SignupActivity.java
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
FirebaseFirestore fStore;
String userID;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
final String name = mName.getText().toString();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("email", email);
user.put("image", "default");
user.put("thumb_image", "default");
current_user_db.setValue(user);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: user Profile is created for "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: "+ e.toString());
}
});
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("886475354465-j5suema9gt5mhi2fhli0un9vsn1olvaa.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.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
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
NotesAdapter.java
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyHolder>
{
List<Listdata> noteslist;
private Context context;
public NotesAdapter(List<Listdata> noteslist,Context context)
{
this.context=context;
this.noteslist=noteslist;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
MyHolder myHolder=new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int position) {
Listdata data=noteslist.get(position);
myHolder.title.setText(data.getTitle());
myHolder.desc.setText(data.getDesc());
}
#Override
public int getItemCount() {
return noteslist.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView title,desc;
public MyHolder(#NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title);
desc=itemView.findViewById(R.id.desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listdata listdata=noteslist.get(getAdapterPosition());
Intent i=new Intent(context, StreamActivity.class);
i.putExtra("id",listdata.id);
i.putExtra("title",listdata.title);
i.putExtra("desc",listdata.desc);
context.startActivity(i);
}
});
}
}
}
AddNotesActivity.java
public class AddNotesActivity extends AppCompatActivity {
EditText title,desc;
String titlesend,descsend;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_notes);
title=findViewById(R.id.title);
desc=findViewById(R.id.desc);
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void AddNotes(View view) {
titlesend=title.getText().toString();
descsend=desc.getText().toString();
if(TextUtils.isEmpty(titlesend) || TextUtils.isEmpty(descsend)){
return;
}
AddNotes(titlesend,descsend);
}
private void AddNotes(String titlesend, String descsend)
{
String id=mDatabase.push().getKey();
Listdata listdata = new Listdata(id,titlesend, descsend);
mDatabase.child("Notes").child(id).setValue(listdata).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AddNotesActivity.this, "Notes Added", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),NotesActivity.class));
}
});
}
}
NotesActivity.java
public class NotesActivity extends AppCompatActivity {
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
//HomeScreen variables
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
List<Listdata> list =new ArrayList<>();
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(NotesActivity.this);
recyclerView.setLayoutManager(layoutManager);
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Notes Screen
final NotesAdapter notesAdapter=new NotesAdapter(list,this);
recyclerView.setAdapter(notesAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("Notes");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Listdata listdata=dataSnapshot1.getValue(Listdata.class);
list.add(listdata);
}
notesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddNotesActivity.class));
}
});
// end NotesScreen
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(NotesActivity.this, LoginActivity.class);
startActivity(startIntent);
finish();
}
Please I need help on how should I modify my code to display the notes for a specific user when they create them. documentation links will be much appreciated.
you simply need to change this line of code from AddNotesActivity.java
mDatabase.child("Notes").child(id)
to
mDatabase.child("Users").child(userID).child("Notes").child(id)
and don't forget to retrieve the data in NotesActivity.java
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID).child("Notes");

java.lang.IllegalArgumentException while authentication using firebase

I am making a Whatsapp like app(By Following tutorial). It crashes when i click on send code button. i confirmed it by try/catch my phone number verification is not working or there's a problem with it
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential
without either verificationProof, sessionInfo, ortemprary proof.
What i confirmed/tried:
both activities are declared in manifest,
assigned id to layout,
initialized relative argument,
Nothing is there in libs folder of the project,
swapped initialization with layout ,
Tried this code to get value:
String.valueOf(phoneNumberEdt)
I did all what i could as per my level
public class MainActivity extends AppCompatActivity {
private EditText phoneNumberEdt, verificationcodeEdt;
Button sendCodeButton;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks;
String mVerificationId = "0";
//private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumberEdt = (EditText) findViewById(R.id.phonenumber_edt);
verificationcodeEdt = (EditText)
findViewById(R.id.verificationcode_edt);
sendCodeButton = (Button) findViewById(R.id.sendcode_btn);
FirebaseApp.initializeApp(this);
userIsLoggedIn();
phoneNumberEdt.setText("03026989523");
sendCodeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//try{
if(mVerificationId != null)
verifyPhoneNumberWithCode();
else
startPhoneNumberVerification();
/*}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(),
"Verification Code is wrong, try again", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}*/
mCallBacks = new
PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential
phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {}
#Override
public void onCodeSent(String VerificationId,
PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(VerificationId, forceResendingToken);
mVerificationId = VerificationId;
sendCodeButton.setText("Verify Code");
}
};
}
});
}
Error points here
private void startPhoneNumberVerification() {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumberEdt.getText().toString(),//String.valueOf(phoneNumberEdt)
60,
TimeUnit.SECONDS,
this,
mCallBacks);
}
Rest of the functions
private void verifyPhoneNumberWithCode(){
PhoneAuthCredential credential =
PhoneAuthProvider.getCredential(mVerificationId,
verificationcodeEdt.getText().toString());
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential
phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).
addOnComp leteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
userIsLoggedIn();
}
});
}
private void userIsLoggedIn() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
startActivity(new
Intent(getApplicationContext(),MainPageActivity.class));
finish();
return;
}
}

MVP Architecture

I tried to Refactor the Login Module of the Application Any Mistakes and Suggestions what else should i work on and i should keep in mind
Login Presenter.java
public class LoginPresenter implements LoginInteractor.LoginPresenter {
private LoginInteractor.LoginView loginView;
public LoginPresenter(LoginInteractor.LoginView loginView) {
this.loginView = loginView;
}
#Override
public void CheckIdUserVerified(FirebaseUser currentUser, Context context) {
if (currentUser != null) {
if (currentUser.isEmailVerified()) {
loginView.OnLoginSuccess();
}
}
}
#Override
public void Register() {
loginView.OnRegister();
}
#Override
public void Login(String email,String password,final FirebaseAuth mAuth){
if (email.isEmpty() && password.isEmpty()) {
loginView.OnMessage("password is empty");
return;
} else if (email.isEmpty()) {
loginView.OnMessage("email is empty");
return;
} else if (password.isEmpty()) {
loginView.OnMessage("password is empty");
return;
} else {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
if (mAuth.getCurrentUser().isEmailVerified()) {
loginView.OnLoginSuccess();
} else {
loginView.builderr("Verify","Verify mo to","Verify");
loginView.OnMessage("Failed");
}
}
}});}}}
Should i Use Firebase on the Model part or its ok if its in View
Login View.java
public class LoginView extends AppCompatActivity implements
LoginInteractor.LoginView {
private LoginPresenter loginPresenter;
public Button login;
public TextView register;
EditText editTextEmail, editTextPassword;
FirebaseAuth mAuth;
FirebaseUser currentUser;
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Initialize();
loginPresenter.CheckIdUserVerified(currentUser,this);
//LoginButtonOnClick
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginPresenter.Login(editTextEmail.getText().toString(),
editTextPassword.getText().toString(),mAuth);
}
});
//Goto Register Page
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginPresenter.Register();
}
});
}
#Override
public void Initialize() {
loginPresenter = new LoginPresenter(this);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
login = (Button)findViewById(R.id.buttonLogin);
register = (TextView)findViewById(R.id.registertext);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Logging in..");
progressDialog.setCancelable(false);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
}
public void OnVerify(){
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.gm");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
} else {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://mail.google.com/mail/#inbox")));
}
}
public void OnRegister(){
startActivity(new Intent(LoginView.this, RegisterView.class));
}
public void OnMessage(String message){
Toast.makeText(LoginView.this, message, Toast.LENGTH_SHORT).show();
}
public void OnLoginSuccess(){
startActivity(new Intent(LoginView.this, MainActivity.class));
finish();
}
public void builderr(String BulderTitle,String BuilderMessage,String
PositiveButton) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(BulderTitle);
builder.setMessage(BuilderMessage);
builder.setInverseBackgroundForced(true);
builder.setPositiveButton(PositiveButton,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
OnVerify();
}});
AlertDialog alert = builder.create();
alert.show();
}}
LoginInteractor
public interface LoginInteractor {
interface LoginView{
void Initialize();
void OnLoginSuccess();
void OnMessage(String message);
void OnRegister();
void builderr(String BulderTitle,String BuilderMessage,String
PositiveButton);
}
interface LoginPresenter{
void CheckIdUserVerified(FirebaseUser currentUser, Context context);
void Login(String email, String password, FirebaseAuth mAuth);
void Register();
}
}
**
If i should put firebase on model any idea that will look like?
i was kinda reasearching and looking for answers but how should i initialize firebase without the oncreate Method?**

MainActivty should lead to LoginActivity but skips it. Leads to MapActivity that should only be visible after login

I seem to have altered something in my code and I can't figure out what it is I need to revert.
I'm building an app that will have a MainActivity that will lead to a loginActivity. However, when the login button is pressed the app is now skipping that and going to a MapActivity that should only be visible to logged in users.
I've checked my MainActivity code and I don't think the problem is there, I think it's the LoginActivity code:
public class ResponderLoginActivity extends AppCompatActivity {
private EditText mEmail, mPassword;
private Button mLogin, mRegistration;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_responder_login);
mAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
Intent intent = new Intent(ResponderLoginActivity.this, ResponderMapActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.login);
mRegistration = (Button) findViewById(R.id.registration);
mRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(ResponderLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(ResponderLoginActivity.this, "sign up error", Toast.LENGTH_SHORT).show();
} else {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Responders").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(ResponderLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(ResponderLoginActivity.this, "Sign in error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
}

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String for (Using map to update the details from Firebase)

Currently, I'm trying to use to update the details from my Firebase Database.However, it gives the classcastexception error. Could anyone help me to solve this problem? Thank you
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.online_mobile_flexi_parking, PID: 21533
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
at com.google.online_mobile_flexi_parking.ChangeEmailPassword$8$1.onDataChange(ChangeEmailPassword.java:243)
at com.google.android.gms.internal.zzakg.zza(Unknown Source)
at com.google.android.gms.internal.zzalg.zzcxk(Unknown Source)
at com.google.android.gms.internal.zzalj$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5028)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
243 line is phoneAcc.set_IdentityCard(map.get("_IdentityCard"));
ChangeEmailPassword.java
public class ChangeEmailPassword extends AppCompatActivity {
private Button btnChangeEmail, btnChangePassword,
changeEmail, changePassword, back, btnChangePhone, btnChangeCarPlate, changePhone,
changeCarPlate, signOut;
private EditText oldEmail, newEmail, password, newPassword, oldPhone, newPhone, confirmPassword;
private ProgressBar progressBar;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
DatabaseReference mDatabase;
FirebaseUser user;
private String txtPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_email_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.app_name));
setSupportActionBar(toolbar);
//get firebase auth instance
auth = FirebaseAuth.getInstance();
//get current user
user = FirebaseAuth.getInstance().getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(ChangeEmailPassword.this, TestUser.class));
finish();
}
}
};
btnChangeEmail = (Button) findViewById(R.id.change_email_button);
btnChangePassword = (Button) findViewById(R.id.change_password_button);
btnChangePhone=(Button)findViewById(R.id.change_phone_button);
changeEmail = (Button) findViewById(R.id.changeEmail);
changePassword = (Button) findViewById(R.id.changePass);
changePhone=(Button) findViewById(R.id.changePhone);
//signOut = (Button) findViewById(R.id.sign_out);
back=(Button)findViewById(R.id.btnback1);
oldEmail = (EditText) findViewById(R.id.old_email);
newEmail = (EditText) findViewById(R.id.new_email);
password = (EditText) findViewById(R.id.password);
newPassword = (EditText) findViewById(R.id.newPassword);
confirmPassword=(EditText)findViewById(R.id.confirmpassword);
oldPhone=(EditText)findViewById(R.id.old_phone);
newPhone=(EditText)findViewById(R.id.new_phone);
oldEmail.setVisibility(View.GONE);
newEmail.setVisibility(View.GONE);
password.setVisibility(View.GONE);
newPassword.setVisibility(View.GONE);
confirmPassword.setVisibility(View.GONE);
changeEmail.setVisibility(View.GONE);
changePassword.setVisibility(View.GONE);
oldPhone.setVisibility(View.GONE);
newPhone.setVisibility(View.GONE);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(ChangeEmailPassword.this, TestUser.class));
finish();
}
});
btnChangeEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oldEmail.setVisibility(View.GONE);
newEmail.setVisibility(View.VISIBLE);
password.setVisibility(View.GONE);
newPassword.setVisibility(View.GONE);
confirmPassword.setVisibility(View.GONE);
changeEmail.setVisibility(View.VISIBLE);
changePassword.setVisibility(View.GONE);
changePhone.setVisibility(View.GONE);
oldPhone.setVisibility(View.GONE);
newPhone.setVisibility(View.GONE);
}
});
changeEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
if (user != null && !newEmail.getText().toString().trim().equals("")) {
user.updateEmail(newEmail.getText().toString().trim())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ChangeEmailPassword.this, "Email address is updated. Please sign in with new email id!", Toast.LENGTH_LONG).show();
startActivity(new Intent(ChangeEmailPassword.this, MainActivity.class));
finish();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(ChangeEmailPassword.this, "Failed to update email!", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else if (newEmail.getText().toString().trim().equals("")) {
newEmail.setError("Enter email");
progressBar.setVisibility(View.GONE);
}
}
});
btnChangePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oldEmail.setVisibility(View.GONE);
newEmail.setVisibility(View.GONE);
password.setVisibility(View.GONE);
newPassword.setVisibility(View.VISIBLE);
confirmPassword.setVisibility(View.VISIBLE);
changeEmail.setVisibility(View.GONE);
changePassword.setVisibility(View.VISIBLE);
changePhone.setVisibility(View.GONE);
oldPhone.setVisibility(View.GONE);
newPhone.setVisibility(View.GONE);
}
});
changePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
if (user != null && !newPassword.getText().toString().trim().equals("")) {
if (newPassword.getText().toString().trim().length() < 6) {
newPassword.setError("Password too short, enter minimum 6 characters");
progressBar.setVisibility(View.GONE);
} else if (!(newPassword.getText().toString().trim().equals(confirmPassword.getText().toString().trim()))) {
newPassword.setError("Password are not matching");
progressBar.setVisibility(View.GONE);
} else {
user.updatePassword(newPassword.getText().toString().trim())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ChangeEmailPassword.this, "Password is updated, sign in with new password!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ChangeEmailPassword.this, MainActivity.class));
finish();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(ChangeEmailPassword.this, "Failed to update password!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
} else if (newPassword.getText().toString().trim().equals("")) {
newPassword.setError("Enter password");
progressBar.setVisibility(View.GONE);
}
}
});
btnChangePhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oldEmail.setVisibility(View.GONE);
newEmail.setVisibility(View.GONE);
password.setVisibility(View.GONE);
newPassword.setVisibility(View.GONE);
confirmPassword.setVisibility(View.GONE);
changeEmail.setVisibility(View.GONE);
changePassword.setVisibility(View.GONE);
changePhone.setVisibility(View.VISIBLE);
oldPhone.setVisibility(View.GONE);
newPhone.setVisibility(View.VISIBLE);
}
});
changePhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
txtPhone = newPhone.getText().toString().trim();
if (!txtPhone.equals("")) {
mDatabase.child(user.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Account phoneAcc=new Account();
Map<String,String> map=(Map)dataSnapshot.getValue();
phoneAcc.set_FullName(map.get("_FullName"));
phoneAcc.set_CarPlate1(map.get("_CarPlate1"));
phoneAcc.set_IdentityCard(map.get("_IdentityCard"));
phoneAcc.set_Phone(txtPhone);
mDatabase.child(user.getUid()).setValue(phoneAcc);
Toast.makeText(ChangeEmailPassword.this, "Phone is updated, sign in with new password!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ChangeEmailPassword.this, MainActivity.class));
finish();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else if (txtPhone.equals("")) {
newPhone.setError("Enter phone number");
progressBar.setVisibility(View.GONE);
}
}
});
}
}
Account.java
public class Account {
private String _Phone;
private String _IdentityCard;
private String _FullName;
private String _CarPlate1;
private String _CarPlate2;
private String _CarPlate3;
public Account(){}
public Account(String fullname, String phone, String carplate1, String identitycard)
{
this._Phone=phone;
this._CarPlate1=carplate1;
this._FullName=fullname;
this._IdentityCard=identitycard;
}
public Account(String carplate1,String carplate2,String carplate3)
{
this._CarPlate1=carplate1;
this._CarPlate2=carplate2;
this._CarPlate3=carplate3;
}
public void set_Phone(String _Phone) {
this._Phone = _Phone;
}
public String get_Phone() {
return _Phone;
}
public String get_IdentityCard() {
return _IdentityCard;
}
public void set_IdentityCard(String _IdentityCard){this._IdentityCard=_IdentityCard;}
public String get_FullName() {
return _FullName;
}
public void set_FullName(String _FullName){ this._FullName=_FullName;}
public void set_CarPlate1(String _CarPlate1) {
this._CarPlate1 = _CarPlate1;
}
public String get_CarPlate1() {
return _CarPlate1;
}
public void set_CarPlate2(String _CarPlate2) {
this._CarPlate2 = _CarPlate2;
}
public String get_CarPlate2() {
return _CarPlate2;
}
public void set_CarPlate3(String _CarPlate3) {
this._CarPlate3 = _CarPlate3;
}
public String get_CarPlate3() {
return _CarPlate3;
}
}
It means you can't cast Long type to String directly.Try add "" like
long l = 123;
String str = "" + l;
When you are assigning the long value into string then
long var = 1;
String value = ""+var;
insted of assigning like
String value = var;
It will work.

Categories

Resources