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.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
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) {
builder.append(line).append("\n");
}
bufferedReader.close();
outputString = builder.toString();
return outputString;
}

public void setWeather (View view) throws IOException, JSONException {
String json = getStringFromURL("https://query.yahooapis.com/v1/public/yql?q=select * 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(R.id.textView);
tv.setText(last);
}


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 (https://developer.android.com/training/basics/network-ops/connecting.html) and follow this document.