Firebase AuthUI - Uknown Error Code - java

I am using the Firebase AuthUI to sign in to my application, specifically with Facebook. I have verified within my console that my sign in was successful, as I see the user added.
However, my callback method is not triggering, I have toasts implemented and I do not know why the success method is not being called. I have logged the error code and do not know what issue it signifies. Am I capturing the error correctly? It is generating -1, which I do not see in the Firebase AuthUI docs:
public class LoginActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 123;
private static final String USERS = "Users";
private FirebaseAuth mAuth;
FirebaseDatabase mBaseRef;
DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
mBaseRef = FirebaseDatabase.getInstance();
mUserRef = mBaseRef.getReference(USERS);
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.FacebookBuilder().build()))
.build(), RC_SIGN_IN);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// RC_SIGN_IN is the request code you passed into startActivityForResult(...) when starting the sign in flow.
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
Log.v("RESPONSE", String.valueOf(response.getErrorCode()));
// Successfully signed in
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "SIGNED IN SUCCESSFULLY", Toast.LENGTH_LONG).show();
if (mAuth.getCurrentUser() != null) {
HashMap<String, Object> map = new HashMap<>();
map.put("TEST USER ", mAuth.getCurrentUser());
mUserRef.push().updateChildren(map);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
} else {
//not signed in
Toast.makeText(getApplicationContext(), "SIGN IN FAILED", Toast.LENGTH_LONG).show();
return;
}
} else {
// Sign in failed
if (response == null) {
// User pressed back button
Toast.makeText(getApplicationContext(), "SIGN IN CANCELLED", Toast.LENGTH_LONG).show();
return;
}
if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
Toast.makeText(getApplicationContext(), "NO INTERNET CONNECTION", Toast.LENGTH_LONG).show();
return;
}
if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
Toast.makeText(getApplicationContext(), "UNKNOWN ERROR", Toast.LENGTH_LONG).show();
return;
}
}
}
}
}
EDIT: I have added the complete activity
EDIT: My log is running very quickly and then the error is automatically deleting before I can read it, it might actually be a StackOverflow.

The error code is only valid if an error actually occurred by checking the onActivityResult result code, otherwise it just returns -1 (Activity.RESULT_OK) as you've noticed. Here's an example from the sample:
private void handleSignInResponse(int resultCode, Intent data) {
IdpResponse response = IdpResponse.fromResultIntent(data);
// Successfully signed in
if (resultCode == RESULT_OK) {
startSignedInActivity(response);
finish();
} else {
// Sign in failed
if (response == null) {
// User pressed back button
showSnackbar(R.string.sign_in_cancelled);
return;
}
if (response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) {
showSnackbar(R.string.no_internet_connection);
return;
}
showSnackbar(R.string.unknown_error);
Log.e(TAG, "Sign-in error: ", response.getError());
}
}

Related

Unable to continue after cropping a image in CropActivity

I am using ArthurHub's library to crop a image and put it in a ImageButton or ImageView.
Crop Activity starts smoothly but after cropping when I clicks to CROP button, my app reruns and opens MainActivity.
It seems to me that there is no error in the code and also I have checked it 5-6 times.
Thanks!!!
Here is my code...
public class AddActivity extends AppCompatActivity {
private ImageButton add_image_button;
private Uri imageUri;
private String imageUrl;
private String recordPermission = Manifest.permission.RECORD_AUDIO;
private String readExternalStorage = Manifest.permission.READ_EXTERNAL_STORAGE;
private String recordFile;
private int PERMISSION_CODE = 7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
add_image_button = findViewById(R.id.add_image_button);
CropImage.activity(imageUri).start(AddActivity.this);
add_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkReadExternalStoragePermissions();
CropImage.activity(imageUri).start(AddActivity.this);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUri = result.getUri();
add_audio_button.setImageURI(imageUri);
}else {
Toast.makeText(this, "Try again...", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AddActivity.this, MainActivity.class));
finish();
}
}
private boolean checkRecordPermissions() {
if (ActivityCompat.checkSelfPermission(this, recordPermission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{recordPermission}, PERMISSION_CODE);
return false;
}
}
private boolean checkReadExternalStoragePermissions() {
if (ActivityCompat.checkSelfPermission(this, readExternalStorage) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{readExternalStorage}, PERMISSION_CODE);
return false;
}
}
}
implementation 'com.github.Drjacky:ImagePicker:1.8.4'
use this library it is one of best for imagePicker
it will be give functionality like
1)crop
2)zoom
3)rotate
I have found out the error, there was a slight mistake in the code.
I used add_audio_button.setImageUri(imageUri) instead of add_image_button.setImageUri(imageUri); here:
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUri = result.getUri();
add_audio_button.setImageURI(imageUri);

what to use insead of requestCode

hello i am trying to make a todo list and i have 2 activities ,i want to open the new activity in two ways
one way is to press the button and the other the recyclerView and they open the same activity but in the first you just add and in the second you update
before you could just insert the requestCode together with the intent like this :
Intent i = new Intent(this, ActivityTwo.class);
startActivityForResult(i, REQUEST_CODE);
but now that startActivityForResult is deprecated i dont't know how to do it
and i searched a lot
Hre is my code until now :
eActivityResultLauncher<Intent> mGetContent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
int id=data.getIntExtra(AddEditNoteActivity.EXTRA_ID,-1);
if(id == -1){
Toast.makeText(MainActivity.this, "Note can't be updated", Toast.LENGTH_SHORT).show();
return;
}
String title=data.getStringExtra(AddEditNoteActivity.EXTRA_TITLE);
String description = data.getStringExtra(AddEditNoteActivity.EXTRA_DESCRIPTION);
int priority = data.getIntExtra(AddEditNoteActivity.EXTRA_PRIORITY, 1);
Note note = new Note(title, description, priority);
noteViewModel.insert(note);
Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "Note not saved", Toast.LENGTH_SHORT).show();
}
}
}
);
and here is what i want to do
ActivityResultLauncher<Intent> mGetContent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// action if button is clicked
}else if() {
//action if recycledView is clicked
}
}
}
);

How can i store credentials from google sign in in firebase authentication to be used for future logins

i created a standard login and signup page and i added an alternative to sign in with a google account using the custom GogleSignInButton.
The button works welll. am able to select a google account and sign in but the credentials do not reflect in the firebase authentication console nor does it bring up the signup activity for new users like it does when using the standard firebase UI.
I already have a working login with email and password(if it helps).
I would like help in immplementing the storage of credentials and signing up new users with google accounts.
From the image below you can see there are no gmail accounts
SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
GoogleSignInOptions gso = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this,
MainActivity.class));
finish();
}
signInButton.setOnClickListener(this);
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_button:
signIn();
break;
}
}
#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);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
startActivity(new Intent(LoginActivity.this,MainActivity.class));
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
Toast.makeText(this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onStart() {
// Check if user is signed in (non-null) and update UI accordingly.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if(account != null) {
startActivity(new Intent(LoginActivity.this,MainActivity.class));
}
super.onStart();
}

Email verification for Firebase Auth UI

I am using firebase auth UI (FirebaseUI-Android) in an android app, where the user can signup with personal email, Facebook, number and Gmail accounts. My question is I need to get email verification when user sign's up with his personal email id.
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(true)
.setTheme(R.style.GreenTheme)
.setTosUrl("https://termsfeed.com/blog/terms-conditions-mobile-apps/")
.setPrivacyPolicyUrl("https://superapp.example.com/privacy-policy.html")
.setAvailableProviders(providers)
.build(),
RC_SIGN_IN);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// RC_SIGN_IN is the request code you passed into startActivityForResult(...) when starting the sign in flow.
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
// Successfully signed in
if (resultCode == RESULT_OK) {
startActivity(new Intent(Login.this,MainActivity.class));
finish();
return;
} else {
// Sign in failed
if (response == null) {
Toasty.error(getApplicationContext(),"Sign in cancelled",Toast.LENGTH_SHORT, true).show();
return;
}
if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
Toasty.error(getApplicationContext(),"No internet connection",Toast.LENGTH_SHORT, true).show();
return;
}
if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
Toasty.error(getApplicationContext(),"Unkown Error",Toast.LENGTH_SHORT, true).show();
return;
}
}
Toasty.error(getApplicationContext(),"Unknown sign in response",Toast.LENGTH_SHORT, true).show();
}
}
Here is my intent for sign up options.
You can simply do it as follows,
Get Current Firebase User Instance,
final FirebaseUser currentUser = mAuth.getCurrentUser();
Check if the provider is password indicating that the login method used is Email Auth,
if(null != currentUser) {
if("password".equals(currentUser.getProviderData().get(0).getProviderId())) {
/* Handle Verification */
}
}
Reference Link: https://firebase.google.com/docs/reference/android/com/google/firebase/auth/EmailAuthProvider#PROVIDER_ID
Check if user is already verified,
currentUser.isEmailVerified();
If user is not verified then the following code can be used to send a verification EMail,
if (!currentUser.isEmailVerified()) {
/* Do Something */
}
/* Send Verification Email */
currentUser.sendEmailVerification()
.addOnCompleteListener(this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
/* Check Success */
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(),
"Verification Email Sent To: " + currentUser.getEmail(),
Toast.LENGTH_SHORT).show();
} else {
Log.e(TAG, "sendEmailVerification", task.getException());
Toast.makeText(getApplicationContext(),
"Failed To Send Verification Email!",
Toast.LENGTH_SHORT).show();
}
}
});
Once you have all the pieces in place, the final code snippet should look something like below:
Final Code Snippet:
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
/* Success */
if (resultCode == RESULT_OK) {
final FirebaseUser currentUser = mAuth.getCurrentUser();
if(null != currentUser) {
if("password".equals(currentUser.getProviderData().get(0).getProviderId())) {
if(!currentUser.isEmailVerified()) {
/* Send Verification Email */
currentUser.sendEmailVerification()
.addOnCompleteListener(this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
/* Check Success */
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(),
"Verification Email Sent To: " + currentUser.getEmail(),
Toast.LENGTH_SHORT).show();
} else {
Log.e(TAG, "sendEmailVerification", task.getException());
Toast.makeText(getApplicationContext(),
"Failed To Send Verification Email!",
Toast.LENGTH_SHORT).show();
}
}
});
/* Handle Case When Email Not Verified */
}
}
/* Login Success */
startActivity(new Intent(Login.this, MainActivity.class));
finish();
return;
}
} else {
/* Handle Failure */
}
}
#user2004685 answer above gives very good hint. But it does not work at least for the latest firebase-ui because currentUser.getProviderData().get(0).getProviderId() returns 'firebase'.
So the updated solution is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
/* Success */
if (resultCode == RESULT_OK) {
final FirebaseUser currentUser = mAuth.getCurrentUser();
if(null != currentUser) {
if(currentUser.getEmail()!=null) {
if(!currentUser.isEmailVerified()) {
/* Send Verification Email */
currentUser.sendEmailVerification()
.addOnCompleteListener(this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
/* Check Success */
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(),
"Verification Email Sent To: " + currentUser.getEmail(),
Toast.LENGTH_SHORT).show();
} else {
Log.e(TAG, "sendEmailVerification", task.getException());
Toast.makeText(getApplicationContext(),
"Failed To Send Verification Email!",
Toast.LENGTH_SHORT).show();
}
}
});
/* Handle Case When Email Not Verified */
}
}
/* Login Success */
startActivity(new Intent(Login.this, MainActivity.class));
finish();
return;
}
} else {
/* Handle Failure */
}
}
}
simply replace if("password".equals(currentUser.getProviderData().get(0).getProviderId())) with if(currentUser.getEmail()!=null)

android - Google places opens the map on closes after 1 sec

Im creating an intent to an activity by clicking on a button which should open google places, but it closes again really fast and says no location selected, and returns to the main activity, and then nothing happens if i click again.
My api should be fine, I have checked that it's the correct SHA1-fingerprint thats connected to the api key.
The result code is 2
It worked earlier in the activity before this one, but I needed it to open when i click on a button instead, and now when I try to open this new activity as an intent it wont work.
public class MapActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
GooglePlayServicesUtil.getErrorDialog(status, this,
100).show();
}
}
if (status == ConnectionResult.SUCCESS) {
int PLACE_PICKER_REQUEST = 199;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Context context = this;
try {
startActivityForResult(builder.build(context), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Result code: " + resultCode);
System.out.println("Request code: " + requestCode);
if (requestCode == 100) {
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
}
if (requestCode == 199) {
//process Intent......
if (data != null) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
} else {
String toastMsg = ("No location selected.");
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
}
This is from the intent which create the new intent to maps
public void onClick(View view) {
Intent i = new Intent(this, MapActivity.class);
startActivity(i);
}
I think its happening because of you are using old method of getPlace
try to swap the arguments, by changing it from:
Place place = PlacePicker.getPlace(data, this);
to
Place place = PlacePicker.getPlace(getContext(), data);
Update #2
Enable Google places API in the developer console and add these lines to AndroidManifest
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="ADD_YOUR_API_KEY_HERE" />
Update #3
after some search, it looks like there is others having same issue. Look at these links:
https://github.com/zhangtaii/react-native-google-place-picker/issues/21
https://stackoverflow.com/a/32751164/
https://github.com/googlesamples/android-play-places/issues/13

Categories

Resources