8396

Android Firebase createUser() is not Working

Question:

I'm trying to create a user in the Firebase console using email and password but it doesn't work showing an error. Actually we can add users in the console by going to the dashboard and clicking on add user but I want to automate this process.

Here's the full code:

import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.firebase.client.AuthData; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import java.util.Map; public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "SignInActivity"; private static final int RC_SIGN_IN = 9001; private SignInButton mSignInButton; private Button but; private EditText email; private EditText password; private FirebaseAuth mAuth; private FirebaseUser mFirebaseUser; private GoogleApiClient mGoogleApiClient; private FirebaseAuth mFirebaseAuth; String user_id="",pass=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); email=(EditText)findViewById(R.id.emails); password=(EditText)findViewById(R.id.passwords); but=(Button)findViewById(R.id.create); Firebase.setAndroidContext(getBaseContext()); mAuth = FirebaseAuth.getInstance(); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { user_id= email.getText().toString(); pass= password.getText().toString(); Firebase ref = new Firebase("https://final-6b828.firebaseio.com/auth"); ref.createUser(user_id, pass, new Firebase.ValueResultHandler<Map<String, Object>>() { @Override public void onSuccess(Map<String, Object> result) { System.out.println("Successfully created user account with uid: " + result.get("uid")); String a= result.get("uid").toString(); Log.i("Success",user_id); Log.i("Success",pass); Toast.makeText(getApplicationContext(), "Pass", Toast.LENGTH_LONG).show(); } @Override public void onError(FirebaseError firebaseError) { // there was an error System.out.println("Failed to create user account : "); Log.i("Failed","a"); Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show(); } }); } }); mSignInButton = (SignInButton) findViewById(R.id.sign_in_button); mSignInButton.setOnClickListener(this); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); // Initialize FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance(); } private void handleFirebaseAuthResult(AuthResult authResult) { if (authResult != null) { FirebaseUser user = authResult.getUser(); Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, MainActivity.class)); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sign_in_button: signIn(); break; default: return; } } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); Log.e(TAG, "Google Sign In Successfull."); } else { Log.e(TAG, "Google Sign In failed."); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mFirebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); if (!task.isSuccessful()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(SignInActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } else { startActivity(new Intent(SignInActivity.this, MainActivity.class)); finish(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.d(TAG, "onConnectionFailed:" + connectionResult); Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); } } }

The code used to create an user is :

but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { user_id= email.getText().toString(); pass= password.getText().toString(); Firebase ref = new Firebase("https://final-6b828.firebaseio.com/auth"); ref.createUser(user_id, pass, new Firebase.ValueResultHandler<Map<String, Object>>() { @Override public void onSuccess(Map<String, Object> result) { System.out.println("Successfully created user account with uid: " + result.get("uid")); String a= result.get("uid").toString(); Log.i("Success",user_id); Log.i("Success",pass); Toast.makeText(getApplicationContext(), "Pass", Toast.LENGTH_LONG).show(); } @Override public void onError(FirebaseError firebaseError) { // there was an error System.out.println("Failed to create user account : "); Log.i("Failed","a"); Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show(); } }); } });

Answer1:

The correct code to create a user is..

but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { user_id= email.getText().toString(); pass= password.getText().toString(); createAccount(user_id,pass); } }); private void createAccount(String email, String password) { Log.d(TAG, "createAccount:" + email); if (!validateForm()) { return; } // showProgressDialog(); // [START create_user_with_email] mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful()); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Toast.makeText(SignInActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // [START_EXCLUDE] //hideProgressDialog(); // [END_EXCLUDE] } }); // [END create_user_with_email] } private boolean validateForm() { boolean valid = true; String emails = email.getText().toString(); if (TextUtils.isEmpty(emails)) { email.setError("Required."); valid = false; } else { email.setError(null); } String passwords = password.getText().toString(); if (TextUtils.isEmpty(passwords)) { password.setError("Required."); valid = false; } else { password.setError(null); } return valid; }

Recommend

  • PHPExcel: Automatically download and open an Excel file
  • Why is R reading numeric data as character?
  • Why throw local variable invokes moves constructor?
  • Unique array comprehension
  • Multiple sort depending on the current day and tomorrow (bus trips)
  • Entity Framework: “Faking” a queryable navigation property
  • Get domain\\username from microsoft graph
  • Multiple git user in single device
  • Custom progress dialog not working
  • How to search for a method or variable name within android project?
  • Failed to resolve: firebase-auth-15.0.0 [closed]
  • Authorize Attribute Authentication with Postman in Web Api
  • How to include WYSIWYG text editor in an HTML using google script
  • PHP: Need to close STDIN in order to read STDOUT?
  • Windows biometric framework sample umdf driver: This device cannot start. (Code 10)
  • What does “T extends Junk” mean in a generic class in Java?
  • Spotify cocoalibspotify offline status set to 1 but all tracks stuck at waiting
  • Pandas vs matplotlib datetime
  • How to make Rss News Reader application in android …? [closed]
  • 'Edit' function for forum posts and such
  • Year over Year Stats from a Crossfilter Dataset
  • How to define something in JavaScript [closed]
  • Calculate time from document
  • Neo4j…how to get a visual representation of my data?
  • How to turn off notice reporting in xampp?
  • reshape/remould data frame to create normalized bar chart and pie chart
  • Will this work on all screen sizes?
  • Google App Engine Datastore: Dealing with eventual consistency
  • read part of h5 dataset python
  • Bitrate JWplayer
  • Sign a Pdf using custom digital signature in Java
  • customize soft keyboard key preview
  • Accessing Arguments, Workflow Variables from custom activities
  • Write to .csv file with PHP (Commas in Data Error)
  • Spring Boot not autowiring @Repository
  • ReferenceError: TextEncoder is not defined
  • ARKit code issue {unknown error -1=ffffffffffffffff error: Task failed with exit 1}