You are on page 1of 5

Android Tutorial

Get JSON

19-Aug-11

Get JSON
Important used Classes and Interfaces:
HttpClient: This is an interface for an HTTP client. HttpResponse: This is an HTTP response. HttpGet: This is an HTTP GET method. HttpEntity: This is an entity that can be sent or received with an HTTP message. InputStream: This is the base class for all input streams. BufferedReader: This class wraps an existing Reader and buffers the input. StringBuilder: This is a modifiable sequence of characters for use in creating strings. JSONObject This is a modifiable set of name/value mappings.

Workflow:
Start a new project named GetJSON. Open the res/layout/main.xml file and insert the following:
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlocationlayout" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TableRow> <TextView android:id="@+id/json" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="JSON:"/> <TextView android:id="@+id/jsonValue" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </TableRow> <TableRow> <TextView android:id="@+id/added" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Added by:"/> <TextView android:id="@+id/addedValue" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </TableRow> <TableRow> <TextView android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Time:"/> <TextView android:id="@+id/timeValue" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </TableRow>

Gwendolin Lehrer

Geoinformation FH Krnten

[1]

Android Tutorial

Get JSON

19-Aug-11

<TableRow> <TextView android:id="@+id/sub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Subcategory:"/> <TextView android:id="@+id/subValue" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </TableRow> <TableRow> <TextView android:id="@+id/main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Maincategory:"/> <TextView android:id="@+id/mainValue" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </TableRow> <TableRow> <Button android:id="@+id/btn" android:text="Get JSON"/> </TableRow> </TableLayout>

A simple TableLayout is used, with TextViews that will contain the JSON and its components.
Now open GetJSONActivity.java and be sure it loads the res/layout/main.xml layout in the onCreate() method:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }

Declare the TextViews and the Button at the beginning of the Activity and set the OnClickListener for the Button:
json = (TextView) findViewById(R.id.jsonValue); added = (TextView) findViewById(R.id.addedValue); time = (TextView) findViewById(R.id.timeValue); sub = (TextView) findViewById(R.id.subValue); main = (TextView) findViewById(R.id.mainValue); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new Click());

Now create an inner class Click() which implements the OnClickListener:


public class Click implements OnClickListener { @Override public void onClick(View v) { json.setText(http.getJson()); added.setText(http.getAdded()); time.setText(http.getTime()); sub.setText(http.getSub());

Gwendolin Lehrer

Geoinformation FH Krnten

[2]

Android Tutorial

Get JSON
main.setText(http.getMain());

19-Aug-11

} }

Start a new Thread in your onCreate method:


new Thread(new Runnable() { public void run() { url = "http://193.171.127.97:5000/subcategorys?queryable= subcategoryname&subcategoryname__like=Badesee"; http = new Connector(); http.connect(url); } }).start();

To be able to use this Thread you have to create a new Java Class in your package called Connector. Declare the following variables:
private private private private private private private private String str, result, added, time, sub, main; JSONArray valArray, nameArray, innerArray; JSONObject obj, innerObject; InputStream instream; HttpClient httpclient; HttpGet getRequest; HttpResponse response; HttpEntity entity;

As you see in the Thread you need a method called connect():

public void connect(String url){ obj = new JSONObject(); try { httpclient = new DefaultHttpClient(); // Prepare a request object getRequest = new HttpGet(); try{ getRequest.setURI(new URI(url)); }catch (URISyntaxException e){ Log.e("URISyntaxException", e.toString()); } // Execute the request response = null; response = httpclient.execute(getRequest); // Examine the response status Log.i("Status",response.getStatusLine().toString()); // Get the response entity entity = response.getEntity(); // no instream.close() needed if there is no entity if (entity != null) { // Read the JSON Response instream = entity.getContent(); result = convertStreamToString(instream); // Create a JSONObject obj = new JSONObject(result); Log.i("first subs json", obj.toString()); // Get the keys and values from obj

Gwendolin Lehrer

Geoinformation FH Krnten

[3]

Android Tutorial

Get JSON
nameArray=obj.names(); valArray=obj.toJSONArray(nameArray);

19-Aug-11

// Delete the squared brackets, so that the String can be converted into a JSONArray str = valArray.getString(0); innerArray = new JSONArray(str); Log.i("inner subs array", str); // Get the JSONObject from the JSONArray innerObject = (JSONObject) innerArray.get(0); added = innerObject.get("addedby").toString(); time = innerObject.get("timecreated").toString(); sub = innerObject.get("subcategoryname").toString(); main = innerObject.get("maincategory_fk").toString(); Log.i("added", added); Log.i("time", time); Log.i("sub", sub); Log.i("main", main); // Closing the input stream will trigger connection release instream.close(); } else{ added = "no connection"; time = "no connection"; main = "no connection"; sub = "no connection"; result = "no connection"; } } catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace();} }

At first you need an HttpClient with which you will be able to execute the built HttpGet. For the HttpGet you use the given url. What you get returned is what you save as HttpResponse. The response is saved as HttpEntity, which can be converted into a String via savings its content as stream. With the String you can create a JSONObject. Now you have to split up the JSON into its names and values. The only value here is surrounded by squared brackets, delete them and you can create a JSONArray. The only JSONObject in the array is saved as innerObject. From that you can get the values for addedby, time, sub and main. For converting the given stream into a String you have to implement a static method called convertStreamToString.

private static String convertStreamToString(InputStream is) { // Use the BufferedReader.readLine() until it returns null (no data left to read. // Append the data to a StringBuilder and return it as a String BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder();

Gwendolin Lehrer

Geoinformation FH Krnten

[4]

Android Tutorial

Get JSON

19-Aug-11

String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }

Before you run your Activity, make sure that you mention the needed permissions in your manifest. You declare them inside the manifest tag but outside the application tag.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></usespermission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></usespermission> <uses-permission android:name="android.permission.INTERNET"></usespermission>

When you run your application it should look like that

and after you clicked the get JSON Button:

Gwendolin Lehrer

Geoinformation FH Krnten

[5]

You might also like