2014-04-04 77 views
1

這裏是我的Contacts活動(我的主要活動):SharedPreferences似乎並沒有工作

public class Contacts extends Delegate { 

    private static final String TAG = "Contacts"; 
    public View listContactsView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
     String restoredText = prefs.getString("token", null); 

     if(restoredText == null) 
     { 
      Intent intent = new Intent(this, SignIn.class); 
      startActivity(intent); 
     } 

     setContentView(R.layout.activity_contacts); 

     if (savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new ContactListFragment()).commit(); 
     } 

     //new InEventAPI(this).execute(""); 
    } 
    ... 
    ... 

這裏是我的SignIn活動:

public SignIn extends Delegate { 
    ... 
    ... 


    public void personSignInDelegate(HttpResponse response, JSONObject result) 
    { 
     if(response != null && result != null) 
     { 
      switch(response.getStatusLine().getStatusCode()) 
      { 
      case 200: 
       try { 

        SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); 
        editor.putString("token", result.get("tokenID").toString()); 
        editor.commit(); 

       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       }    
       break; 
      case 401: 
       Toast.makeText(this, R.string.toastEmailPasswordIncorrect, Toast.LENGTH_LONG).show(); 
       break; 
      } 
     } 
     else 
     { 
      Log.d(TAG, "Something went wrong!"); 
     } 
    } 

當我登錄,它承諾在SharedPreferences ,但是當我關閉我的應用程序並重新打開時,String變爲null,我的OnCreate意圖再次變爲SignIn

是我失蹤的東西?

,只是爲了避免懷疑,我Delegate類:

public class Delegate extends ActionBarActivity { 

    protected InEventAPI api; 

    public Delegate() {} 

    public void personSignInDelegate(HttpResponse response, JSONObject result) {}; 

} 

回答

2

問題是最有可能與您使用的getPreferences()。從documentation

檢索SharedPreferences對象訪問是 私人這項活動的偏好。通過傳入此活動的 類名稱作爲首選項名稱,這只是簡單地調用底層 getSharedPreferences(String,int)方法。

儘管這兩個類都擴展了Delegate類,但它們都是具有唯一名稱的唯一類。這意味着getPreferences()Contacts返回一個不同的SharedPreferenceObject與SignIn相比。

可以使用getSharedPreferences(String, int) 例如,的 代替

getPreferences(MODE_PRIVATE); 

改變它

getSharedPreferences ("OneSharedPreference", MODE_PRIVATE); 

或覆蓋DelegategetPreferences()所以它調用getSharedPreferences()一個獨特的名字。

或者,如果你不使用任何東西默認SharedPreferences(這通常被任何PreferenceActivity類),您可以隨時撥打

PreferenceManager.getDefaultSharedPreferences(),並通過在Context實例。

+0

哪一個更好? –

+1

在你的情況下,我會使用覆蓋,因爲'Delegate'是兩個活動的父類。 –