2013-03-03 16 views
8

忘記sharedpreferences我不知道該怎麼用它做任何更多的應用不斷重啓

似乎是工作的罰款與Android 3.0和更高版本,但是在Android 2.3.3我每次啓動應用程序是再次詢問用戶名/密碼。

我正在使用共享首選項。

這是我如何保存的喜好:

 SharedPreferences preferences = MyApplication.getAppContext().getSharedPreferences("athopbalance", MODE_PRIVATE); 
     SharedPreferences.Editor editor = preferences.edit(); 
     editor.putString("username", username).commit(); 
     editor.putString("password", password).commit(); 

這裏是我如何閱讀:

SharedPreferences preferences = MyApplication.getAppContext().getSharedPreferences("athopbalance", Context.MODE_PRIVATE); 
    String username = preferences.getString("username", ""); 
    String password = preferences.getString("password", ""); 

我也嘗試使用這段代碼保存喜好:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext()); 
     SharedPreferences.Editor editor = preferences.edit(); 
     editor.putString("username", username).commit(); 
     editor.putString("password", password).commit(); 

並閱讀它們與此代碼:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext()); 
    String username = preferences.getString("username", ""); 
    String password = preferences.getString("password", ""); 

但它也不起作用。

問題是我重新啓動應用程序之前,我可以看到他們仍然存在。然而,只要我重新啓動 - 我最終得到「」(空字符串)的用戶名和「」密碼。

任何想法,將不勝感激

回答

0

我不知道到底發生了什麼,但是在重新啓動模擬器問題後,消失了。

對不起,浪費你的時間

+0

同樣的問題在這裏,它重新啓動後就像你的一樣。真的很奇怪... – Victor 2015-07-23 19:02:08

1

試試這個:

SharedPreferences preferences = context.getSharedPreferences("YOUR_TAG", 0); 
String username = preferences.getString("username", ""); 
String password = preferences.getString("password", ""); 


    SharedPreferences.Editor editor = preferences.edit(); 
    editor.putString("username", username).commit(); 
    editor.putString("password", password).commit(); 

其中上下文是您的應用程序的情況下:

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


     context = this; 
+0

你好,非常感謝你的評論。我在第一個示例中的表現相當,但恐怕它不起作用 – 2013-03-03 07:08:17

+0

請嘗試使用您的活動而不是MyApplication。 – Gyonder 2013-03-03 07:12:16

+0

我正在調用getApplicationContext(),而不是從活動傳遞上下文。 – 2016-07-06 07:28:13

2
public class MyApplication extends Application { 
    private static MyApplication instance; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Log.d(TAG, "onCreate() called"); 
    } 

    public MyApplication() { 
     super(); 
     Log.d(TAG, "Constructor called"); 
     instance = this; 
    } 


    public static MyApplication getApplication() { 
     if (instance == null) { 
      instance = new MyApplication(); 
     } 
     return instance; 
    } 
} 

與用法:

MyApplication.getApplication().getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE) 
+0

您的示例在返回之前不會將'new MyApplication'保存到實例中,因此緩存從不發生。 – mikebabcock 2013-03-03 07:07:22

+0

謝謝,我會給它去一個 – 2013-03-03 07:12:39

+0

修復了mikebabcock指出的問題。謝謝! – agamov 2013-03-03 07:20:55