我試圖通過擴展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)'
你覺得哪個活動你得到婷?如果沒有活動會怎麼樣? –
你應該從'Context' –
我試圖通過上下文得到的喜好,並沒有工作 –