本文介绍了如何通过(Android版)应用程序上下文Java类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code中,我使用的应用程序上下文检索所需信息:

I have the following code in which I am using the application context to retrieve needed information:

public class Data{
   private boolean VarA;

   public void setVarA(boolean B,Context ctx)
   {
        SharedPreferences CoreDataStorage = ctx.getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = CoreDataStorage.edit();
        editor.putBoolean("PrefVarA", VarA);
        edit.commit();
   }

}

现在我呼吁市民法setVarA()从下面的类

Now I am calling the public method setVarA() from the below class

public class MyActivity extends Activity{

    Data cd = new Data();

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

        setContentView(R.layout.registration);
        cd.setVarA(true,this);
    }
}

在上面的活动它为我的编译错误,它不能从MyActivity转换为语境。请提出解决方案。是上面code未通过上下文正确方法?

In the activity above it shows me compilation error that it can't cast from MyActivity to Context. Please suggest any solution. Is the above code is not proper way to pass the context?

推荐答案

您需要的应​​用程序上下文来访问共享preferences。它应该是:

You need the application Context to access the shared preferences. It should be:

cd.setVarA(true,this.getApplicationContext());

的onCreate MyActivity

这篇关于如何通过(Android版)应用程序上下文Java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:54