Panagiotis
Panagiotis

Reputation: 511

Using Gson in Android

I am using google-gson to get data from one rest web service but LogCat displays me android.os.NetWorkOnMainThreadException. For the connection to the web service I am using httpclientandroidlib package from https://code.google.com/p/httpclientandroidlib/.

My code is:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.HttpStatus;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;

import com.google.gson.Gson;


public class MainActivity extends Activity {

    String url = "http://localhost:8080/SightsWebService/sights/getFun";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        InputStream source = retrieveStream(url);

        Gson gson = new Gson();
        Reader reader = new InputStreamReader(source);
        ListKozanisPlaces sightsList = gson.fromJson(reader, ListKozanisPlaces.class);


        for ( int counter = 0; counter < sightsList.getList().size(); counter++ )
            Toast.makeText(this, sightsList.getList().get( counter ).toString(), Toast.LENGTH_SHORT).show();
    }

    private InputStream retrieveStream(String url) 
    {    
        DefaultHttpClient client = new DefaultHttpClient(); 

        HttpGet getRequest = new HttpGet(url);

        try {      
           HttpResponse getResponse = client.execute(getRequest);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();
           return getResponseEntity.getContent();

        } 
        catch (IOException e) {
           getRequest.abort();
           Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
        }   
        return null;     
    }
}

Any pointers appreciated. Thanks.

Upvotes: 1

Views: 85

Answers (2)

Mukesh Rana
Mukesh Rana

Reputation: 4091

This exception is thrown when an application attempts to perform a networking operation on its main thread. Try using AsyncTask for your network operations

For a demo sample, you can refer this http://android-er.blogspot.in/2012/04/androidosnetworkonmainthreadexception.html

Upvotes: 1

MidasLefko
MidasLefko

Reputation: 4559

As the name implies android does not allow for networking operations on the "main" thread. You need to do these operations on an other thread. The simplest way to go about this is with an Asynctask. A quick google search should net you several tutorials on Asynctasks.

Upvotes: 1

Related Questions