1

I'm new in Android and I was following a tutorial about how to use Gson. (http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html)

I have tried to receive the following json object. (http://api.openweathermap.org/data/2.5/weather?q=London,uk)

This is my code:

MainClass:

public class MainActivity extends Activity {


String url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk";

@Override
protected 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);
    Weather weather = gson.fromJson(reader, Weather.class);
    Toast.makeText(this, weather.clouds, 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;

}}

WeatherClass:

public class Weather {

public double lon;

public double lat;

public String country;

public int speed;

@SerializedName("all")
public int clouds;
}

If I run this on the emulator, my App "unfortunately has stopped" and LogCat say this:

enter image description here

enter image description here

I found much about gson problems on stackoverflow but nothing solved my problem. So what am I doing wrong ??

Sasch
  • 35
  • 2

1 Answers1

1

You are performing network operation inside main thread. You shouldn't do that because you can block your UI ths way. Android warns you about it and throws NetworkOnMainThreadException. Perform network operation on worker thread. You can use AsyncTask for that if you would like to use results of your network operation to update UI. If you do not need to update your UI simply create a new thread and do network stuff there.

michal.z
  • 2,025
  • 1
  • 15
  • 10