我如何使用 AsyncTask 在 android 中发送 httppost?

How do i send a httppost in android using AsyncTask?

我正在尝试使用 httppost 将数据存储在数据库中。我发现在主线程中尝试这样做会导致崩溃,所以我尝试使用 AsyncTask.

这是我创建的 AsyncTask 代码

   public class PostData extends AsyncTask<String, Void, String> {

   protected String doInBackground(String... params){
        // get zero index of nameValuePairs and use that to post
       String result = "fail";
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.name.com/Script.php");


            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            Log.d("1", "nope");
            nameValuePairs.add(new BasicNameValuePair("id", params[0]));
            Log.d("2", "nope");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            Log.d("3", "nope");

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            Log.d("4", "nope");
            Log.i("postData", response.getStatusLine().toString());
            result="got it";
        }
        catch (Exception e){
            Log.d("lol","lool");
        }
        finally{}

       return result;

    }
}

我最近才开始android所以我对AsyncTask很陌生。 这是我尝试使用此 class

的代码
public class HomePage extends ActionBarActivity {

    PostData postD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
    }

    //Connect to other activities

    public void aboutPage(View view) throws IOException {
        //Intent intent = new Intent(this, AboutPage.class);
        //startActivity(intent);

        postD.doInBackground("1111");



    }

我得到了新的错误

01-30 18:13:44.592    1921-1921/com.example.user2013.mobileapplicationcustomerversion I/art﹕ Not late-enabling -Xcheck:jni (already on)
01-30 18:13:44.962    1921-1942/com.example.user2013.mobileapplicationcustomerversion D/OpenGLRenderer﹕ Render dirty regions requested: true
01-30 18:13:45.003    1921-1921/com.example.user2013.mobileapplicationcustomerversion D/﹕ HostConnection::get() New Host Connection established 0xa6853600, tid 1921
01-30 18:13:45.033    1921-1921/com.example.user2013.mobileapplicationcustomerversion D/Atlas﹕ Validating map...
01-30 18:13:45.110    1921-1942/com.example.user2013.mobileapplicationcustomerversion D/﹕ HostConnection::get() New Host Connection established 0xa6853740, tid 1942
01-30 18:13:45.130    1921-1942/com.example.user2013.mobileapplicationcustomerversion I/OpenGLRenderer﹕ Initialized EGL, version 1.4
01-30 18:13:45.169    1921-1942/com.example.user2013.mobileapplicationcustomerversion D/OpenGLRenderer﹕ Enabling debug mode 0
01-30 18:13:45.216    1921-1942/com.example.user2013.mobileapplicationcustomerversion W/EGL_emulation﹕ eglSurfaceAttrib not implemented
01-30 18:13:45.216    1921-1942/com.example.user2013.mobileapplicationcustomerversion W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6805440, error=EGL_SUCCESS
01-30 18:13:48.461    1921-1921/com.example.user2013.mobileapplicationcustomerversion I/Choreographer﹕ Skipped 78 frames!  The application may be doing too much work on its main thread.
01-30 18:13:49.128    1921-1942/com.example.user2013.mobileapplicationcustomerversion W/EGL_emulation﹕ eglSurfaceAttrib not implemented
01-30 18:13:49.128    1921-1942/com.example.user2013.mobileapplicationcustomerversion W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6805440, error=EGL_SUCCESS
01-30 18:13:49.828    1921-1921/com.example.user2013.mobileapplicationcustomerversion I/Choreographer﹕ Skipped 36 frames!  The application may be doing too much work on its main thread.
01-30 18:13:51.004    1921-1921/com.example.user2013.mobileapplicationcustomerversion D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
01-30 18:13:51.004    1921-1921/com.example.user2013.mobileapplicationcustomerversion E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.user2013.mobileapplicationcustomerversion, PID: 1921
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View.onClick(View.java:4007)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method \'java.lang.String com.example.user2013.mobileapplicationcustomerversion.PostData.doInBackground(java.lang.String[])\' on a null object reference
            at com.example.user2013.mobileapplicationcustomerversion.HomePage.aboutPage(HomePage.java:41)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-30 18:14:00.311    1921-1921/com.example.user2013.mobileapplicationcustomerversion I/Process﹕ Sending signal. PID: 1921 SIG: 9

这里:

 postD.doInBackground("1111");

您正在使用 class 对象调用 doInBackground 方法,该对象也将在主 ui 线程上工作。

要在后台线程中 运行 doInBackground 您需要使用 AsyncTask.execute 方法启动 AsyncTask。这样做:

public void aboutPage(View view) throws IOException {
    postD=new PostData();
    postD.execute("1111");
 }

查看更多关于 AsyncTask