Skip to content

Instantly share code, notes, and snippets.

@sijangurung
Last active April 21, 2017 08:57
Show Gist options
  • Save sijangurung/bbc0ab35dc444f5a1049b35c90d130ed to your computer and use it in GitHub Desktop.
Save sijangurung/bbc0ab35dc444f5a1049b35c90d130ed to your computer and use it in GitHub Desktop.
Consuming JSON data in Android ( primitive way)
package com.example.sijangurung.jsontest;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
/**
* Created by sijangurung on 21/04/2017.
*/
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
package com.example.sijangurung.jsontest;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
private TextView txtContainer;
HashMap<String, String> userData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userData = new HashMap<String, String>();
txtContainer = (TextView) findViewById(R.id.txtContainer);
new GetUser().execute();
}
private class GetUser extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://rayrays-json-deliverer.herokuapp.com/user";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON User node
JSONObject user = jsonObj.getJSONObject("user");
String created_at = user.getString("created_at");
JSONObject family = user.getJSONObject("family");
String f_created_at = family.getString("created_at");
String f_created_by = family.getString("created_by");
String f_id = family.getString("id");
JSONArray f_members = family.getJSONArray("members");
for (int i = 0; i < f_members.length(); i++) {
JSONObject m = f_members.getJSONObject(i);
String id = m.getString("id");
String first_name = m.getString("first_name");
String last_name = m.getString("last_name");
Boolean is_authenticated = m.getBoolean("is_authenticated");
}
String f_name = family.getString("name");
String f_updated_at = family.getString("updated_at");
String id = user.getString("id");
String first_name = user.getString("first_name");
String last_name = user.getString("last_name");
Boolean is_authenticated = user.getBoolean("is_authenticated");
String updated_at = user.getString("updated_at");
userData.put("user", user.toString());
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
txtContainer.setText(userData.toString());
}
}
}
{
"user": {
"created_at": "2017-03-21T121241.989Z",
"family": {
"created_at": "2017-03-21T122428.328Z",
"created_by": "66d4fb14-7ec7-4ce6-9aa7-41c12d6d9de2",
"id": "47b4d072-f299-45f7-8bb2-4da30c104fcb",
"members": [
{
"first_name": "Fred",
"id": "8f619c4b-b9fe-48b1-b1bf-515eda28b13a",
"is_authenticated": true,
"last_name": "Flintstone"
},
{
"first_name": "Pebbles",
"id": "5c1bfdc6-b0c8-49d9-b2fb-c9756a1ea5b6",
"is_authenticated": false,
"last_name": "Rubble"
}
],
"name": "Flintstones",
"updated_at": "2017-03-21T122428.328Z"
},
"first_name": "Fred",
"id": "8f619c4b-b9fe-48b1-b1bf-515eda28b13a",
"is_authenticated": true,
"last_name": "Flintstone",
"updated_at": "2017-03-21T121241.989Z"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment