内部类AsyncTask静态还是通过WeakReference?

问题描述 投票:0回答:1

我对android中这种简单的经常发生的情况有疑问。

我有一个活动将调用异步任务,并且异步任务将从SQLite数据库中提取值并在UI上进行更新。我使用Async任务使UI响应迅速。

这是我一直在努力的代码。

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);

    }
}

我现在在班上添加了薄弱的参考。但是Android Studio仍然会警告我有关内存泄漏的信息。我试图将其更改为静态,但是将sqlhandler更改为静态也会导致内存泄漏。将异步任务更改为顶级类对我不利。我在不同的活动中有许多异步任务。

所以有人知道如何解决吗?

android android-asynctask static inner-classes weak-references
1个回答
0
投票

尝试使用单例数据/对象持有者,例如:

/* Holder.java file */
class Holder{
   /* Implement singleton ability*/
   MyMainClass mainClass = null;
}

/* MyMainClass.java file */
class MyMainClass{
    someMethod(){
        Holder.singletonObject.mainClass = this;
    }

    class MySubClass{
        someSubMethod(){
            //Check for null
            MyMainClass mainClass = Holder.singletonObject.mainClass
            /* Use the mainClass anywhere directly as  Holder.singletonObject.mainClass*/
        }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.