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

一个人想着一个人 提交于 2019-12-12 14:18:22

问题


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();

回答1:


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.



来源:https://stackoverflow.com/questions/40417124/how-to-store-the-token-in-local-or-session-storage-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!