Skip to content

Instantly share code, notes, and snippets.

@razarahil
Last active December 20, 2015 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save razarahil/6149775 to your computer and use it in GitHub Desktop.
Save razarahil/6149775 to your computer and use it in GitHub Desktop.
MainActivity of Parsing JSON with Volley
package com.razzil.volleyjson;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
private TextView mTemp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTemp = (TextView) findViewById(R.id.temp);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://api.openweathermap.org/data/2.5/weather?q=Udaipur,In&APPID=c6d8d951c8af2e67a6748c70e274031e";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject jsObj = new JSONObject(response.toString());
JSONObject jsMain = jsObj.getJSONObject("main");
double temp = jsMain.getDouble("temp");
String finalTemp=String.valueOf(temp);
mTemp.setText(finalTemp);
} catch (JSONException e) {
mTemp.setText("Parse Error");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTemp.setText(error.getMessage());
}
}
);
queue.add(jsObjRequest);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment