-2

I'm novice with web service and i try to create a web service with netbeans, i test it with rest client (mozilla plugin) it work but when i try to use the android client, it's doesn't and i receive this android.os.NetworkOnMainThreadException in my logcat. Here is the code

<pre><code>
package cg.skylab.clientrest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import cg.skylab.clientrest.model.Personne;


public class ListePersonnel extends ListActivity {
    private ArrayList<Personne> personnes = new ArrayList<Personne>();
    private String adresse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.liste);
        startActivityForResult(new Intent(this, ChoixServeur.class), 1);

    }


    protected void onActivityResult(int requestCode, int resultCode,
            Intent intention) {

        if (resultCode == RESULT_OK) {
            adresse = intention.getStringExtra("adresse");
            try {
                miseAJour();
            } catch (Exception ex) {
                Toast.makeText(this, "Reponse incorrecte", Toast.LENGTH_SHORT).show();
                String tagException = ex.toString();
                String tagAdresse = intention.getStringExtra("adresse");
                Log.i(tagException, "Exception");
                Log.i(tagAdresse, "Adresse IP");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adresse != null)
            try {
                miseAJour();
            } catch (Exception ex) {

            }
    }

    @Override
    protected void onStop() {
        super.onStop();
        finish();
    }

    public void miseAJour() throws IOException, JSONException {
        HttpClient client = new DefaultHttpClient();
        HttpGet requete = new HttpGet("http://"+adresse+":8080/Personnel/rest/"+1);
        HttpResponse reponse = client.execute(requete);
        if (reponse.getStatusLine().getStatusCode() == 200) {
            Scanner lecture = new Scanner(reponse.getEntity().getContent());
            StringBuilder contenu = new StringBuilder();
            while (lecture.hasNextLine())
                contenu.append(lecture.nextLine() + '\n');
            JSONArray tableauJSON = new JSONArray(contenu.toString());
            StringBuilder message = new StringBuilder();
            personnes.clear();

            for (int i = 0; i < tableauJSON.length(); i++) {
                JSONObject json = tableauJSON.getJSONObject(i);
                Personne personne = new Personne();
                personne.setId(json.getLong("id"));
                personne.setNom(json.getString("nom"));
                personne.setPrenom(json.getString("prenom"));
                personne.setNaissance(json.getLong("naissance"));
                personne.setTelephone(json.getString("telephone"));
                personnes.add(personne);
            }
            setListAdapter(new ArrayAdapter<Personne>(this,
                    android.R.layout.simple_list_item_1, personnes));
        } else
            Toast.makeText(this, "Problème de connexion avec le serveur",
                    Toast.LENGTH_SHORT).show();
    }

    public void edition(View v) {
        Intent intention = new Intent(this, Personnel.class);
        intention.putExtra("id", 0);
        intention.putExtra("adresse", adresse);
        startActivity(intention);
    }

    protected void onListItemClick(ListView liste, View v, int position, long id) {
        Personne personne = personnes.get(position);
        Intent intention = new Intent(this, Personnel.class);
        intention.putExtra("id", personne.getId());
        intention.putExtra("adresse", adresse);
        intention.putExtra("nom", personne.getNom());
        intention.putExtra("prenom", personne.getPrenom());
        intention.putExtra("naissance", personne.getNaissance());
        intention.putExtra("telephone", personne.getTelephone());
        startActivity(intention);
    }
}
</code></pre>
That1Guy
  • 7,075
  • 4
  • 47
  • 59
Lordgodgiven
  • 11
  • 1
  • 4

1 Answers1

2

You are getting NewtworkOnMainThread exception because you are making network calls on the UI thread. This is a bad practice because it can block/bog down your UI thread which would make your app feel slow.

To avoid that error you have to use AsyncTask.

You have to use like this:

public class DowloadTest extends AsyncTask<String, Integer, String> {
  @Override
  protected void onPreExecute() {

  };

  @Override
  protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    // Call your web service here
    return null;
  }

  @Override
  protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    // Update your UI here
    return;
  }
}

For more detail check out this article

fklappan
  • 3,259
  • 2
  • 17
  • 18
Piyush
  • 18,895
  • 5
  • 32
  • 63