2016-08-24 18 views
0

你好,我是用dynamodb,我想知道如何維護會話時英寸如何存儲用戶的細節作爲會話

用戶登錄以下是我的登錄代碼

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

這是我的用戶類,我設置並獲取所有實體

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; 
} 

對於所有其他變量也是如此。

請看看這些代碼,並告訴我如何我可以存儲會議,因爲我想登錄的用戶的ID。

+0

請參閱本http://stackoverflow.com/questions/23024831/android-shared-preferences-example – vinoth12594

+0

是的,共享的偏好將是你的好問題,上面的鏈接很好,跟着它 –

回答

2

V1

可以使用SharedPreferences像下面

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

後能得到你的存儲數據後

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

你可以在你的應用程序中使用它。

V2

使用GSON 添加到您的build.gradle

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

和用戶對象轉換成JSON這樣

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

多數民衆贊成