我知道有線程問題的ProgressDialog已經被問了很多次,但沒有一個解決方案似乎適用於我的項目。基本上我想要做的是這樣的: 1)當用戶點擊一個按鈕時,活動向服務器發送一個授權請求 2)當這樣做時ProgressDialog顯示爲 3)當響應來臨時我想解僱ProgressDialog和活動的讀取和解釋返回對象如何在Activity從Web服務請求SoapObject時實現ProgressDialog?
如果我: 1)設置線程以更新具有響應的應用程序字段,下一個方法(線程外)將引發一個NPE當訪問字段 2)如果我在Thread中包含下一個方法,則第二個方法將拋出一個'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() {
// (...)
}
我可能會錯過一些關於線程的完全基本的東西,因爲我從來沒有真正讀過它們的tbh ......對不起一個noobish q。 authenticateReal()的內容可以很容易地傳遞給autenticate()的try塊。 – TomaszRykala 2011-01-23 20:26:34