Android-ProgressDialog不显示在AsyncTask中 [英] Android - progressdialog not displaying in AsyncTask

查看:49
本文介绍了Android-ProgressDialog不显示在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的方法:

   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.

谢谢.

推荐答案

return new HttpConnection(activity).execute().get();删除.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-ProgressDialog不显示在AsyncTask中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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