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:
I found much about gson problems on stackoverflow but nothing solved my problem. So what am I doing wrong ??