I have a JSON array sent from my SQL server via PHP in the following format which I am finding difficult to parse without encountering errors.
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
{
"placename": "place2",
"latitude": "51",
"longitude": "-0.5",
"question": "place2 existed when?",
"answer1": "800",
"answer2": "1000",
"answer3": "1200",
"answer4": "1400",
"correctanswer": "800"
},
{
"placename": "place3",
"latitude": "52",
"longitude": "-1",
"question": "place 3 was established when?",
"answer1": "2001",
"answer2": "2005",
"answer3": "2007",
"answer4": "2009",
"correctanswer": "2009"
}
]
I have verified my JSON at JSONLint and it comes up as valid. I have also used log code to print out my JSON in the Eclipse app debugger after my HTTP client has processed it and that also works fine (it shows the JSON as above so I know it has downloaded correctly).
I'm trying to fit the JSON Parser into the following activity but all my attempts thus far have either contained too many errors to run or have simply returned no results because of JSON parsing errors.
Here is the code of the main activity. The code for this activity is adapted from NewThinkTank.com (Android Development 15) and I'm trying to tweak it for my needs but the structure of the JSON used in the example is very different to mine.
I was hoping someone could suggest some code, or give me some pointers, as to how I could go about parsing this JSON array properly. I am fairly new to Android programming so this is a fairly steep task to figure out on my own.
Thanks for your time.
public class MainActivity extends Activity {
// The JSON REST Service I will pull from
static String dlquiz = "http://exampleserver.php";
// Will hold the values I pull from the JSON
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
#Override
public void onCreate(Bundle savedInstanceState) {
// Get any saved data
super.onCreate(savedInstanceState);
// Point to the name for the layout xml file used
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(dlquiz);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
//this allowed me to verify the JSON download in the debugger
Log.v("JSONParser RESULT ", result);
// JSON parsing needs to happen here...
return result;
}
protected void onPostExecute(String result){
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Place Name: " + placename);
line2.setText("Question: " + question);
line3.setText("Correct Answer: " + correctanswer);
}
}
}
Check this answer out: How to parse JSON in Android
You'll be using:
JSONArray array = new JSONArray(result);
From there, you'll loop through and get each JSONObject:
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
//now, get whatever value you need from the object:
placename = obj.getString("placename");
//or if on the MainUI thread you can set your TextView from here:
yourTextView.setText(obj.getString("placename"));
}
Good luck!
Related
I'm creating an activity that get a JSON file from internet (via AsyncTask).
I'm experiencing this error: org.json.JSONException: Unterminated string at character...
I checked the JSON file that I downloaded inside the app and I discovered that there is an object that contains brackets. Here is the suspected JSON object:
[{ ... }{"id":"5674563646","cat":"Uncategorized","subcat":"Uncategorized","name":"Tecno Lab","desc":"We run open hours from 8-10pm and [most] Saturdays from 12-6pm.","addr":"Main Street","city":"New York","country":"United States"}
{ ... }]
So, how to escape the brackets from my activity?
Here is the part of AsyncTask in which I download the JSON file:
protected String doInBackground(String... urls) {
int timeout = 10;
int i, count = 0;
BasicHttpParams basicParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(basicParams, timeout * 1000);
HttpConnectionParams.setSoTimeout(basicParams, timeout * 1000 );
DefaultHttpClient client = new DefaultHttpClient(basicParams);
StringBuilder stringBuilder = new StringBuilder();
for (i = 0; i < urls.length; i++) {
HttpGet request = new HttpGet(urls[i]);
request.addHeader("Cache-Control", "no-cache");
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStreamReader in = new InputStreamReader(entity.getContent());
BufferedReader reader = new BufferedReader(in);
String line = "";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
count++;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
publishProgress(count * 100 / urls.length);
}
return stringBuilder.toString();
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
...
JSONArray ja = new JSONArray(result);
...
JSON response normally contains two kinds of brackets {} and [] but both the brackets have quite different meaning and use. While, the first one represents JSON Object, the second one represents JSON Array.
In the JSON file you downloaded, the problem has nothing to do with the [most] word as it is inside double quotes. The problem in your JSON input is "addr": "Main Street". The opening double quote is missing there.
Corrected JSON input:
{"id":"5674563646","cat":"Uncategorized","subcat":"Uncategorized","name":"Tecno Lab","desc":"We run open hours from 8-10pm and [most] Saturdays from 12-6pm.","addr":"Main Street","city":"New York","country":"United States"}
I am having trouble figuring out why i'm getting a JSON exception while I am parsing my JSON object. I am getting(Http GET) the JASON from a URL. Here is all the relevant code, let me know if you need to see any more of the code
The doInBackground Async method:
#Override
protected Void doInBackground(Void... arg0)
{
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL,ServiceHandler.GET);
Log.w("Rakshak", "the jaon String is:"+jsonStr);// this prints the JASON in the log and it looks fine
// I am not pasting it in coz it is HUGE
if (jsonStr != null)
{
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.w("Rakshak", "in the try before the JASON");
// Getting JSON Array node
kingtide = jsonObj.getJSONArray("JASON");
// looping through All Kingtide events
for (int i = 0; i < kingtide.length(); i++)
{
JSONObject k = kingtide.getJSONObject(i);
String date = "Date Range:"+k.getString(KEY_DATE);
String lat = k.getString(KEY_LAT);
String lng = k.getString(KEY_LNG);
String loc = "Location of the Kingtide:"+k.getString(KEY_LOC)+", "+k.getString(KEY_STATE);
String temp_Time = k.getString(KEY_TIME);
String[] time_parts = temp_Time.split("T");
String time = "Kingtide at:"+time_parts[1]+" "+getYear(time_parts[0]);
// tmp hashmap for single kingtide event
HashMap<String, String> kt = new HashMap<String, String>();
// adding each child node to HashMap key => value
kt.put(KEY_DATE, date);
kt.put(KEY_LAT, lat);
kt.put(KEY_LNG, lng);
kt.put(KEY_LOC, loc);
kt.put(KEY_TIME, time);
Log.w("Rakshak", KEY_DATE+KEY_LAT+KEY_LNG+KEY_LOC+KEY_TIME);
// adding the kingtide to the kingtide hash map. this will be used to fill up the list view
kingTideList.add(kt);
}
} catch (JSONException e) {
Log.e("Rakshak", "JSONException "+e.getMessage()); // this prints "JSONException Value [{"Latitude":-19.9078861,"Location":"Abbot....." and the rest of the JASON(all of it)
}
}
else
Log.w("Rakshak", "JASON string is null");
return null;
}
the Service handler class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.e("Rakshak", "UnsupportedEncodingException "+e.getMessage());
} catch (ClientProtocolException e) {
Log.e("Rakshak", "ClientProtocolException "+e.getMessage());
} catch (IOException e) {
Log.e("Rakshak", "IOException "+e.getMessage());
}
Log.w("Rakshak", "In the service handeler: this is a test");
return response;
}
}
Part of the stacktrace:
03-14 10:09:56.861: E/Rakshak(7037): JSONException Value [{"Latitude":-19.9078861,"Location":"Abbot Point","Longitude":148.08467259999998,"DateRange":"1–3 January 2014","HighTideOccurs":"2014-01-02T09:47:00","State":"QLD"},{"Latitude":-27.477819,"Location":"Brisbane
The URL for the JASON file is "http://witnesskingtides.azurewebsites.net/api/kingtides"
NOTE: I know it looks like a XML file but it is JASON . Just run it through a validator/viewer and see for your self if you want.
My question in why am I getting a JASON exception and how do I fix it.
The Response you are getting is XML response and you are trying to parse it as JSON.
Refer this tutorial on XML parsing
When getting the contents, I get this back (part of it):
[
{
"Location": "Abbot Point",
"State": "QLD",
"HighTideOccurs": "2014-01-02T09:47:00",
"DateRange": "1–3 January 2014",
"Latitude": -19.9078861,
"Longitude": 148.08467259999998
},
{
"Location": "Brisbane Bar",
"State": "QLD",
"HighTideOccurs": "2014-01-02T10:16:00",
"DateRange": "1–3 January 2014",
"Latitude": -27.477819,
"Longitude": 153.01889119999998
},
...
]
This means that your object is already an array. Try to change this in your code:
//JSONObject jsonObj = new JSONObject(jsonStr);
Log.w("Rakshak", "in the try before the JASON");
// Getting JSON Array node
kingtide = new JSONArray(jsonStr);
since the returned jsonStr is already an array (and not an object with an array-attribute called "JASON").
Confirmed that the service is in fact returning a JSON response (you can check this in a tool like Fiddler). The default response from the API is JSON. The reason you are seeing XML by clicking the link provided in the question is because the browser is requesting a content type of application/xml, so that is what the browser shall receive.
I don't know the answer to your actual problem though, as the JSON seems to validate in everything I've tried. Maybe an incompatibility with the Android parser?
I'd suggest trying a different parser in your Android app to parse the response from the server. I've used Gson before which was easy to set up and use.
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
The service returns an array of objects so instead of
JSONObject jsonObj = new JSONObject(jsonStr);
use
JSONArray jsonArray = new JSONArray(jsonStr);
and continue from there.
Update: Disregard my answer below...
Not to burst your repeated notion of the fact that it is JSON, it is not.
The response that your code gets back is plain XML.
However,
The resource you are requesting ( http://witnesskingtides.azurewebsites.net/api/kingtides ) supports both XML formatted responses and JSON formatted responses. It probably all has to do with the Accept headers that are missing from your request in your code or are set to application/xml or text/xml or something similar in your ServiceHandler.
When your code gets the response of the server, the server does not find an Accept header and returns XML format.
When the JSON validator sites, that you mention, request the same URL, they likely add an Accept header that tells the server to return the response in JSON format.
I'm not sure how the ServiceHandler class works, but when you create a GET request you should add the HTTP Header with name Accept and value application/json and then issue the request. You now will get JSON back instead of XML.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
I am new to Android Programming, I am trying to parse JSON with android
and trying to invoke the web service from this yahoo URL:
http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select+*+from+yahoo.finance.quote+where+symbol+in+(%22MSFT%22)
Error: However, I get error when I try to run this simple application on the emulator:
code:
MainActivity.java
package com.example.jsonparser;
public class MainActivity extends Activity {
//The JSON Rest Service I will pull from:
static String yahooStockInfo ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22MSFT%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
//Will hold the values I pull from the JSON
static String stockSymbol = "";
static String stockDaysLow = "";
static String stockDaysHigh = "";
static String stockChange = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(yahooStockInfo);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the
// Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
// Holds Key Value pairs from a JSON source
JSONObject jsonObject;
try {
// Print out all the data read in
// Log.v("JSONParser RESULT ", result);
// Delete cbfunc( and ); from the results
result = result.substring(7);
result = result.substring(0, result.length()-2);
// Get the root JSONObject
jsonObject = new JSONObject(result);
// Get the JSON object named query
JSONObject queryJSONObject = jsonObject.getJSONObject("query");
// Get the JSON object named results inside of the query object
JSONObject resultsJSONObject = queryJSONObject.getJSONObject("results");
// Get the JSON object named quote inside of the results object
JSONObject quoteJSONObject = resultsJSONObject.getJSONObject("quote");
// Get the JSON Strings in the quote object
stockSymbol = quoteJSONObject.getString("symbol");
stockDaysLow = quoteJSONObject.getString("DaysLow");
stockDaysHigh = quoteJSONObject.getString("DaysHigh");
stockChange = quoteJSONObject.getString("Change");
// EXTRA STUFF THAT HAS NOTHING TO DO WITH THE PROGRAM
Log.v("SYMBOL ", stockSymbol);
Log.v("Days Low ", stockDaysLow);
Log.v("Days High ", stockDaysHigh);
Log.v("Change ", stockChange);
// GET ARRAY DATA
JSONArray queryArray = quoteJSONObject.names();
List<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
for(String item : list){
Log.v("JSON ARRAY ITEMS ", item);
}
// END OF GET ARRAY DATA
// Gets the first item in the JSONObject
JSONArray objectArray = resultsJSONObject.names();
// Prints out that first item in the JSONObject
Log.v("JSON NEXT NODE ", objectArray.getString(0));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result) {
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Stock: " + stockSymbol + " : " + stockChange);
line2.setText("Days Low: " + stockDaysLow);
line3.setText("Days High: " + stockDaysHigh);
}
}
#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;
}
}
code main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="#+id/line1"
style="#android:style/TextAppearance.Medium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/line2"
style="#android:style/TextAppearance.Medium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/line3"
style="#android:style/TextAppearance.Medium"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
please help me out, iam eager to learn
The url to get json from
Not knowing the actual error it's hard to see whats wrong with your code but looking at the json result from the url you are trying to parse I noticed that it doesn't start with cbfunc( which you're trying to clean up in the rows:
// Delete cbfunc( and ); from the results
result = result.substring(7);
result = result.substring(0, result.length()-2);
This means you're just corrupting the json just before trying to parse it. It's better to do the clean up with regex and String.replaceFirst(...) or just plain old String.replace(...).
In my application, I have a food activity in which the user enters his/her food, and the app requests the food, by the name entered by the user, from a MYSQL database. In the case that the entered food not exist, the string returned by the database should be null.
Currently, when this happens, an exception to occurs since the null value cannot be parsed to a JSON array. My question is: "Is there a way to prevent my app from force closing? Can I handle the exception and display a toast notifying the user that the requested food was not found?" I would like to prevent the app from crashing, and, rather, fail gracefully.
Please help me.
I've shown the relevant code in my application..
private class LoadData extends AsyncTask<Void, Void, String>
{
private JSONArray jArray;
private String result = null;
private InputStream is = null;
private String entered_food_name=choice.getText().toString().trim();
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... params)
{
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/food.php");
nameValuePairs.add(new BasicNameValuePair("Name",entered_food_name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//convert response to string
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result =sb.toString();
result = result.replace('\"', '\'').trim();
}
catch(Exception e){
Log.e("log_tag", " connection" + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result)
{
try{
String foodName="";
int Description=0;
jArray = new JSONArray(result); // here if the result is null an exeption will occur
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
foodName=json_data.getString("Name");
.
.
.
.
.
}
catch(JSONException e){
**// what i can do here to prevent my app from crash and
// make toast " the entered food isnot available " ????**
Log.e("log_tag", "parssing error " + e.toString());
}
}
}
This will fix your code:
jArray = (result == null) ? new JSONArray() : new JSONArray(result);
Now that you have an empty JSONArray, you will be able to test for null JSONObjects later in your program. Many of the JSON methods return a JSONObject if one is found, of null if none exists.
You might also want to initialize your JSONObject with the no-argument JSON constructor, rather than simply setting it to null. It will avoid problems when passing it to other JSON methods (such as using it in a constructor to a JSONArray():
JSONObject json_data = new JSONObject();
Finally, if you're still getting JSONExceptions, it's because you're not actually passing a valid JSON string to the constructor. You can print out the value of result to the log:
Log.d("JSON Data", result);
You may see some SQL error text or if you retrieve from a web server, then an HTTP error code (404 is common if you don't have your url correct).
If your result does look like JSON, then you can verify whether it's actually valid JSON or not using the JSONLint validator. It will help you catch any errors you may have, especially if you're formatting the JSON yourself.
Are you looking to capture the Exception and log it (remotely) to aid in crash reporting and debugging? I've used this package to remotely capture Exceptions and it works pretty good:
http://code.google.com/p/android-remote-stacktrace/
I want to write an Android application that can display some data received(polled) from an internet resource.
I guess that I need to write some logic that will periodically call and get data from some endpoint, parse the response and display it. Is there a good tutorial for all this steps?
I know very little about Android programming at the momment and maybe it is better to start with something simpler. I just want to know what to look for while learning an gather some resources on this.
What you want to do is developing a rest api that provides data for your android app. E.g. you website has some content that you want use in your app, then you could write a php script that just returns that data in a specific format.
E.g. mysite.net/rest/fetchAllLocations.php?maybe_some_parameters
This would return locations in e.g. json format, here is an example how that looks like:
[{"id":1,"shop_lng":8.5317153930664,"shop_lat":52.024803161621,"shop_zipcode":33602,"shop_city":"Bielefeld","shop_street":"Arndtstra\u00dfe","shop_snumber":3,"shop_name":"M\u00fcller","shop_desc":"Kaufhaus"}]
Here is an example for a rest api request:
http://shoqproject.supervisionbielefeld.de/public/gateway/gateway/get-shops-by-city/city/Bielefeld
So when you have your rest api set up you can deal with receiving that data with your android phone. I use a static method to get this data:
public class JsonGrabber{
public static JSONArray receiveData(){
String url = "your url";
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
JSONArray jArray = null;
try{
jArray = new JSONArray(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Well thats all, once you have your data in json format you just have to parse it:
JSONArray test = (JSONArray) JsonGrabber.receiveData()
try {
for(int i=0;i<test.length();i++){
JSONObject json_data = test.getJSONObject(i);
int id = json_data.getInt("id");
}
}
The web request should run in another thread, because it can be a time consuming process. So you need to deal with AsyncTask. Here are some resources:
Painless Threading
Multithreading for performance
Hello Android Tutorial