1
A
回答
2
創建共享優先級,其中第一次,當用戶輸入他/她的用戶名店呢。
你可以閱讀更多關於共享偏好here
的你在如下
public class SharePref {
public static final String PREF_NAME = "chatroom.shared.pref";
public static final String PREF_KEY = "chatroom.shared.username";
public SharePref() {
}
public void save(Context context, String text) {
SharedPreferences sharePref;
SharedPreferences.Editor editor;
sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
editor = sharePref.edit();
editor.putString(PREF_KEY,text);
editor.apply();
}
public String getData(Context context) {
SharedPreferences sharePref;
String text;
sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
text = sharePref.getString(PREF_KEY,null);
return text;
}
}
現在你MainActivity
您可以檢查您是否已經存儲了用戶名用戶
裏面你onCreate()
SharePref sharePref = new SharePref();
String UserName = sharePref.getData(mContext);
if(UserName == null) {
String value = //username value;
SharePref sharePref = new SharePref();
sharePref.save(context,value);
}
else {
// you already have username do your stuff
}
希望這會有所幫助
+0
上下文和mContext都指向getApplicationContext()或其他東西嗎? –
+0
mContext是我傳遞給Shared Preference類的MainActivity的上下文 – eLemEnt
1
您可以使用共享首選項。假設你在用戶名字符串中保存用戶名。若要保存用戶名:
SharedPreferences shareit = getSharedPreferences("KEY",Context.MODE_PRIVATE);
SharedPreferences.Editor eddy = shareit.edit();
eddy.putString("AKEY", User);
eddy.commit();
而且每次用戶登錄:
SharedPreferences sharedPreferences = getContext().getSharedPreferences("KEY", Context.MODE_PRIVATE);
String getName = sharedPreferences.getString("AKEY", "");
字符串的getName將有你的用戶名的值。上面使用的「KEY」和「AKEY」是爲通過共享偏好保存的不同值賦予特殊的id。
0
SharedPreferencec prefs = getSharedPreferences("username",Context.MODE_PRIVATE);
SharedPreference.Editor editor = prefs.edit();
if (!prefs.getString("username",null)
//do the chatting
else {
//show dialog to get username
//now save it in shared preferences
editor.putString("username",username);
editor.commit();
}
相關問題
- 1. 如何讓android應用程序記住用戶數據/配置文件?
- 2. 如何讓iOS應用程序記住用戶從UIImagePickerController中選擇的圖像
- 3. 如何讓我的應用程序記住/保存我的應用程序用戶贏得我的應用程序的硬幣?
- 4. 如何讓我的android應用程序「用戶」在運行時?
- 5. iPhone應用程序記住用戶名和密碼
- 6. 如何讓jQuery在Rails應用程序中記住狀態?
- 7. 我的應用程序在用戶登錄後如何記住用戶名和密碼?
- 8. 如何讓我的頁面記住用戶的上次操作?
- 9. Android WebView-記住用戶名和密碼
- 10. 如何讓Egit記住密碼和用戶名?
- 11. 如何記住用戶名和密碼?
- 12. iPhone應用程序如何記住我的特色作品?
- 13. 記住我 - 獲取用戶名 - MVC
- 14. 在Spring Security中記住我只記住用戶名
- 15. SharedPreferences在Android應用程序記住我按鈕
- 16. 如何在WPF應用程序中實現「記住我」
- 17. 如何讓單個用戶登錄應用程序在Android的
- 18. Ionic 2應用程序:記住設備上的用戶
- 19. 如何記住用戶?
- 20. 如何讓用戶名可點擊Twitter和Facebook應用程序?
- 21. 如何不讓用戶退出我的應用程序?
- 22. 如何讓我的rails應用程序顯示url作爲用戶名?
- 23. 如何讓我的應用程序單例應用程序?
- 24. Facebook應用程序 - 如何讓我的應用程序生活?
- 25. 如何讓我的應用程序ID
- 26. 如何讓我的android應用程序NFC啓用?
- 27. 我如何讓我的Android應用程序在後臺運行
- 28. 如何讓用戶在Android上登錄應用程序?
- 29. 在Android應用程序中記住/忘記設備功能
- 30. 我如何讓用戶更改Android應用程序中的按鈕顏色
您可以將用戶登錄會話保存爲共享首選項。即在您的設備內部存儲器/內存中。 –