2016-07-12 57 views

回答

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(); 
} 
相關問題