2017-04-14 72 views
-2

我試圖通過擴展Application類來編寫全局方法。 具體地說我想要添加2方法來快速訪問存儲在SharedPreferences一個值。 可惜我不能讓SharedPreferences工作,這裏是代碼:無法訪問類中擴展的SharedPreferences應用程序

package postfixcalculator.mattiarubini.com.postfixcalculator; 

import android.app.Application; 
import android.content.Context; 
import android.content.SharedPreferences; 

public class PostfixCalculatorExtendApplication extends Application { 

    public void ChangePreference (boolean flag){ 
     //I'm updating the preference file based on the purchase 
     SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedPref.edit(); 
     editor.putBoolean(getString(R.string.purchase_status), flag); 
     editor.commit(); 
    } 

    public boolean RetrievePreferences(){ 
     SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); 
     /*If the file doesn't exist, I create the file and I'm returned with a false value. 
     * Because if the file was not created it's likely to be the first install. 
     * If the user acquired the product on the store, it will be able to restore its purchase.*/ 
     boolean flagPurchase = sharedPref.getBoolean(getString(R.string.purchase_status), false); 
     return flagPurchase; 
    } 
} 

我明白getActivity()不以Activity工作,但在Fragment,我只是不知道在做這具體案例。 通常在Activity,要使SharedPreferences的作品,我只需要使用關鍵詞this

這些都是錯誤的,我得到:)代替getActivity()

Cannot resolve method 'getActivity()'

Cannot resolve method 'getPreferences(int)'

+1

你覺得哪個活動你得到婷?如果沒有活動會怎麼樣? –

+0

你應該從'Context' –

+0

我試圖通過上下文得到的喜好,並沒有工作 –

回答

1

嘗試getApplicationContext()與getSharedPreferences()

+0

謝謝你,它解決了我的問題。 –

0

嘗試使用getApplicationContext(。

+0

它不工作,問題轉變,我得到的錯誤:無法解析法「的getPreferences(INT)」 –

1

使用

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

    SharedPreferences.Editor editor = preferences .edit(); 
    editor.putBoolean(getString(R.string.purchase_status), flag); 
    editor.commit(); 
+0

謝謝,您的解決方案確實有效,但我更傾向於使用其他解決方案。 –

+0

您的歡迎:) –

-1

試試這個保存共享偏好:

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
    sharedPreferences.edit().putString("key","value").apply(); 

爲了得到共享偏好值:

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
    sharedPreferences.getString("key",""); 

我希望這會有所幫助。

+0

它不起作用我得到的錯誤:無法解析符號'sharedPrefernces' –

+0

你必須聲明變量。 SharedPreferences sharedPreferences –

1

我在我的應用程序類中使用getSharedPreferences("Name of preferences", Context.MODE_PRIVATE);

+0

它確實奏效,謝謝。 –