使用Volley开发注册模块:数据插入成功但ProgressDialog持续转圈
Hey there! As a fellow Android developer who’s been through Volley’s learning curve, I can spot the most likely issue here right away—you’re probably forgetting to dismiss your ProgressDialog once the Volley request completes (whether it succeeds or fails).
问题根源
Volley runs network requests asynchronously in the background. When you show the ProgressDialog before firing the request, it stays visible until you explicitly tell it to close. Since your data is inserting successfully, the request is finishing—but the dialog never gets the signal to stop spinning.
修复方案
You need to call dialog.dismiss() in both Volley’s success and error response listeners. Here’s how to adjust your code:
First, make sure you initialize and show the dialog before sending the request:
// 发起请求前显示ProgressDialog dialog = ProgressDialog.show(this, "注册中", "请稍候...", true);
Then, update your Volley request to include dismissal in both callbacks:
StringRequest stringRequest = new StringRequest(Request.Method.POST, Reg_url, new Response.Listener<String>() { @Override public void onResponse(String response) { // 请求成功时关闭对话框(先判断状态避免空指针) if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } // 处理成功逻辑,比如提示用户注册完成 Toast.makeText(registration.this, "注册成功!", Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 请求失败时也必须关闭对话框!这一步很容易被忽略 if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } // 处理错误逻辑,比如提示用户重试 Toast.makeText(registration.this, "注册失败,请检查网络后重试", Toast.LENGTH_SHORT).show(); } }) { // 重写getParams()传递注册参数 @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("name", Name.getText().toString().trim()); params.put("email", Email.getText().toString().trim()); params.put("username", Username.getText().toString().trim()); params.put("password", Password.getText().toString().trim()); return params; } }; // 将请求加入Volley队列 RequestQueue queue = Volley.newRequestQueue(this); queue.add(stringRequest);
额外提示
- Always check if the dialog is non-null and still showing before dismissing it—this prevents
NullPointerExceptionif the activity is destroyed while the request is in flight. - If you’re using the
ProgressBarvariable in your code instead ofProgressDialog, remember to set its visibility toView.GONEin both response callbacks too.
内容的提问来源于stack exchange,提问作者Sahil Arman

