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

时间:2015-01-30 18:15:27

标签: android android-asynctask http-post

我正在尝试使用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非常不熟悉。 这是我试图使用这个类的代码

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$1.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$1.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$1.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

1 个答案:

答案 0 :(得分:0)

下面:

 postD.doInBackground("1111");

您正在使用类对象调用doInBackground方法,该方法也适用于主ui线程。

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

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

详细了解AsyncTask