【问题标题】:Store Access Token in Android Local Storage?在 Android 本地存储中存储访问令牌?
【发布时间】:2017-02-17 09:48:32
【问题描述】:

我无法在 SharedPreferences 中存储访问令牌、用户名。如何完成?

登录类

   public class Login extends AppCompatActivity implements View.OnClickListener {


EditText userName, Password;
Button login;
public static final String LOGIN_URL = "http://192.168.100.5:84/Token";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_PASSWORD = "Password";
String username, password, accesstoken, tokentype;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    userName = (EditText) findViewById(R.id.login_name);
    Password = (EditText) findViewById(R.id.login_password);
    userName.setHint(Html.fromHtml("<font color='#008b8b' style='italic'>Username</font>"));
    Password.setHint(Html.fromHtml("<font color='#008b8b'>Password</font>"));
    login = (Button) findViewById(R.id.login);
    login.setOnClickListener(this);
}

private void UserLogin() {

    username = userName.getText().toString().trim();
    password = Password.getText().toString().trim();


    StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        accesstoken = jsonObject.getString("access_token");
                        tokentype = jsonObject.getString("token_type");
                        SessionManagement session = new SessionManagement(Login.this);
                        session.createLoginSession(accesstoken);
                        openProfile();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {


        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            //  params.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            return params;
        }


        @Override
        protected Map<String, String> getParams() {
            Map<String, String> map = new HashMap<String, String>();
            map.put(KEY_USERNAME, username);
            map.put(KEY_PASSWORD, password);
            map.put("grant_type", "password");
            return map;
        }
    };


    stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}


private void openProfile() {
    Intent intent = new Intent(this, Home.class);
    intent.putExtra(KEY_USERNAME, username);
    startActivity(intent);
}

@Override
public void onClick(View v) {


    UserLogin();
}

}

会话管理类

   public class SessionManagement {
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static final String PREF_NAME = "AndroidHivePref";


    private static final String IS_LOGIN = "IsLoggedIn";


    public static final String KEY_USERNAME = "UserName";

    public static final String KEY_access_token = "access_token";
    public static final String KEY_TOKEN_TYPE = "token_type";
    public static final String KEY_MASTER_ID = "MasterID";
    public static final String KEY_NAME = "Name";
    public static final String KEY_Access = "Name";


    // Constructor
    public SessionManagement(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    /**
     * Create login session
     */
    public void createLoginSession(String username, String accesstoken, String tokentype, String masterid, String name, Integer access) {
        // Storing login value as TRUE
        editor.putBoolean(IS_LOGIN, true);
        editor.putString(KEY_USERNAME, username);
        // Storing name in pref
        editor.putString(KEY_access_token, accesstoken);

        // Storing email in pref
        editor.putString(KEY_TOKEN_TYPE, tokentype);

        editor.putString(KEY_MASTER_ID, masterid);
        editor.putString(KEY_TOKEN_TYPE, tokentype);
        editor.putString(KEY_NAME, name);
        editor.putInt(KEY_Access, access);


        // commit changes


        String user_name_new = pref.getString(KEY_USERNAME, null);

        Log.d("TAG", "Pass user name :" + username + " user_name_new:" + user_name_new);
        editor.commit();

    }

    /**
     * Check login method wil check user login status
     * If false it will redirect user to login page
     * Else won't do anything
     */
    public void checkLogin() {
        // Check login status
        if (!this.isLoggedIn()) {
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, Login.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);
        }

    }


    /**
     * Get stored session data
     */
    public HashMap<String, String> getUserDetails() {
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        user.put(KEY_USERNAME, pref.getString(KEY_USERNAME, null));
        user.put(KEY_access_token, pref.getString(KEY_access_token, null));

        user.put(KEY_TOKEN_TYPE, pref.getString(KEY_TOKEN_TYPE, null));
        user.put(KEY_MASTER_ID, pref.getString(KEY_MASTER_ID, null));
        user.put(KEY_access_token, pref.getString(KEY_access_token, null));
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));
        user.put(KEY_Access, pref.getString(KEY_Access, null));


        // return user
        return user;
    }

    /**
     * Clear session details
     */
    public void logoutUser() {

        editor.clear();
        editor.commit();

        // After logout redirect user to Loing Activity
        Intent i = new Intent(_context, Login.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }

    /**
     * Quick check for login
     **/
    // Get Login State
    public boolean isLoggedIn() {
        return pref.getBoolean(IS_LOGIN, false);
    }

}

如何在 LOGin CLass 中使用 SessionManagement 类来本地存储信息??

【问题讨论】:

  • 到目前为止你尝试了什么?您面临的问题是什么?
  • 我已经创建了会话管理类,但不知道如何在登录类中使用它
  • 创建SessionManagement类的对象,必要时调用相应的方法。
  • 您没有更新或设置accesstoken 变量的值(来自响应数据),应首先在onResponse 内完成
  • 你能不能给一些代码sn-p。

标签: android session android-volley token shared


【解决方案1】:

试试这个,

    if (response.trim().equals("success")) {

        //add these 2 lines
        SessionManagement session=new SessionManagement(Login.this);
        session.createLoginSession(username, accesstoken,tokentype, masterid,name, access);

        openProfile();
    } else {
        Toast.makeText(Login.this, response, Toast.LENGTH_LONG).show();
    }

编辑您的 createLoginSession 函数:

 /**
 * Create login session
 * */
public void createLoginSession(String username, String accesstoken,String tokentype, String masterid,String name, Integer access){
    // Storing login value as TRUE


    editor.putBoolean(IS_LOGIN, true);
    editor.putString(KEY_USERNAME, username);
    // Storing name in pref
    editor.putString(KEY_access_token, accesstoken);

    // Storing email in pref
    editor.putString(KEY_TOKEN_TYPE, tokentype);

    editor.putString(KEY_MASTER_ID, masterid);
    editor.putString(KEY_TOKEN_TYPE, tokentype);
    editor.putString(KEY_NAME, name);
    editor.putInt(KEY_Access, access);




    // commit changes
    editor.commit();


    String user_name_new=pref.getString(KEY_USERNAME, null)

    Log.d("TAG","Pass user name :"+username+" user_name_new:"+user_name_new);
}

【讨论】:

  • 您的 createLoginSession 是否被调用。?添加日志并打印 createLoginSession 中的所有值并检查您是否获得所有值
  • 我已经编辑 createLoginSession 函数按原样使用并检查日志值 Pass user name & user_name_new in logcat
  • 意味着您的值存储在 SharedPreferences 中,那么有什么问题?
  • 对不起,用户名没有打印在日志中
  • 表示您的 onResponse 方法未在登录活动中调用。检查您的响应。发布您的更新代码
【解决方案2】:

您可以使用共享偏好来保存登录详细信息/访问令牌。请通过代码sn-p。

public class Preferences {
public static void setAccessToken(@NonNull Context context, String token) {
    SharedPreferences sharedPreferences = context.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("ACCESSTOKEN", token);
    editor.apply();
}

public static String getAccessToken(@NonNull Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE);
    return sharedPreferences.getString("ACCESSTOKEN", null);
}}

同样,您可以将用户名和密码存储到共享首选项中,并根据需要检索它们。

【讨论】:

  • 在Login类的哪里实例化这个类?
  • 您不必实例化该类,因为方法是静态的,您可以直接访问。登录api成功后,可以保存来自服务器的令牌和用户名/密码。
  • 我必须在哪里使用 Preferences 类。,在登录类中?
  • onResponse() 内部
【解决方案3】:

按照这些步骤将任何类型的数据保存在本地存储中都可以完美运行,因为这是我的应用程序的运行代码。

  1. 首先在应用程序类中创建应用程序的静态实例。在这个应用程序类中创建 PreferenceManager 类的静态实例,所有操作都将在其中完成。
public class MyApp extends Application {

public static MyApp myApp ;
public static MyPreferenceManager myPreferenceManager;

@Override
public void onCreate() {
    super.onCreate();

    myApp = this;

  }

/*For creating the context of the Whole app.*/
public static MyApp getInstance() {
    return myApp ;
}

/*This is for getting the instance of the MyPreferenceManager class using the context of MyApp App.*/
public static MyPreferenceManager getPreferenceManager() {
    if (myPreferenceManager == null) {
        myPreferenceManager = new MyPreferenceManager(getInstance());
    }

    return myPreferenceManager;
}

}
  1. 现在您的 MyPreferenceManager 类的代码:
public class MyPreferenceManager {

Context context;

SharedPreferences sharedPreferences;

SharedPreferences.Editor editor;

private static final String PREF_NAME = "com.example.App";

public static final String KEY_ID = "id";
public static final String KEY_ACCESS_TOKEN = "access_token";

public MyPreferenceManager(Context context) {

    this.context = context;

    sharedPreferences = context.getSharedPreferences(PREF_NAME,   Context.MODE_PRIVATE);

    editor = sharedPreferences.edit();

    editor.apply();

}

public void putString(String key, String value) {

    editor.putString(key, value);

    editor.apply();

}

public String getString(String key) {

    return sharedPreferences.getString(key, null);

}

//Method to clear the login data of the application.
public void clearLoginData() {

    editor.remove(KEY_ID);
    editor.remove(KEY_ACCESS_TOKEN);
    editor.apply();

}

}
  1. 现在,您可以从任何地方通过以下代码将数据保存到本地存储。
MyApp.getInstance().getPreferenceManager().putString(MyPreferenceManager.KEY_ID, "1");
MyApp.getInstance().getPreferenceManager().putString(MyPreferenceManager.KEY_ACCESS_TOKEN, "oihfodfdshfhfoifhoifh3393");
  1. 现在,您可以从任何地方通过以下代码从本地存储中获取数据。
String id = MyApp.getInstance().getPreferenceManager().getString(MyPreferenceManager.KEY_ID);
String accessToken = MyApp.getInstance().getPreferenceManager().getString(MyPreferenceManager.KEY_ACCESS_TOKEN);

谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-02
    • 2012-09-11
    • 2021-04-12
    • 2016-07-23
    • 2019-03-24
    • 2019-11-16
    • 2012-07-18
    • 2020-11-26
    相关资源
    最近更新 更多