Android - AsyncTask 中未显示进度对话框 [英] Android - progressdialog not displaying in AsyncTask

查看:22
本文介绍了Android - AsyncTask 中未显示进度对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Android 应用,但遇到了问题.

I have an android app that I am having trouble with.

基本上 ProgressDialog 根本没有显示.我认为这是某种线程问题,但我不知道如何解决.

Basically the ProgressDialog is not showing at all. I believe this to be a threading issue of some sort but I don't know how to fix it.

我正在使用 ActionBarSherlock 和一些 Fragments.我还使用了新的 Android DrawerLayout,其中我在抽屉上有我的选项,单击时替换片段.

I am using ActionBarSherlock with some Fragments. I am also using the new Android DrawerLayout where I have my options on the drawer, which replace a fragment when clicked.

在我的应用程序第一次加载时,我想检查数据库以查看是否已下载初始数据.如果没有,那么我就开始执行 AsyncTask 来下载数据.这应该在此期间显示 ProgressDialog,但它没有.

On first load of my app, I want to check the database to see if the inital data has been downloaded. If not, then I go off and begin an AsyncTask to download the data. This SHOULD have a ProgressDialog display during this, but it doesnt.

有人能看到我哪里出错了吗?谢谢.

Can someone see where I am going wrong? Thanks.

MainScreen - 应用打开时的默认登陆页面/片段

MainScreen - The default landing page/fragment when the app opens

public class MainScreen extends SherlockFragment {
    public static final String TAG = "MainScreen";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_main, container, false);
        setHasOptionsMenu(false);

        ImageView imgLogo = (ImageView) rootView.findViewById(R.id.imgMainScreen);
        imgLogo.setOnClickListener(new ButtonHandler(getActivity()));

        checkDatabase();
        return rootView;
    }

    private void checkDatabase() {
        //Ensure there is data in the database
        DBHelper db = new DBHelper(this.getSherlockActivity());
        db.checkDatabase();
    }
...
}

DBHelper.checkDatabase() - 启动下载的方法

public void checkDatabase() {
    if (isEmpty()) {
        //Connect to net and download data
        NetworkManager nm = new NetworkManager(activity);
        if (!nm.downloadData()) {
            Toast.makeText(activity, R.string.internetCheck, Toast.LENGTH_SHORT).show();
        }
    }
}

最后NetworkManager.downloadData() - 启动 AsyncTask 的方法:

and finally NetworkManager.downloadData() - The method that kicks off the AsyncTask:

   public boolean downloadData() {
        try {
            return new HttpConnection(activity).execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return false;
    }

    public class HttpConnection extends AsyncTask<Void, Void, Boolean> {
        private ProgressDialog progressDialog;
        private Activity m_activity;

        protected HttpConnection(Activity activity) {
            m_activity = activity;
        }

        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(m_activity);
            progressDialog.setMessage("Wait ...");
            progressDialog.setCancelable(false);
            progressDialog.setMax(100);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();

            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            String[] types = new String[]{"type1", "type2", "type3", "type4", };
            StringBuilder sb = new StringBuilder();

            for(String type : types) {
                sb = new StringBuilder();
                if(DBHelper.TYPE4_TABLE.equals(type)) {
                    InputStream is = activity.getResources().openRawResource(R.raw.dbdata);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    try {
                        sb.append(reader.readLine());
                    } catch (IOException e) {
                        Toast.makeText(activity.getApplicationContext(), "Error retriveving data", Toast.LENGTH_SHORT).show();
                        Log.e(Constants.TAG, "Error reading data");
                        e.printStackTrace();
                    }
                } else {
                    sb = fetchURLData(Constants.ALL_URL+type);
                }
                cleanDataAndStore(sb, type);
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean result){
              progressDialog.hide();
        }
    }

使用上面的代码,当应用程序尝试加载时,我得到的只是一个白屏,有时是 ANR.下载完成后,片段加载.所以它工作正常,除了缺少 ProgressDialog.

Using the above code, all I get is a white screen as the app tries to load, and sometimes an ANR. When the download is done, the fragment loads. So it works fine except for the missing ProgressDialog.

PS,注意我在每个构造函数中设置了 activity.

PS, Notice I'm setting the activity in each constructor.

谢谢.

推荐答案

Remove .get() from return new HttpConnection(activity).execute().get(); 您基本上是在锁定您的 UI 线程.删除后,它应该可以正常工作,因为 AsyncTasks 应该可以正常工作.

Remove .get() from return new HttpConnection(activity).execute().get(); You are basically locking your UI thread. Once removed it should work as AsyncTasks are expected to work.

目的是异步,所以 boolean downloadData() 应该有一个 void 的返回类型.如果您需要对数据做一些事情,那么您应该实现一个接口侦听器"并将其传递给 AsyncTask.

The purpose is to be Asynchronous so boolean downloadData() should have a return type of void. If you need to do something with the data then you should implement an interface "listener" and pass it to the AsyncTask.

示例监听器:

class TaskConnect extends AsyncTask<Void, Void, ConnectionResponse> {

    private final AsyncTaskListener mListener;

    /**
     *
     */
    public TaskConnect(AsyncTaskListener listener) {
        ...
        mListener = listener;
    }

    @Override
    protected void onPreExecute() {
        if (mListener != null) {
            mListener.onPreExecute(mId);
        }
    }

    @Override
    protected ConnectionResponse doInBackground(Void... cData) {
        ...
        return responseData;
    }

    @Override
    protected void onPostExecute(ConnectionResponse response) {
        if (mListener != null) {
            mListener.onComplete(response);
        } else {
            LOG.w("No AsyncTaskListener!", new Throwable());
        }
    }
}

public interface AsyncTaskListener {
    public abstract void onPreExecute(int id);
    public abstract void onComplete(ConnectionResponse response);
}

这篇关于Android - AsyncTask 中未显示进度对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆