JPJens
JPJens

Reputation: 1205

Read Firebase token in Fragment or Activity

I have implemented Firebase using this code and I'm able to see the refresh token in logcat.

I am trying to store the token so that I can use it in a Fragment

private void sendRegistrationToServer(String token) {
 PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("regToken", token).commit();  
}

When I try to read it in my Fragment, where I will send the token to a server, I'm unable to read it:

PreferenceManager.getDefaultSharedPreferences(context).getString("regToken", "false"); 

Unfortunately, it fails to read regToken and returns false once the Fragment is invoked.

How can I read the stored value from MyFirebaseInstanceIDService in my Fragment? I suspect the issue is with "different context's". If so, how can I use "the same" context when storing/reading.

Upvotes: 1

Views: 1271

Answers (3)

Arthur Thompson
Arthur Thompson

Reputation: 9225

The FirebaseInstanceId class provides a singleton that you can use anywhere to retrieve the current token.

FirebaseInstanceId.getInstance().getToken();

Calling that in your Fragment where you are doing the sending to your server should work.

Upvotes: 3

JPJens
JPJens

Reputation: 1205

I found that there was some delay to get the refresh token, and therefore when i was trying to read the sharedpreferences, it was not yet written to.

By creating a small delay, I can now successfully read the token:

    new android.os.Handler().postDelayed(
            new Runnable() {
                public void run() {
                    String savedToken = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getString("pushToken", "false");
                    Log.e("SAVED", savedToken);
                }
            },
            3000);

Upvotes: 0

Hya
Hya

Reputation: 199

Create an Application Class

public class MyApplication extends Application {
    public String Token;
}

Use this code to store the token

((MyApplication) getApplicationContext()).Token = "Your Token";

and this piece of code to retrieve it back

String token  =  ((MyApplication) getApplicationContext()).Token

don't forget to add the Application class in AndroidManifist file like

<application
        android:name=".MyApplication"

and also you can change the Token Property of the MyAppliction class to private and use getters and setters to access this.

Upvotes: 0

Related Questions