2017-04-14 34 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

它确实奏效,谢谢。 –