【发布时间】:2011-01-23 20:17:07
【问题描述】:
我知道带有线程问题的 ProgressDialog 已被多次询问,但似乎没有一个解决方案适用于我的项目。基本上我想做的是: 1)当用户单击按钮时,Activity 向服务器发送身份验证请求 2)在完成此操作时,会显示 ProgressDialog 3)当响应到来时,我想关闭 ProgressDialog 和返回对象以由 Activity 读取和解释
如果我: 1)设置Thread以响应更新Application字段,next方法(在Thread之外)访问该字段时会抛出NPE 2) 如果我在 Thread 中包含下一个方法,则第二种方法会抛出“java.lang.RuntimeException: Can't create handler inside thread that has not called 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() {
// (...)
}
【问题讨论】:
-
我可能在这里遗漏了一些关于线程的基本知识,因为我从来没有真正读过足够多的东西……抱歉,我很抱歉。 authenticateReal() 的内容可以很容易地转移到 autenticate() 的 try 块中。
标签: android multithreading android-activity progressdialog