Issue
I am getting and setting sharedPreferences in a Constructor class
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();
}
However I am calling this from a Async Task (which uses a WeakReference context, to prevent memory leaks)
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";
}
Problem is that a weakreference context can't be passed as context
How do I call my constructor class with context without causing memory leaks?
Solution
You need to use the get() method on the weak reference instance to get the actual object. Something like this:
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";
}
Answered By - p.mathew13
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.