我正在創建一個應用程序,當您使用用戶名和密碼登錄時,它會向服務器請求信息。 服務器的請求需要一定的時間(15-20秒),同時我想顯示一個單詞很少的旋轉欄。 但我嘗試了AsyncTask
這個類的很多變體,我無法讓它工作。它得到的信息沒問題,但凍結屏幕直到響應。 現在我只是有一個新線程實施runnable
。我不知道從代碼的哪個位置我需要撥打AsyncTask
。AsyncTask進程
的onClick
觸發attemptLogin()
功能:
public void onClick(View view) {
attemptLogin();
}
在attemptLogin()
功能:
// more code
showProgress(true);
new Thread(new GetServerResponseRunnable()).start();
while (wait) {}
// more code
而且Runnable的是:
public class GetServerResponseRunnable implements Runnable {
@Override
public void run() {
response = getInfo.getTours(mUsername, mPassword);
wait = false;
}
}
正如你可以看到從調用另一個函數一個不同的班級。 這是函數:
public String getTours(String username, String password) {
String req = "GETALLDATA";
String retStr = "";
try {
url = getURL(req, username, password);
sendOutputLine(url, "");
retStr = getReturnString();
Log.d(LoginActivity.DEBUG_TAG, "getTours() return: " + retStr);
} catch (Exception e) {
Log.d(LoginActivity.DEBUG_TAG, "programm bommed client: " + e.getMessage());
}
return retStr;
}
我需要幫助,請。主要是我想要做的是:
response = getInfo.getTours(mUsername, mPassword);
wait = false;
而同時顯示旋轉酒吧。
感謝
更新:2013年2月13日
我用這個代碼,但我得到了
02-13 09:07:16.142: E/AndroidRuntime(1046): java.lang.NullPointerException
在該行
:
this.dialog.setMessage(getResources().getString(R.string.login_progress_signing_in));
任何想法爲什麼?
public class LoginTask extends AsyncTask<Object, Void, String> {
public Context context;
public ProgressDialog dialog;
public void BaseTask(Context context) {
this.context = context;
this.dialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
this.dialog.setMessage(getResources().getString(R.string.login_progress_signing_in));
this.dialog.show();
}
@Override
protected String doInBackground(Object... objects) {
String name = (String) objects[0];
String password = (String) objects[1];
String response = getInfo.getTours(name , password);
return response;
}
@Override
protected void onPostExecute(String response) {
if (dialog != null && dialog.isShowing())
dialog.dismiss();
LoginActivity.response = response;
// process response as you need
}
}
謝謝,但我該怎麼稱呼這個班?只是創建它的新實例?我如何傳遞用戶名和密碼? – Mike 2013-02-12 22:55:23
更新了我的答案,有關更多詳細信息,請參閱http://developer.android.com/reference/android/os/AsyncTask.html – 2013-02-13 06:24:45
我更新了代碼,您可以查看一下嗎?我正在從'attemptLogin()'中調用新的LoginTask。可以嗎?或者我需要從onClick? – Mike 2013-02-13 14:10:42