我知道带有线程问题的 ProgressDialog 已被多次询问,但似乎没有一个解决方案适用于我的项目。基本上我想要做的是:1)当用户单击按钮时,Activity 会向服务器发送身份验证请求 2)在完成此操作时会显示 ProgressDialog 3)当响应到来时,我想关闭 ProgressDialog 和Activity要读取和解释的返回对象
如果我: 1)设置线程以使用响应更新应用程序字段,下一个方法(在线程之外)在访问字段时抛出 NPE 2)如果我在线程中包含下一个方法,第二种方法抛出“java.lang.RuntimeException:无法在未调用 Looper.prepare() 的线程内创建处理程序”
对不起,很长的文字,但我完全失去了它......我的代码是这样的:
public class XXX extends Activity implements OnClickListener {
// (...)
private SoapObject returnObject;
private String response;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// (...)
authProgressDialog = ProgressDialog.show(XXX.this, "", "Authenticating...", true, false);
new Thread(new Runnable() {
@Override
public void run() {
authenticate(); // method that calls the API via SOAP
authenticateReal(); // method that handles the response
}
}).start();
mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 10:
authProgressDialog.dismiss();
break;
}
}
};
}
}
public void authenticate() {
// API stuff (...)
AndroidHttpTransport aht = new AndroidHttpTransport(URL);
try {
aht.call(SOAP_ACTION, soapEnvelope);
returnObject = (SoapObject) soapEnvelope.getResponse();
response = returnObject.getProperty("ResponseStatus").toString();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
mHandler.sendEmptyMessage(10);
}
}
// Method that needs to access returnObject and reponse objects and
// it is here where the NPE's or other exceptions are thrown
public void authenticateReal() {
// (...)
}