Android进度对话框未在AsyncTask中显示。被阻止的UI?

时间:2015-11-30 07:21:28

标签: android

我有一个AsyncTask,我用它来查询数据库并使用自定义游标适配器加载ListView。任务本身有效,但我无法显示进度对话框。

异步任务:

private class LoadListTaskByCursor extends AsyncTask<Void, Void, Cursor> {
    private ProgressDialog progressDialog;
    private String dictionary;
    private Activity activity;


    public LoadListTaskByCursor (Activity activity, String dictionary) {
        progressDialog = new ProgressDialog(activity);
        this.dictionary = dictionary;
        this.activity = activity;
    }

    @Override
    protected  void onPreExecute() {
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Cursor result) {
        ListView lv = (ListView) activity.findViewById(R.id.viewDictionaryList);
        lv.setFastScrollEnabled(true);

        lv.setAdapter(new CustomTermsCursorAdapter(activity,
                R.layout.custom_term_item,
                result,
                new String[]{getString(R.string.KEY_ID), getString(R.string.KEY_TERM)},
                new int[]{R.id.term_item}));

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Get the cursor, positioned to the corresponding row in the result set
                Cursor cursor = (Cursor) parent.getItemAtPosition(position);

                // Get the term id from this row in the database.
                int termId = cursor.getInt(cursor.getColumnIndexOrThrow(getString(R.string.KEY_ID)));

                Bundle bundle = new Bundle();
                bundle.putInt("id", termId);

                Fragment fragment = new ViewTermFragment();
                fragment.setArguments(bundle);
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .add(R.id.container, fragment)
                        .addToBackStack(null)
                        .commit();
            }
        });

        if(progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected Cursor doInBackground(Void... params) {
        Cursor cursor = null;
        try {
            // do the background process
            cursor = db.getAllTermListItemsByDictionaryCursor(getString(R.string.TABLE_TERMS), dictionary);
        } catch (Exception e) {
            Log.e("tag", e.getMessage());
        }

        return cursor;
    }
}

我从这个片段中调用这个任务:

 LoadListTaskByCursor loadListTaskByCursor = new LoadListTaskByCursor(getActivity(), dictionary);
 loadListTaskByCursor.execute();

我之前使用类似的方法使用自定义数组适配器而不是游标,并且工作正常。谁能告诉我我做错了什么?感谢。

1 个答案:

答案 0 :(得分:0)

事实证明,我的doInBackGround实际上运行的时间非常短(因为它只返回一个游标)而我的onPostExecute实际上花了很长时间(由于setAdapter)。进度对话框显示并消失,我甚至没有注意到。

感谢所有评论的人,我很感激。