我如何将用户详细信息存储为会话 [英] How do i store the user details as session

查看:28
本文介绍了我如何将用户详细信息存储为会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用 dynamodb,我想知道如何在用户登录时保持会话.

Hello i am using dynamodb and i want to know how do i maintain a session when the user logs in.

以下是我的登录代码

  Runnable runnable = new Runnable() {
        public void run() {
            Users user = mapper.load(Users.class,username);

            System.out.println(user.getPassword());
            System.out.println(username);
            if (user != null && user.getPassword().equals(password)){
                //System.out.println("Correct");
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        setContentView(R.layout.activity_account);
                    }
                });
            }

这是我设置和获取所有实体的用户类

and this is my user class where i set and get all entities

public class Users {

private String id;
private String email;
private String username;
private String password;
private String role;


@DynamoDBHashKey(attributeName = "id")
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@DynamoDBAttribute(attributeName = "email")
public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

同样适用于所有其他变量.

same goes for all other variables as well.

请查看这些代码并告诉我如何存储会话,因为我需要登录用户的 ID.

Please look at these codes and tell me how i could store sessions as i want the id of the logged in user.

推荐答案

V1

你可以像下面这样使用 SharedPreferences

you can use SharedPreferences like below

public class Prefs {

public static void putPref(String key, String value, Context context){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getPref(String key, Context context) {
    SharedPreferences preferences =   PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
 }
}

在你必须存储之后

 Prefs.putPref("the key","the value",your context);

在获取您存储的数据之后

after to get your stored data

   String userId = Prefs.getPref("the key",your context);

你可以在你的应用程序中使用它.

you can use that where you want in your App .

V2

使用 Gson将此添加到您的 build.gradle

use Gson add this to your build.gradle

  compile 'com.google.code.gson:gson:1.7.2'

并像这样将您的用户对象转换为 json

and convert your user object to json like this

 Gson gson = new Gson();

 User user = ...; 
 String json = gson.toJson(user);

存储您的用户后

 Prefs.putPref("user",json,your context);

获取您的用户

 String json = = Prefs.getPref("user",your context);

 User user = null;
 if(json != null)
 user = gson.fromJson(json,User.class);

就这些

这篇关于我如何将用户详细信息存储为会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆