Data of previous user is displayed after another user is signed in - java

Update
I had every activity set as SingleInstance on launch mode, which makes sense why the issue had appear. Set it as default or SingleTop and it clears out the issue.
So, I'm making an android app where there is Firebase email auth for signing in and out. There is a ProfileActivity that shows user's profile picture and other information like images, posts and etc. When that user is signed out, and another user is logged in and navigates to profileActivity, the data from the previous user appears. But if the app is closed and restarted, then everything is fine, the correct data is displayed. This sigin and signout are done simultaneously without closing the app and only then the problem seems to appear.
I've tried modifying rules in the firebase database, rechecked the signout method and didn't find any related issue.
Firebase database rules
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
sign out method
auth = FirebaseAuth.getInstance();
auth.signOut();
these methods are included too
#Override
protected void onStart() {
super.onStart();
auth.addAuthStateListener(authStateListener);
}
#Override
public void onStop(){
super.onStop();
if(authStateListener != null){
auth.removeAuthStateListener(authStateListener);
}
}

Related

How an app open custom action after install

Suppose an user wants to download a music from example.com. User goes to example.com from browser and clicks "download sample.mp3".Now instead of downloading the sample.mp3,the browser downloads an android app. When the user installs the app, the app downloads exactly the same 'sample.mp3' that the user clicked from the browser.
So, how do i make an app like this? Note: i can use download Api to download a music inside onCreate of the app without any views or anything.
But the key challenge here is to get the data that the user clicked in the browser (when my app was not even installed). Is it do-able somehow?
You can use firebase dynamic links for that.
You can pass the songId with the link and google play will pass that link into the app after installation. There you can extract the songId and start downloading the song.
One more advantage of the dynamic link is that google play will check if your app is already installed or not. If it is already installed then it will open the app directly else it will redirect to playstore page of the app.
To extract the songId in the app you can use below code:
FirebaseDynamicLinks.getInstance()
.getDynamicLink(getIntent())
.addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
// Get deep link from result (may be null if no link is found)
Uri deepLink = null;
if (pendingDynamicLinkData != null) {
deepLink = pendingDynamicLinkData.getLink();
}
// Handle the deep link. For example, open the linked
// content, or apply promotional credit to the user's
// account.
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "getDynamicLink:onFailure", e);
}
});

How to update the details of the user in Firebase Authentication

I am trying to develop an app in android studio using firebase where user verifies their email address after signup. But even after verifying the email address, whenever I open the app again, it forwards me to the send email verification code page. However, if I clear app data, the same problem does not exist.
I tried using AuthStateListener (without knowing much about it) but it did not work.
here is the code that I tried. I also tried it without the authstatelistener, but the same problem continued
mAuth=FirebaseAuth.getInstance();
user=mAuth.getCurrentUser();
authStateListener=new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(!user.isEmailVerified()){
startActivity(new Intent(HomePage.this,VerifyEmail.class));
}
}
};
It leads to the verify email page if I open it in the phone where I signed up. But after clearing the data, it does not forward me to that page.
The reason for this issue is the FirebaseUser object is cached in the app by default. That's why there is no problem when the app data is cleared. To fix this call FirebaseAuth.getCurrentUser().reload() when your app starts.
mAuth=FirebaseAuth.getInstance();
user=mAuth.getCurrentUser();
user.reload()
if(!user.isEmailVerified()){
startActivity(new Intent(HomePage.this,VerifyEmail.class));
}

Firebase authentication via microsoft - Login tab not showing

got some copy-paste code from firebaseauth tutorial to connect a client on my app with Microsoft authentication. problem is, login screen not showing
you can find the full tutorial here.
note, I did copy everything just to test connection (not including optional code, to simplify things)
the problem stats at firebaseAuth.startActivityForSignInWithProvider method. it always ends up with failure. trace show this message:
"FirebaseAuthException... There was an error while trying to get your package certificate hash."
I did everything in the tutorial including registration of my app at Microsoft and Firebase Authentication screen. I ran this code at android studio emulator and an actual device, same result
my sign in function:
public void signinToMicrosoft(Activity activity) {
OAuthProvider.Builder provider = OAuthProvider.newBuilder("microsoft.com");
Log.e(TAG,"Signing with microsoft");
Task<AuthResult> pendingResultTask = firebaseAuth.getPendingAuthResult();
if (pendingResultTask != null) {
// There's something already here! Finish the sign-in for your user.
pendingResultTask
.addOnSuccessListener(
new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Log.e(TAG,"Pending Success");
// User is signed in.
// IdP data available in
// authResult.getAdditionalUserInfo().getProfile().
// The OAuth access token can also be retrieved:
// authResult.getCredential().getAccessToken().
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG,"Pending Failed: "+e.getMessage());
// Handle failure.
}
});
} else {
Log.e(TAG,"No Pending");
// There's no pending result so you need to start the sign-in flow.
// See below.
}
firebaseAuth
.startActivityForSignInWithProvider(activity, provider.build())
.addOnSuccessListener(
new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Log.e(TAG,"Auth Success");
// User is signed in.
// IdP data available in
// authResult.getAdditionalUserInfo().getProfile().
// The OAuth access token can also be retrieved:
// authResult.getCredential().getAccessToken().
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG,"Auth Failed: "+e.getMessage() + "\nTrace: "+ e.getClass().getCanonicalName());
// Handle failure.
}
});
}
a custom chrome tab was supposed to open and allow signing to Microsoft but it pops up for a split second and closes. if anyone had that problem or got a fix for me it would be much appreciated. thanks!
If anyone still has this problem, I just want to share my solution and my problem which is similar to this.
TL;DR
Your SHA-1 Fingerprint may be used by another Firebase project so either delete that fingerprint or sign with a different keystore
Long Version
I worked on a project that has a development and production environment using different Firebase projects. We use Firebase Auth to link Microsoft login for our Android app. I got the same error as above while trying to set up the development environment of the project. We used to only have one environment for Firebase so this was never a problem.
It turns out that when you don't provide an SHA-1 fingerprint when you create the project, Firebase automatically adds them when you run an authentication call. This meant that when we created debug APKs for testing, the SHA-1 fingerprint was recorded to the Firebase project that was intended for the live environment so when you try to add the same fingerprint in another project it won't let you. The solution would be to include the SHA-1 fingerprint in the development environment but to do so you would need to delete it the fingerprint from the live environment (in my case) and wait for that change to reflect. Or you could sign with a different, unused keystore.
You need to have microsoft (hotmail, outlook ...) account on your android, to solve this problem.

Firebase connection check online offline status in Android

If user turn off both wi-fi, 3g, 4g, and so on and reverse (no internet connection). Firebase database name child connections:(true/false)
So, when internet connections, wi-fi, 3g, 4g, and so on are off or missing, the user is offline so he can't be found.
Remember the two scenarios: Before and After. If user is offline before an other user search him, then he will not displayed in the list result, if user is off-line after an other user search him, then it will display NO MORE AVAILABLE icon on the user
Kindly some one help me for this problem.
To solve this, you can create a new node in your Firebase Realtime Database to hold all online users, so when the user opens the application, you'll immediately add his id to this newly created node. Then, if you want to check if the user is online, just check if his id exists in the list.
You can also add a new property named isOnline for each user in your database and then update it accordingly.
For that, I recommend you using Firebase's built-in onDisconnect() method. It enables you to predefine an operation that will happen as soon as the client becomes disconnected.
See Firebase documentation.
You can also detect the connection state of the user. For many presence-related features, it is useful for your app to know when it is online or offline. Firebase Realtime Database provides a special location at /.info/connected which is updated every time the Firebase Realtime Database client's connection state changes. Here is an example also from the official documentation:
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("connected");
} else {
System.out.println("not connected");
}
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});
Though this is more than a year late, to clear up the confusion. Alex's question would like to implement a live chat scenario in which each user can view everyone's online status at their ends or on their devices.
A simple solution be to create a node where all users would inject their online status each. e.g.
//say your realtime database has the child `online_statuses`
DatabaseReference online_status_all_users = FirebaseDatabase.getInstance().getReference().child("online_statuses");
//on each user's device when connected they should indicate e.g. `linker` should tell everyone he's snooping around
online_status_all_users.child("#linker").setValue("online");
//also when he's not doing any snooping or if snooping goes bad he should also tell
online_status_all_users.child("#linker").onDisconnect().setValue("offline")
So if another user, say mario checks for linker from his end he can be sure some snooping around is still ongoing if linker is online i.e.
DatabaseReference online_status_all_users = FirebaseDatabase.getInstance().getReference().child("online_statuses");
online_status_all_users.child("#linker").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String snooping_status = dataSnapshot.getValue(String.class);
//mario should decide what to do with linker's snooping status here e.g.
if(snooping_status.contentEquals("online")){
//tell linker to stop doing sh*t
}else{
//tell linker to do a lot of sh****t
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

ParseUser Android indicates user is signed in but no information can be retrieved from object

I am having a Parse Starter Application on Android Studio (downloaded from the github of Parse) and I am using Heroku yo have Parse Server.
I can add collections with no problem but with the users I am having difficulties...
[JavaCode]
if(ParseUser.getCurrentUser() == null){
ParseAnonymousUtils.logIn(new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (e != null) {
Log.i("MyApp", "Anonymous login failed.");
} else {
Log.i("MyApp", "Anonymous user logged in.");
}
}
});
}
else{
//Log.i("MyApp", ParseUser.getCurrentUser().getUsername());
Log.i("MyApp", "User already logged in");
}
and in my StarterApplication file I have:
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
ParseACL.setDefaultACL(defaultACL, true);
When running, my debugger prints 'user already logged in' but if I uncomment the above line, application crashes. On the Parse dashboard, there's no 'User' class and of course no User Objects.
I have tried deploying app in a completely new emulator with no other apps installed and I still have the same problem!!! any ideas???
This code is correct as is - you are simply misunderstanding how the anonymous user works in Parse. When you put
ParseUser.enableAutomaticUser();
in your MyApplication class (which I assume is what you meant by your "StarterApplication" file), you have told Parse that you want to allow users to access your database anonymously (aka without logging in). Once you tell Parse that, Parse.getCurrentUser() will ALWAYS return a user. Straight out of Parse's documentation:
When you enable automatic anonymous user creation at application startup, ParseUser.getCurrentUser() will never be null.
So since you used ParseUser.enableAutomaticUser(), once you call Parse.getCurrentUser(), it never returns null, therefore you are seeing the printout "User already logged in." Admittedly, that user is essentially blank, but they are a user nonetheless.
Read the section in this guide on Anonymous Users for more information: https://parse.com/docs/android/guide

Categories

Resources