显示不确定的进度指标

时间:2014-02-25 22:31:37

标签: java android networking android-volley

我正在尝试使用排球进行网络请求时显示进度指示器。我收到错误“只有创建视图层次结构的原始线程才能触及其视图”。我无法弄清楚如何将hideProgressDialog()与showProgressDialog()放在同一个线程上。这是我的代码......

showProgressDialog("Logging you in");

    String url = ApplicationController.getInstance().getBaseURL() + "Customer/LoginCustomer";

    JsonRequest<String> jr = new JsonRequest<String>(Method.POST, url, jo.toString(), this.createSuccessListener(),
            this.createErrorListener()) {

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse nr) {
            hideProgressDialog();
            try {
                String str = new String(nr.data, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }
    };

    ApplicationController.getInstance().addToRequestQueue(jr);
}

/** Create Volley Listeners **/
private Response.ErrorListener createErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            hideProgressDialog();
        }
    };
}

private Response.Listener<String> createSuccessListener() {
    return new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            hideProgressDialog();}
    };
}

解决方案

感谢tautvydas。我最终将这些方法放在我的基类中。

protected void showProgressDialog(String message) {
    if(mHandler == null){
        mHandler = new Handler();
    }
    if (mDialog == null || !mDialog.isShowing()) {
        mDialog = new ProgressDialog(getActivity());
        mDialog.setMessage(message);
        mDialog.setCancelable(false);
        mDialog.setIndeterminate(true);
        mDialog.show();
    }
}

protected void hideProgressDialog() {
    if (mDialog != null) {
        mHandler.post(new Runnable() {
            @Override
            // this will run on the main thread.
            public void run() {
                mDialog.hide();
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

创建一个Handler并向其传递Runnable以在主线程上运行。

1)在Handler方法的构造函数中onCreate()声明Handler handler = new Handler()。 2)然后在parseNetworkResponse()方法调用中

handler.post(new Runnable() {
           @Override
           // this will run on the main thread.
           public void run() {
               hideProgressDialog();
           }
      });