Converting runOnUiThread to AsyncTask

不打扰是莪最后的温柔 提交于 2019-12-25 08:35:24

问题


I read in some links that i need to convert my runOnUiThread to AsyncTask: Android: RunOnUiThread vs AsyncTask

But I am unable to get it done. I am implementing an AutoCompleteText which takes query from a database.

My runOnUiThread along with the new thread (it compiles):

new Thread(new Runnable() {
        public void run() {
            final DataBaseHelper dbHelper = new DataBaseHelper(ActivityName.this);
            dbHelper.openDataBase();
            item_list = dbHelper.getAllItemNames();

            ActivityName.this.runOnUiThread(new Runnable() {

                public void run() {
                    ArrayAdapter<String> sAdapter = new ArrayAdapter<String>(
                            ActivityName.this,
                            android.R.layout.simple_dropdown_item_1line,
                            item_list);
                    itemNameAct = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView_item_name);
                    itemNameAct.setAdapter(sAdapter);

                }
            });

        }
    }).start();

I put the worker thread part in doInBackground and the runOnUiThread part of code in onPostExecute but it crashes on launch.


回答1:


This is awkward. I asked a question and am answering it myself :/ Actually I was trying AsyncTask(Object, Void, Cursor) and it was not doing me any good.

Here is the class which is working:

class autoComplete extends AsyncTask<Void, Void, Void> {
    final DataBaseHelper dbHelper = new DataBaseHelper(ActivityName.this);

    @Override
    protected Void doInBackground(Void... params) {

        dbHelper.openDataBase();
        item_list = dbHelper.getAllItemNames();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ArrayAdapter<String> sAdapter = new ArrayAdapter<String>(
                ClassName.this, android.R.layout.simple_dropdown_item_1line,
                item_list);
        itemNameAct= (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView_item_name);
        itemNameAct.setAdapter(sAdapter);
    }

}

and then in onCreate i initialize it as:

new autoComplete().execute();


来源:https://stackoverflow.com/questions/14291215/converting-runonuithread-to-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!