2
我試圖用齊射做網絡請求時顯示進度指示器。我收到錯誤「只有創建視圖層次結構的原始線程才能觸及其視圖」。我無法弄清楚如何讓我的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();
}
});
}
}
參考這個職位各種方式對UI線程上運行: http://stackoverflow.com/questions/12850143/android-basics-running-code-在最UI線程 – Prakash