Parsing JSON into Android TextViews
I am trying to fill Vikas and Hassan to two text views respectively
but having problems to complete the AndroidJSONParsingActivity.java
Any Ideas,
JSON URL :: http://54.218.73.244:8084/
JSON-Structure::
{
"first": [
{
"_id": 1,
"name": "devrath",
"age": 24
},
{
"_id": 2,
"name": "Dheeraj",
"age": 25
},
{
"_id": 3,
"name": "Vikas",
"age": 26
}
],
"second": [
{
"_id": 1,
"place": "Hassan",
"phone": 1
},
{
"_id": 2,
"place": "Pune",
"phone": 2
},
{
"_id": 3,
"place": "Delhi",
"phone": 3
}
]
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +
e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:8084/";
private HashMap<Integer, String> contentsMap = new HashMap<Integer,
String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
//CODE to be ADDED
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
TextView textView=(TextView) findViewById(R.id.textView1);
textView.setText(contentsMap.get(1));
textView=(TextView) findViewById(R.id.textView2);
textView.setText(contentsMap.get(2));
}
}
I am trying to complete the AndroidJSONParsingActivity
No comments:
Post a Comment