1 year ago

#378879

test-img

ilham

How to get preferences from fragment

i am wanna get string from my preferences file to fragment activity. for the other activity i use code like this:

        String fcmToken = Preferences.getFcmToken(getBaseContext());

but in the fragment activity i can not use that. here is my preferences code fill:

public class Preferences extends Application {

static final String KEY_USER_TEREGISTER ="user", KEY_PASS_TEREGISTER ="pass";
static final String KEY_USER_TOKEN = "user_token";
static final String KEY_FCM_TOKEN = "fcm_token";

public static SharedPreferences getSharedPreference(Context context){
    return PreferenceManager.getDefaultSharedPreferences(context);
}

public static void setRegisteredUser(Context context, String username){
    SharedPreferences.Editor editor = getSharedPreference(context).edit();
    editor.putString(KEY_USER_TEREGISTER, username);
    editor.apply();
}

public static String getRegisteredUser(Context context){
    return getSharedPreference(context).getString(KEY_USER_TEREGISTER,"");
}


public static void setRegisteredPass(Context context, String password){
    SharedPreferences.Editor editor = getSharedPreference(context).edit();
    editor.putString(KEY_PASS_TEREGISTER, password);
    editor.apply();
}

public static String getRegisteredPass(Context context){
    return getSharedPreference(context).getString(KEY_PASS_TEREGISTER,"");
}

public static void setUserToken(Context context, String token){
    SharedPreferences.Editor editor = getSharedPreference(context).edit();
    editor.putString(KEY_USER_TOKEN,token);
    editor.apply();
}

public static String getUserToken(Context context){
    return getSharedPreference(context).getString(KEY_USER_TOKEN, "");
}

public static void setFcmToken(Context context, String token){
    SharedPreferences.Editor editor = getSharedPreference(context).edit();
    editor.putString(KEY_FCM_TOKEN,token);
    editor.apply();
}

public static String getFcmToken(Context context){
    return getSharedPreference(context).getString(KEY_FCM_TOKEN, "");
}

public static void clearLoggedInUser (Context context){
    SharedPreferences.Editor editor = getSharedPreference(context).edit();
    editor.clear();
    editor.commit();
}

}

can you guys please how to do in fragment activity or my preferences code must to change?

java

android

android-fragments

sharedpreferences

preferences

0 Answers

Your Answer

Accepted video resources