سؤال

I've tried to create a program which allows users to send an HTTP POST to a PHP script using the following code. I get a android.os.NetworkOnMainThreadException when I click on the send button. (btnSend).

package com.naveed.post;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        // Creating HTTP client
        final HttpClient httpClient = new DefaultHttpClient();
        // Creating HTTP Post
        final HttpPost httpPost = new HttpPost("http://10.0.2.2/android_post/test.php");
        Button send = (Button)findViewById(R.id.btnSend);
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText message = (EditText)findViewById(R.id.textMessage);

                String msg = message.getText().toString();

                   // Building post parameters
                // key and value pair
                List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
                nameValuePair.add(new BasicNameValuePair("message", msg));

                // Url Encoding the POST parameters
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
                } catch (UnsupportedEncodingException e) {
                    // writing error to Log
                    e.printStackTrace();
                }

                // Making HTTP Request
                try {
                    HttpResponse response = httpClient.execute(httpPost);

                    // writing response to log
                    Log.d("Http Response:", response.toString());
                } catch (ClientProtocolException e) {
                    // writing exception to log
                    e.printStackTrace();
                } catch (IOException e) {
                    // writing exception to log
                    e.printStackTrace();

                }
            }
        });

    }
}

I know I have to use AsyncTask, so i tried. But I know I am doing it wrong. Any suggestions. My code is below:

package com.naveed.post;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {


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


        Button send = (Button)findViewById(R.id.btnSend);
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
                 EditText message = (EditText)findViewById(R.id.textMessage);

                    String msg = message.getText().toString();

                    nameValuePair.add(new BasicNameValuePair("message", msg));


            }
        });

    }

   class doThePost extends AsyncTask<Void, Void, Void>{

        protected Void doInBackground(ArrayList<NameValuePair>... nameValuePair) {
            // TODO Auto-generated method stub
            ArrayList<NameValuePair> nvPairs = nameValuePair[0];
             HttpClient httpClient = new DefaultHttpClient();
                // Creating HTTP Post
             HttpPost httpPost = new HttpPost("http://10.0.2.2/android_post/test.php");
                // Url Encoding the POST parameters
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nvPairs));
                } catch (UnsupportedEncodingException e) {
                    // writing error to Log
                    e.printStackTrace();
                }

                // Making HTTP Request
                try {
                    HttpResponse response = httpClient.execute(httpPost);

                    // writing response to log
                    Log.d("hello", "done");
                    Log.d("Http Response:", response.toString());
                } catch (ClientProtocolException e) {
                    // writing exception to log
                    e.printStackTrace();
                } catch (IOException e) {
                    // writing exception to log
                    e.printStackTrace();

                }
                Log.d("hello", "done");
            return null;
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            return null;
        }




        }

}
هل كانت مفيدة؟

المحلول

Move your doInBackground method's code to protected Void doInBackground(Void... params) method and it will work. And you have to use the AsyncTask class. Here's the link to the AsyncTask class. It also has how to use sample code.

نصائح أخرى

Android killing processes which have been running for 5 seconds +. You have to use AsyncTask.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top