Using Gson in Android Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Using Gson in Android without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

My code is:


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;


public class MainActivity extends Activity {

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

    public void onCreate(Bundle savedInstanceState) {


        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) { 
                  "Error " + statusCode + " for URL " + url); 
              return null;

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

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

Any pointers appreciated. Thanks.


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.

We are here to answer your question about Using Gson in Android - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji