用集合调用构造函数类并从asyncTask获取sharedpreferences(无法传递上下文)

我在Constructor类中获取并设置了sharedPreferences

private Context context;
public NewBusiness (Context c) {
    this.context = c;
    pref = android.preference.PreferenceManager.getDefaultSharedPreferences(getapplicationContext());
    pref = context.getSharedPreferences("MyPref",0);
    editor = pref.edit();
}
public String getLogo() {
    return pref.getString("logo",logo);
}

public void setLogo(String logo) {
    editor.putString("logo",logo);
    editor.commit();
}

但是我从异步任务(使用WeakReference上下文,以防止内存泄漏)中调用它

private WeakReference<Context> contextRef;
public UploadBusiness(Context context) {
    contextRef = new WeakReference<>(context);
}
@Override
protected String doInBackground(Void... params) {

    newBusiness = new NewBusiness(contextRef); //Can´t use WeakReference<Context>
    return "Upload successful";
}

问题是弱引用上下文不能作为上下文传递

如何在不导致内存泄漏的情况下使用上下文调用构造函数类?

iCMS 回答:用集合调用构造函数类并从asyncTask获取sharedpreferences(无法传递上下文)

您需要在弱引用实例上使用get()方法来获取实际对象。像这样:

private WeakReference<Context> contextRef;
public UploadBusiness(Context context) {
    contextRef = new WeakReference<>(context);
}
@Override
protected String doInBackground(Void... params) {

    if(contextRef.get()!=null){
        newBusiness = new NewBusiness(contextRef.get());
    } 
    return "Upload successful";
}
本文链接:https://www.f2er.com/2116565.html

大家都在问