Anjali Patel
Anjali Patel

Reputation: 825

How to store the token in Local or session storage in android?

I'm creating an app that interacts with SOAP web-services to get data from the database. When the user successfully logins it generates a token via web-services. This token will be needed later on in other activities to call web-service methods. My question is, how can I pass on that token to the next activity when its needed and maintain it until the user logs out.

MainActivity.java

SharedPreferences preferences=getApplicationContext().getSharedPreferences("YourSessionName", MODE_PRIVATE); SharedPreferences.Editor editor=preferences.edit(); editor.putString("name",AIMSvalue);

                    editor.commit();

OtherActivity.java

    SharedPreferences preferences=getSharedPreferences("YourSessionName", MODE_PRIVATE);
    SharedPreferences.Editor editor=preferences.edit();

    token=preferences.getString("name","");

    editor.commit();

Upvotes: 3

Views: 3352

Answers (1)

Kush Patel
Kush Patel

Reputation: 1251

public class CommonUtilities {

    private static SharedPreferences.Editor editor;
    private static SharedPreferences sharedPreferences;
    private static Context mContext;

/**
     * Create SharedPreference and SharedPreferecne Editor for Context
     *
     * @param context
     */
    private static void createSharedPreferenceEditor(Context context) {
        try {
            if (context != null) {
                mContext = context;
            } else {
                mContext = ApplicationStore.getContext();
            }
            sharedPreferences = context.getSharedPreferences(IConstants.SAMPLE_PREF, Context.MODE_PRIVATE);
            editor = sharedPreferences.edit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

/**
 * Put String in SharedPreference Editor
 *
 * @param context
 * @param key
 * @param value
 */
public static void putPrefString(Context context, String key, String value) {
    try {
        createSharedPreferenceEditor(context);
        editor.putString(key, value);
        editor.commit();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

}

Use this putString() method to store a token when you logged in. And remove that token when you logged out or token expires.

Upvotes: 1

Related Questions