如何将活动上下文进入非活动类别的Android



我有一个活动类,从我将一些信息传递给助手类(非活动)类。在辅助类中,我想使用getSharedPreferences()。但是我无法使用它,因为它需要活动上下文。

这是我的代码:

  class myActivity extends Activity
    {
    @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.home);

            Info = new Authenticate().execute(ContentString).get();
            ItemsStore.SetItems(Info);
        }
    }
class ItemsStore
{
  public void SetItems(Information info)
 {
  SharedPreferences  localSettings = mContext.getSharedPreferences("FileName", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = localSettings.edit();
            editor.putString("Url", info.Url);
            editor.putString("Email", info.Email);
 }
}

任何想法如何实现?

而不是创建内存泄漏(通过在类字段中保存活动上下文),您可以尝试此解决方案,因为共享的偏好不需要活动上下文对象您应该使用applicationContext。

创建应用程序类:

public class MySuperAppApplication extends Application {
    private static Application instance;
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
    public static Context getContext() {
        return instance.getApplicationContext();
    }
}

在清单上注册

<application
    ...
    android:name=".MySuperAppApplication" >
    ...
</application>

然后您可以做这样的事情

public void persistItems(Information info) {
    Context context = MySuperAppApplication.getContext();
    SharedPreferences sharedPreferences = context.getSharedPreferences("urlPersistencePreferences", Context.MODE_PRIVATE);
    sharedPreferences.edit()
        .putString("Url", info.Url)
        .putString("Email", info.Email);
}

方法签名看起来更好,因为它不需要外部上下文。这可以隐藏在某个接口下。您也可以轻松地将其用于依赖注入。

hth

尝试以下:

class myActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        Info = new Authenticate().execute(ContentString).get();
        ItemsStore.SetItems(Info, getApplicationContext());
    }
}
class ItemsStore
{
   public void SetItems(Information info, Context mContext)
   {
            SharedPreferences  localSettings = mContext.getSharedPreferences("FileName",
            Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = localSettings.edit();
            editor.putString("Url", info.Url);
            editor.putString("Email", info.Email);
   }
}

您需要将上下文传递给非活动类的构造函数

ItemsStore itemstore = new ItemStore(myActivity.this);
itemstore.SetItems(Info);

然后

Context mContext;
public ItemsStore (Context context)
{
       mContext =context;
}

现在mContext可以用作活动上下文。

注意:不要长期对上下文活动的参考(对活动的引用应与活动本身具有相同的生命周期)

在您的活动中写一个公共功能。在活动类中创建助手类实例时,通过构造函数中的活动上下文。

然后,使用活动上下文中的助手类,在活动类中调用公共功能。

相关内容

最新更新