Android Innerclass异步任务静态还是按WeakReference?
我有一个关于android中这种简单的频繁发生的情况的问题 我有一个活动将调用异步任务,异步任务将从SQLite数据库中提取值并在UI上更新。我使用异步任务使UI响应迅速 这是我一直在研究的代码Android Innerclass异步任务静态还是按WeakReference?,android,android-asynctask,static,inner-classes,weak-references,Android,Android Asynctask,Static,Inner Classes,Weak References,我有一个关于android中这种简单的频繁发生的情况的问题 我有一个活动将调用异步任务,异步任务将从SQLite数据库中提取值并在UI上更新。我使用异步任务使UI响应迅速 这是我一直在研究的代码 SqlHandler sqlHandler; @BindView(R.id.list) ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedI
SqlHandler sqlHandler;
@BindView(R.id.list) ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
ButterKnife.bind(this);
sqlHandler = new SqlHandler(this);
new DisplayAll(this).execute();
listView.setOnItemClickListener((AdapterView<?> parent, View view,
int position, long id) -> {
Intent i = new Intent(getApplicationContext(), Activity2.class);
String text = textView.getText().toString();
startActivity(i);
});
}
private class DisplayAll extends AsyncTask<Void, Void, Void> {
int null_val;
final ArrayList<listRow=> myList = new ArrayList<>();
private WeakReference<Activity> mActivity;
public DisplayAll(Activity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
protected Void doInBackground(Void... params) {
myList.clear();
String query = " ...";
Cursor c1 =sqlHandler.selectQuery(query);
if (c1 != null && c1.getCount() != 0) {
if (c1.moveToFirst()) {
do {
.....
} while (c1.moveToNext());
}
}
try {
null_val = Objects.requireNonNull(c1).getCount();
c1.close();
}
catch (NullPointerException e)
{
Log.e("NPE", "" + e);
}
return null;
}
@Override
protected void onPostExecute(Void param) {
// get a reference to the activity if it is still there
Activity activity = mActivity.get();
if (activity == null || activity.isFinishing()) return;
ProgressBar prgBar=findViewById(R.id.prgbar);
listAdapter Adapter;
prgBar.setVisibility(View.GONE);
Adapter = new listAdapter(getApplicationContext(), myList);
listView.setAdapter(Adapter);
}
}
SqlHandler-SqlHandler;
@BindView(R.id.list)ListView ListView;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
把(这个)绑起来;
sqlHandler=新的sqlHandler(此);
新建DisplayAll(this.execute();
setOnItemClickListener((AdapterView父级,视图,
整数位置,长id)->{
Intent i=新的Intent(getApplicationContext(),Activity2.class);
String text=textView.getText().toString();
星触觉(i);
});
}
私有类DisplayAll扩展异步任务{
int null_val;
最终ArrayList myList=新ArrayList();
私人WeakReference问题。我现在已经将弱引用添加到我的类中。但是Android Studio仍然警告我内存泄漏
我试图将其更改为静态,但将sqlhandler更改为静态也会导致内存泄漏。将异步任务更改为顶级类对我不好。我在不同的活动中有许多异步任务
有人知道如何解决这个问题吗?这回答了你的问题吗?@Saswata实际上我在异步任务中没有使用任何上下文。我尝试了weakreference。你可以在代码中看到。但它仍然表示内存泄漏的可能性。嗨,你正在使用一个包含上下文的活动,该上下文将产生内存泄漏警告。