Amir Amir - 1 month ago 10
Android Question

How i can parse JSON result from URL request?

I am a newbie in android and java. I want to get a url request (result is JSON) and parsing it (for example get JSON weather from yahoo api's).
I copy getStringFromUrl Function and I know error for my function (setWeather). please help me.

public static String getStringFromURL(String urlString) throws IOException {
HttpURLConnection urlConnection;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String outputString;
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
outputString = builder.toString();
return outputString;

public void setWeather (View view) throws IOException, JSONException {
String json = getStringFromURL(" * from weather.forecast where woeid in (select woeid from geo.places(1) where text='Esfahan')&format=json");
JSONObject jso = new JSONObject(json);
JSONObject query = jso.getJSONObject("query");
JSONObject result = query.getJSONObject("results");
JSONObject channel = result.getJSONObject("channel");
JSONObject windI = channel.getJSONObject("wind");
JSONObject location = channel.getJSONObject("location");
String last = "";
last = location.getString("city");
TextView tv = (TextView) findViewById(;

When I run this app on device app crash.
It's error that write on Android Monitor:

Answer Source

In case of android there is one notion you have to follow, all time taking tasks need to go on a separate thread that is not blocking your UI thread. And all IO calls or heavy operation call should go onto a seperate thread.

For more about how to make network operations refer Android developer guide here ( and follow this document.