-3

I want to make post to the remote db from my device, but i've got NetworkOnMainThread except, how can I solve this task ? Also I need simple example how to post data to remote db.

ib_wyslij.setOnClickListener(new OnClickListener() {

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

                sendAccelerationData(zam);

            }
    });



    private void sendAccelerationData(Zamowienie zam)
    {

        //Add data to be send.
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("Zam_suma", Float.toString(zam.getSuma())));

        this.sendData(nameValuePairs);
    }

private void sendData(ArrayList<NameValuePair> data){

        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("www.kupa.pl/1.php");
            httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(data));
            HttpResponse response = httpclient.execute(httppost);
            Log.i("postData", response.getStatusLine().toString());
                //Could do something better with response.
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error:  "+e.toString());
        }  
    }
Looking Forward
  • 3,579
  • 8
  • 45
  • 65
user2061352
  • 29
  • 1
  • 8

3 Answers3

2

As the exception is telling you - what is wrong is you are doing network activity on the main thread. Put it into the background asynchronously. For this case an AsyncTask will work perfectly.

  private void sendAccelerationData(final Zamowienie zam) {

      new AsyncTask<Void,Void,Void>() {

          public void doInBackground(...) {

                //Add data to be send.
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("Zam_suma", Float.toString(zam.getSuma())));

                MyActivityClass.this.sendData(nameValuePairs);

          }

      }


}
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
1

You cannot make network operations in your main UI, because that would block your program execution with a very disgusting experience for your users. For this, you have to separate network operations inside a Thread, or even better, an AsyncTask if you're just starting with the thread world.

This is the structure you would use:

final class MyNetworkOperation extends AsyncTask<URL, Integer, Void> {
  @Override
  protected void onPreExecute(final Void param) {
    ...
  }

  @Override
  protected Void doInBackground(final URL... args) {
    ...
    return null;
  }

  @Override
  protected void onPostExecute(final Void param) {
    ...
  }
}

Even the method names are very self explanatory. When you define your AsyncTask, and call .execute(url_object) on it, the first called method will be .onPreExecute(), there you may initialize variables and prepare everything for the network operation you want to do. The hard part of your network operation should be done inside doInBackground(). There you connect, do the data transfer and disconnect from the host. Finally, onPostExecute() is called: Once you're done, you can process here your results (transfer it to the main Activity, show a Dialog, etc.).

For more on AsyncTasks (and know what does those parameters mean) I strongly recommend reading the reference.

A very good example might be found here.

nKn
  • 13,691
  • 9
  • 45
  • 62
-3

Add this in your onCreate()

if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

ADD this to Manifest

<uses-permission android:name="android.permission.INTERNET"/>

Better use thread or asynctask for network tasks...

Looking Forward
  • 3,579
  • 8
  • 45
  • 65