在Android中使用AsyncTask创建活动

时间:2012-10-04 07:29:31

标签: android android-asynctask android-activity

运行以下代码时出现异常。

public class LoginActivity extends Activity {
/** Called when the activity is first created. */
Button btnSend, btnDelete;
EditText edtUsername, edtPassword;
TextView tvUsername, tvPassword;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    initializeProperties();

    btnGonder.setOnClickListener(new OnClickListener() { public void onClick(View view) {           
        login("aaa@bbb.com", "123456");
    }});
    btnSil.setOnClickListener(new OnClickListener() { public void onClick(View view) {
        clearView();
    }});
}

private void initializeProperties() {
    btnSend = (Button) findViewById(R.id.bSend);
    btnDelete = (Button) findViewById(R.id.bDelete);
    tvUsername = (TextView) findViewById(R.id.tvUsername);
    edtUsername = (EditText) findViewById(R.id.etUsername);
    tvPassword = (TextView) findViewById(R.id.tvPassword);
    edtPassword = (EditText) findViewById(R.id.etPassword);
}

private static final String readInputStream(java.io.InputStream stream) throws IOException {
    java.io.InputStreamReader streamReader = new java.io.InputStreamReader(stream);
    java.io.BufferedReader bufferedReader = new java.io.BufferedReader(streamReader);
    String line, redText = "";
    while ((line = bufferedReader.readLine()) != null) {
        redText += line;
    }
    bufferedReader.close();
    return redText;
}

private void clearView() {
    edtPassword.setText("");
}

private void login(String username, String password) {

    HttpPost httpPost = new HttpPost("http://192.168.1.1/api/login");

    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getApplicationContext());
    alertBuilder.setCancelable(true);

    //HttpResponse response = null;
    try {
        // Add your data
        httpPost.setEntity(new StringEntity(
            String.format("{ 'Email': '%s', 'Password': '%s' }", username, password)
        ));
        // Set Headers
        httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
        // Execute HTTP Post Request
        //response = new AsyncLoginHandler(alertBuilder).execute(httpPost).get();
        new AsyncLoginHandler(alertBuilder).execute(httpPost);

    } catch (UnsupportedEncodingException uee) {
        alertBuilder.setMessage(uee.getMessage());
    }
}

class AsyncLoginHandler extends android.os.AsyncTask<HttpPost, Void, HttpResponse> {
    AlertDialog.Builder alertBuilder;

    AsyncLoginHandler(AlertDialog.Builder alertBuilder) {
        super();
        this.alertBuilder = alertBuilder;
    }

    @Override
    protected HttpResponse doInBackground(HttpPost... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = null;
        for (int i = 0; i < params.length; i++) {
            try {
                httpResponse = httpClient.execute(params[i]);
            } catch (ClientProtocolException cpe) {
                alertBuilder.setMessage(cpe.getMessage());
            } catch (IOException ioe) {
                alertBuilder.setMessage(ioe.getMessage());
            } catch (Exception e) {
                alertBuilder.setMessage(e.getMessage());
            }
        }
        return httpResponse;
    }

    @Override
    protected void onPostExecute(HttpResponse response) {
        if (response != null) {
            try {
                java.io.InputStream stream = response.getEntity().getContent();
                String result = readInputStream(stream);
                alertBuilder.setMessage(result);
            } catch (IllegalStateException ise) {
                alertBuilder.setMessage(ise.getMessage());
            } catch (IOException ioe) {
                alertBuilder.setMessage(ioe.getMessage());
            }
        }

        super.onPostExecute(response);

        alertBuilder.create().show();
    }

}

}

嗯...... Android AsyncTask的文档页面(请参阅标题“4步骤”)指出在UI线程上调用了onPostExecute;但是在“ alertBuilder.create()。show();”之后我遇到以下错误。

 - 10-04 06:36:25.607: W/dalvikvm(711): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
 - 10-04 06:36:25.657: E/AndroidRuntime(711): FATAL EXCEPTION: main
 - 10-04 06:36:25.657: E/AndroidRuntime(711): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.view.ViewRootImpl.setView(ViewRootImpl.java:517)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:301)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.app.Dialog.show(Dialog.java:278)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at org.gdgankara.com.LoginActivity$AsyncLoginHandler.onPostExecute(LoginActivity.java:139)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at org.gdgankara.com.LoginActivity$AsyncLoginHandler.onPostExecute(LoginActivity.java:1)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.AsyncTask.finish(AsyncTask.java:602)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.AsyncTask.access$600(AsyncTask.java:156)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.Handler.dispatchMessage(Handler.java:99)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.os.Looper.loop(Looper.java:137)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at android.app.ActivityThread.main(ActivityThread.java:4424)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at java.lang.reflect.Method.invokeNative(Native Method)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at java.lang.reflect.Method.invoke(Method.java:511)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
 - 10-04 06:36:25.657: E/AndroidRuntime(711):   at dalvik.system.NativeStart.main(Native Method)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:-1)

doInBackground方法无法触及主线程的视图。这意味着您无法通过doInBackground方法设置警报对话框的消息。尝试从doInBackground中的catch中删除set 3 set消息并运行应用程序。