I'm trying to parse json using an url. I'm able to achive it by using Temporary url but when I use my main host url, json returns html values?
Temporary URL
(http://md-plesk-web9.webhostbox.net:8880/sitepreview/http/glossymob.asia/Webservice.asmx/SpecificCategory?category=real%20estate&location=Madurai)
My Code
// url to make request
private static String url = "http://md-plesk-web9.webhostbox.net:8880/sitepreview/http/glossymob.asia/Webservice.asmx/SpecificCategory?category=hotel&location=Madurai";
// JSON Node names
private static final String TAG_MAIN ="hotel";
private static final String TAG_VALUE = "Madurai";
private static final String TAG_ID = "id";
private static final String TAG_CATEGORY = "category";
private static final String TAG_TYPE = "type";
private static final String TAG_NAME = "name";
private static final String TAG_BANNER = "banner";
private static final String TAG_LOGO = "logo";
private static final String TAG_ABOUT = "about";
private static final String TAG_CONTACT = "contact";
private static final String TAG_MAP = "map";
private static final String TAG_MAP_LAT_LONG = "lat_long_1";
private static final String TAG_MAPLATITUDE = "latitude";
private static final String TAG_MAPLONGITUDE = "longitude";
private static final String TAG_CATEGORY_TOTAL = "total";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.v("exact string value", json.toString());
try {
// Getting Array of Contacts
JSONObject js= json.getJSONObject(TAG_MAIN);
int ival = js.getInt(TAG_CATEGORY_TOTAL);
contacts = js.getJSONArray(TAG_VALUE);
Log.v("Total:", ""+ival);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String category = c.getString(TAG_CATEGORY);
String type = c.getString(TAG_TYPE);
String name = c.getString(TAG_NAME);
String banner = c.getString(TAG_BANNER);
String logo = c.getString(TAG_LOGO);
String about = c.getString(TAG_ABOUT);
String contact = c.getString(TAG_CONTACT);
Log.v("Values:", id+"--"+category+"--"+type+"--"+name+"--"+banner+"--"+logo+"--"+about+"--"+contact);
// Phone number is agin JSON Object
JSONObject mapval = c.getJSONObject(TAG_MAP);
JSONArray con = js.getJSONArray(TAG_VALUE);
JSONObject mapvalues = con.getJSONObject(0);
String latitude = mapvalues.getString(TAG_MAPLATITUDE);
String longitude = mapvalues.getString(TAG_MAPLONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_CATEGORY, category);
map.put(TAG_TYPE, type);
map.put(TAG_NAME, name);
/*Log.v("Received json values", ""+map.toString());*/
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
values i'm getting by running this is exact json
01-02 12:03:38.300: V/exact string value(30124): {"hotel":{"total":1,"Madurai":[{"id":"3","logo":"www.glossymob.com\/soli\/MapMadurai\/3_logo_laptop-computer.jpg","category":"Hotel","name":"araas","map":{"lat_long_1":{"longitude":"76.9000","latitude":"8.5000"}},"about":"test","type":"Silver","contact":"test","banner":"www.glossymob.com\/soli\/MapMadurai\/3_banner_laptop-computer.jpg"}]}}
01-02 12:03:38.300: V/Total:(30124): 1
01-02 12:03:38.300: V/Values:(30124): 3--Hotel--Silver--araas--www.glossymob.com/soli/MapMadurai/3_banner_laptop-computer.jpg--www.glossymob.com/soli/MapMadurai/3_logo_laptop-computer.jpg--test--test
When I try to replace this
Main URL
(http://www.glossymob.asia/Webservice.asmx/SpecificCategory?category=real%20estate&location=Madurai)
Values I'm getting is
01-02 11:07:27.116: V/json string value(29330): <html>
<head>
<title>Runtime Error</title>
<style> body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Lucida Console";font-size: .9em} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1> <h2> <i>Runtime Error</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "> <b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine. <br><br>
<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".<br><br>
<table width=100% bgcolor="#ffffcc"> <tr> <td> <code><pre><!-- Web.Config Configuration File --><configuration> <system.web> <customErrors mode="Off"/> </system.web></configuration></pre></code> </td> </tr> </table>
<br> <b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.<br><br>
<table width=100% bgcolor="#ffffcc"> <tr> <td> <code><pre><!-- Web.Config Configuration File --><configuration> <system.web> <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/> </system.web></configuration></pre></code> </td> </tr>
</table> <br>
</body>
</html>
i'm handling that Xml data By replacing that in string and my json returns the exact json string values. Look at my JSONParser class.
package com.androidhive.jsonparsingtest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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) {
line = line.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
line = line.replace("<string xmlns=\"http://tempuri.org/\">","");
line = line.replace("</string>","");
Log.v("string value", line);
sb.append(line);
//Log.v("sbstring value", sb.toString());
}
is.close();
json = sb.toString();
Log.v("json string value", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
your response is :-
<string xmlns="http://tempuri.org/">
{"real estate":{"Madurai":[{"id":"5","category":"real estate","type":"Silver","name":"Heera","banner":"www.glossymob.com/soli/MapMadurai/5_banner_laptop-computer.jpg","logo":"www.glossymob.com/soli/MapMadurai/5_logo_laptop-computer.jpg","about":"test","contact":"test","map":{"lat_long_1":{"latitude":"10.00","longitude":"9.50"}}} ],"total":1} }
</string>
Now first you need to replace with
responseString = responseString.replace("<string xmlns=\"http://tempuri.org/\">","");
responseString = responseString.replace("</string>","");
please convert the string to JSONObject after replacing above lines.
It is not pure JSON. It has XML tags in it. Either use XML only, or JSON.
It would be easy if you just remove the XML tags on the top and the bottom, and go ahead with the JSON parsing.
You are getting JSON response inside <string> i.e. XML, so first you have to retrieve JSON data from that tag.
{"real
estate":{"Madurai":[{"id":"5","category":"real
estate","type":"Silver","name":"Heera","banner":"www.glossymob.com/soli/MapMadurai/5_banner_laptop-computer.jpg","logo":"www.glossymob.com/soli/MapMadurai/5_logo_laptop-computer.jpg","about":"test","contact":"test","map":{"lat_long_1":{"latitude":"10.00","longitude":"9.50"}}}
],"total":1} }
Solution:
Call parse() once you received the data from web.
For example:
XMLParser parser = new XMLParser();
JSONArray jsonRes = parser.parse(response.getEntity().getContent());
// response is the HTTPResponse object
Here is the XMLParser class:
public class XMLParser extends DefaultHandler {
private static String ROOT_ELEMENT = "string";
private StringBuffer data = new StringBuffer();
private JSONArray jsonData;
public XMLParser() {
}
public JSONArray parse(InputStream in) {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(in, this);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return jsonData;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
data.replace(0, data.length(), "");
if (localName.equalsIgnoreCase(ROOT_ELEMENT)) {
jsonData = new JSONArray();
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
data.append(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase(ROOT_ELEMENT)){
try {
jsonData = new JSONArray(data.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON object to listView
i have a json data on server and want to retrive it and show it in my android listview..sorry if this is duplicate question please give me some suggestion to start from stratch
answer will be appreciated thanks
This may help you..
Your Actmain class
Actmain.java
public class Actmain extends Activity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
private ArrayList<HashMap<String, String>> _alistHashmap;
private Clsgetjson getjson;
// contacts JSONArray
private JSONArray Jarray = null;
private JSONObject jobj;
private Listview lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creating JSON Parser instance
getjson = new Clsgetjson();
_alistHashmap = new ArrayList<HashMap<String, String>>();
lv=(listview)findviewbyid(R.id.lv);
jobj= getjson.getJSONFromUrl(url);
try {
// Getting Array of Contacts
Jarray = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject jobject = Jarray.getJSONObject(i);
// Storing each json item in variable
String id = jobject.getString(TAG_ID);
String name = jobject.getString(TAG_NAME);
String email = jobject.getString(TAG_EMAIL);
String address = jobject.getString(TAG_ADDRESS);
String gender = jobject.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = jobject.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
//now set your adapter to listview (you can do this under buttons onclick event)
String[] from=new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE };
int[] to= new int[] {R.id.name, R.id.email, R.id.mobile }
SimpleAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.raw_lv,from,to);
lv.setAdapter(adapter);
now Clsgetjson.java
public class Clsgetjson {
static JSONObject jObj = null;
static String strjson = "";
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
strjson=EntityUtility.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(strjson);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
or with parameter
List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
nvp.add(new BasicNameValuePair("function", "login"));
nvp.add(new BasicNameValuePair("uname", username));
nvp.add(new BasicNameValuePair("pwd", pass)));
add this in request
if(nvp!=null)
hpost.setEntity(new UrlEncodedFormEntity(nvp));
everything else is same as above
First you will want to fetch your JSON
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class WebServiceConnector
{
/**
* Makes the HTTP GET request to the provided REST url
* #param requestUrl the URL to request
* #return The string of the response from the HTTP request
*/
public String callWebService(String requestUrl)
{
String deviceId = "Android Device";
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(requestUrl);
request.addHeader("deviceId", deviceId);
ResponseHandler handler = new BasicResponseHandler();
String result = "";
try
{
result = httpclient.execute(request, handler);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e(TAG, "ClientProtocolException in callWebService(). " + e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, "IOException in callWebService(). " + e.getMessage());
}
httpclient.getConnectionManager().shutdown();
Log.i(TAG, "**callWebService() successful. Result: **");
Log.i(TAG, result);
Log.i(TAG, "*****************************************");
return result;
}
}
Then you need to parse that json. There are several JSON parsers, JAXB, Jackson... If it's simple structure, the easiest is probably to just parse it on your own using org.json classes (included in Android already) like org.json.JSONArray, org.json.JSONObject and org.json.JSONException. Generate your array/list of items from the json and then connect it to a listview using an ArrayAdapter like you normally would. Happy coding!
I am having the following code
{"sports" :[{"name" :"baseball","id" :1,"links" :{"api" :{"sports" :{"href" :"http://api.espn.com/v1/sports/baseball"},"news" :{"href" :"http://api.espn.com/v1/sports/baseball/news"},"notes" :{"href" :"http://api.espn.com/v1/sports/baseball/news/notes"},"headlines" :{"href" :"http://api.espn.com/v1/sports/baseball/news/headlines"},"events" :{"href" :"http://api.espn.com/v1/sports/baseball/events"}}},"leagues" :[{"name" :"Major League Baseball","abbreviation" :"mlb","id" :10,"groupId" :9,"shortName" :"MLB","season" :{"year" :2012,"type" :2,"description" :"regular","startDate" :"2012-03-27T19:00:00Z","endDate" :"2012-10-05T06:59:59Z"},"week" :{"number" :23,"startDate" :"2012-08-28T19:00:00Z","endDate" :"2012-09-04T18:59:00Z"}}]}],"timestamp" :"2012-08-30T18:01:29Z","status" :"success"}
I want to parse the json objects, in sports object we are having another sports object how to parse inner json objects with array of elements.
I am trying with the following code:
public class BaseballActivity extends ListActivity{
private static String url = "http://api.espn.com/v1/sports/baseball?apikey=h29yphwtf7893hktfbn7cd5g";
private static final String TAG_SPORTS = "sports";
private static final String TAG_ID = "id";
private static final String TAG_TIMESTAMP = "timestamp";
private static final String TAG_NAME = "name";
private static final String TAG_NEWS = "news";
private static final String TAG_HEADLINES = "headlines";
private static final String TAG_LINKS = "links";
private static final String TAG_API = "api";
private static final String TAG_SPORTS1 = "sports";
private static final String TAG_HREF = "href";
JSONArray sports = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// HashMap for ListView
ArrayList<HashMap<String, String>> sportsList = new ArrayList<HashMap<String, String>>();
// creating Json parser instance
JSONParser jParser = new JSONParser();
// getting Json String from url
JSONObject json = jParser.getJSONFromUrl(url);
try{
// Getting Array of Contacts
sports = json.getJSONArray(TAG_SPORTS);
// looping through All Contacts
for(int i = 0; i < sports.length(); i++){
JSONObject c = sports.getJSONObject(i);
//String news = c.getString(TAG_NEWS);
// String headlines = c.getString(TAG_HEADLINES);
String name = c.getString(TAG_NAME);
// String timestamp = c.getString(TAG_TIMESTAMP);
String id = c.getString(TAG_ID);
// JSONObject links = c.getJSONObject(TAG_LINKS);
// JSONObject api = c.getJSONObject(TAG_API);
// JSONObject sports = c.getJSONObject(TAG_SPORTS1);
// String href = c.getString(TAG_HREF);
HashMap<String, String> map = new HashMap<String, String>();
// map.put(TAG_TIMESTAMP, timestamp);
map.put(TAG_NAME, name);
// map.put(TAG_NEWS, news);
// map.put(TAG_HEADLINES, headlines);
map.put(TAG_ID, id);
// map.put(TAG_HREF, href);
sportsList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, sportsList,
R.layout.list_item,
new String[]{TAG_NAME,TAG_ID} , new int[] {
R.id.id,R.id.name});
setListAdapter(adapter);
}}
ublic class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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 JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}}
Name and id can be displayed when i try to parse inner objects there is no output please help me.
You should have a class Sports that has the objects that come on your JSON string
Than this should do the job for you
JSONObject jObject = new JSONObject(json);
jObject.getJSONObject("sports");
this will make a JSONOBJECT outof your JsonString
Than you will use Googles Gson library to do the following
Gson gson = new Gson();
Sports sports = gson.fromJson(jObject.toString(), Sports.class);
I advise u to have a class to handle all the WebReqeuisitions and not have this code on your Activitys makes your project more structured and your code will be cleaner
i'm posting here in order to get some issues about my own project problem.
I want to connect to my webservice from my Android application and get this info into good sources. I'm working with JSON files (wich are good) but only containing JSON Objects.
I used this pretty good source (working very well on his example): http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
You can look at my JSON File :
[
{
"id": "2",
"title": "Printemps du cinema",
"content": "Decouvrez plein de nouveaux films durant la semaine du printemps du cinema.",
"date": "2012-07-04",
"author": "Nicolas Jeannin",
"zone": "Mandelieu",
"area": "Cannes"
},
{
"id": "4",
"title": "Festival de Cannes",
"content": "Venez assister a la montee des marches du prestigieux festival !",
"date": "2012-05-26",
"author": "Nicolas Teboul",
"zone": "Cannes",
"area": "Cannes"
}
]
I tried to make it running with his method but with a JSON Array composed of 1 element.
I always have similar errors :
"Error parsing data org.json.Excption:Value[{"content":".........}] ..cannot be converted to JSONObject."
You can look at my Activity below:
public class AndroidJSONParsingActivity extends ListActivity
{
// url to make request
private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8";
//private static String url = "http://twitter.com/statuses/public_timeline.json";
//private static String url = "http://api.androidhive.info/contacts/";
//JSON names
private static final String TAG_content = "content";
private static final String TAG_zone = "zone";
private static final String TAG_id = "id";
private static final String TAG_area = "area";
private static final String TAG_title = "title";
private static final String TAG_date = "date";
private static final String TAG_author = "author";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
JSONArray event = null;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
event = json.getJSONArray("");
JSONObject c = event.getJSONObject(0);
// Storing each json item in variable
String id = c.getString(TAG_id);
String title = c.getString(TAG_title);
String content = c.getString(TAG_content);
String date = c.getString(TAG_date);
String author = c.getString(TAG_author);
String zone = c.getString(TAG_zone);
String area = c.getString(TAG_area);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_content, content);
map.put(TAG_title, title);
map.put(TAG_author, author);
// adding HashList to ArrayList
newsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, newsList,R.layout.list_item,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_content, name);
in.putExtra(TAG_title, cost);
in.putExtra(TAG_author, description);
startActivity(in);
}
});
}
}
And this is the JSONParser :
package com.androidhive.jsonparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String jsonstr = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
//HttpGet httpGet = new HttpGet(url);
//HttpResponse httpResponse = httpClient.execute(httpGet);
HttpResponse httpResponse = httpClient.execute(httpPost);
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();
jsonstr = 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 JSONObject(jsonstr);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing de Mon fichier: " + e.toString());
}
// return JSON String
return jObj;
}
}
Thanks to help me guys. :)
This is because your JSON defines an JSON array and you try to parse it as JSON object - change it to JSONArray in your parser class and you shall be fine.
Another issue is memorz management - you are reallocating strings and parse with vanilla JSON parser provided with android. This works, but has terrible memory consumption and lot of allocations - pretty slow for bigger data. Use pull parser instead ( like GSON, scaled down version is only 16K )
You may also consider kind of databinding to create java objects out of JSON - you may grab my library ( also available on maven central):
https://github.com/ko5tik/jsonserializer
Then it will be as easy as:
InputStream inputStream = getResources().openRawResource(preferences.getRecognitionConfig());
InputStreamReader reader = new InputStreamReader(inputStream);
JsonReader jreader = new JsonReader(reader);
jreader.setLenient(true);
final RecognitionDataContainer recognitionContainer = JSONUnmarshaller.unmarshall(jreader, RecognitionDataContainer.class);
reader.close();
(RecognitionDataContainer is top level object resembling JSON structure )
i want to build a simple app that will fetch records from a remote db and store some records as well
i use php-mysql-apache(wamp) and my php file is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/json; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
mysql_query("SET NAMES 'greek'", $link);
$db_selected = mysql_select_db('products', $link);
if (!$db_selected) {
die ('Can\'t use roflcopter: ' . mysql_error());
}
$id = $_GET['id'];
$sql = "SELECT * FROM `items` WHERE `id` = ".$id. " ORDER BY `id` ASC";
$result = mysql_query($sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
// $message .= 'Whole query: ' . $query;
die($message);
}
$json = NULL;
while ($data_array[] = mysql_fetch_assoc($result)){
$json = json_encode($data_array);
}
echo $json;
?>
</body>
</html>
and the response that i take when i run it from the browser is
[{"id":"1590774","name":"Nokia C7","descr":"????. ??????? Symbian 3, ????? 3,5\", 360 ? 640 pixels, Amoled, Capacitive ?????\/???????? 8GB","price":"339","stock":"3"}]
(it doesn't recognize the greek caracters - what am i supposed to do?)
What code should i write on eclipse so as to fetch and display that row??
Actually i'm trying to use a project found on the internet as an example which fetches this json array
http://api.androidhive.info/contacts/
and the android project consists of 3 java Activities :
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
the second activity is the Json Parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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 JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and the third one is used to display results to a listview
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String cost = in.getStringExtra(TAG_EMAIL);
String description = in.getStringExtra(TAG_PHONE_MOBILE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
i m trying to change this example to adjust it to my json response, the first thing i realize is that my json array doesn't have any tag like the example's "contacts" tag so as to use it as in the example
contacts = json.getJSONArray(TAG_CONTACTS);
another thing is that for my app i need to send a parameter to fetch data for a specific id
i have a table with fields : id, name, desciption, price, stock
i try my url as
"http://localhost/items.php?id=1590774"
or
"http://localhost/items.php"
passing the parameter this way
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id","1590774"));
im a begginner , so i'd appreciate your help...
You should try to add a parameter to your DefaultHttpClient instance for the character-set to use:
...
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(params);
...
If HTTP.UTF_8 does not work for you, from the HTTP class you can select the appropriate value.
In case this doesn't solve the problem, please attach some more logcat output.
I'm trying to integrate an API into an android application I am writing, but am having a nightmare trying to get the JSON array. The API has a URL that returns a an JSON array, but having never used JSON before I have no idea how this works, or how to do it.
I've looked and found tons, and tons of examples, but nothing to explain why/how it is done. Any help understanding this would be greatly appreciated.
This is what I've ended up with, again with no understanding of JSON, it was a shot in the dark on my part (using examples/tutorials as a guide)...but it doesn't work :(
import org.json.*;
//Connect to URL
URL url = new URL("URL WOULD BE HERE");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
//Get Data from URL Link
int ok = connection.getResponseCode();
if (ok == 200) {
String line = null;
BufferedReader buffer = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((line = buffer.readLine()) != null)
sb.append(line + '\n');
//FROM HERE ON I'm Kinda Lost & Guessed
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString()); //ERROR HERE:complains it dosn't know what JSONValue is
JSONArray array = (JSONArray)obj.get("response");
for (int i=0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("name")); //Used to debug
}
}
UPDATE/SOLUTION:
So, it turns out that there was nothing wrong w/t the code. I was missusing what I thought it returns. I thought it was a JSONObject array. In actuality it was a JSONObjects wrapped in an array, wrapped in a JSONObject.
For those interested/ having similar issues, this is what I ended up with. I broke it into two methods. First connect/download, then:
private String[] buildArrayList(String Json, String Find) {
String ret[] = null;
try {
JSONObject jObject = new JSONObject(Json);
JSONArray jArray = jObject.getJSONArray("response");
ret = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String var = json_data.getString(Find);
ret[i] = var;
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
1) use webservice to download your required Json string
2) convert it to your desired object using Google Gson
Gson gson = new Gson();
MyClass C1 = gson.fromJson(strJson, MyClass.class);
Here you used JSONValue.parse() that is invalid.
Insted of that Line write this code:
JSONObject obj = new JSONObject(<String Value>);
Ok my friend, i solved the same problem in my app with the next code:
1.- Class to handle the Http request:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONObject jObj1 = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
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();
//Log.e("JSONObject(JSONParser1):", json);
} catch (Exception e) {
Log.e("Buffer Error json1" +
"", "Error converting result json1:" + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj1 = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser1:", "Error parsing data json1:" + e.toString());
}
// return JSON String
return jObj;
}
}
Later, a class to handle the json info (Arrays, Objects, String, etc...)
public class ListViewer extends ListActivity{
TextView UserName1;
TextView LastName1;
// url to make request
private static String url = "http://your.com/url";
// JSON Node names
public static final String TAG_COURSES = "Courses"; //JSONArray
//public static final String TAG_USER = "Users"; //JSONArray -unused here.
//Tags from JSon log.aspx All Data Courses.
public static final String TAG_COURSEID = "CourseId"; //Object from Courses
public static final String TAG_TITLE = "title";
public static final String TAG_INSTRUCTOR = "instructor";
public static final String TAG_LENGTH = "length";
public static final String TAG_RATING = "Rating"; //Object from Courses
public static final String TAG_SUBJECT = "subject";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_STATUS = "Status"; //Object from Courses
public static final String TAG_FIRSTNAME = "FirstName"; //Object from User
public static final String TAG_LASTNAME = "LastName"; //Object from User
// contacts JSONArray
JSONArray Courses = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
// Hashmap for ListView
final ArrayList<HashMap<String, String>> coursesList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance (json2)
JSONParser2 jParser2 = new JSONParser2();
// getting JSON string from URL json2
final JSONObject json2 = jParser2.getJSONFromUrl(url);
try {
// Getting Array of Contacts
Courses = json2.getJSONArray(TAG_COURSES);
// looping through All Courses
for(int i = 0; i < Courses.length(); i++){
JSONObject courses1 = Courses.getJSONObject(i);
// Storing each json item in variable
String courseID = courses1.getString(TAG_COURSEID);
//String status = courses1.getString(TAG_STATUS);
String Title = courses1.getString(TAG_TITLE);
String instructor = courses1.getString(TAG_INSTRUCTOR);
String length = courses1.getString(TAG_LENGTH);
String rating = courses1.getString(TAG_RATING);
String subject = courses1.getString(TAG_SUBJECT);
String description = courses1.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_COURSEID,courseID);
map.put(TAG_TITLE, Title);
map.put(TAG_INSTRUCTOR, instructor);
map.put(TAG_LENGTH, length);
map.put(TAG_RATING, rating);
map.put(TAG_SUBJECT, subject);
map.put(TAG_DESCRIPTION, description);
//adding HashList to ArrayList
coursesList.add(map);
}} //for Courses
catch (JSONException e) {
e.printStackTrace();
}
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, coursesList,
R.layout.list_courses,
new String[] { TAG_COURSEID, TAG_TITLE, TAG_INSTRUCTOR, TAG_LENGTH, TAG_RATING, TAG_SUBJECT, TAG_DESCRIPTION }, new int[] {
R.id.txt_courseid, R.id.txt_title, R.id.txt_instructor, R.id.txt_length, R.id.txt_rating, R.id.txt_topic, R.id.txt_description });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
//#Override --------check this override for onClick event---------
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String courseID = ((TextView) view.findViewById(R.id.txt_courseid)).getText().toString();
String Title = ((TextView) view.findViewById(R.id.txt_title)).getText().toString();
String instructor = ((TextView) view.findViewById(R.id.txt_instructor)).getText().toString();
String length = ((TextView) view.findViewById(R.id.txt_length)).getText().toString();
String rating = ((TextView) view.findViewById(R.id.txt_rating)).getText().toString();//Check place in layout
String subject = ((TextView) view.findViewById(R.id.txt_topic)).getText().toString();// <- HERE
String description = ((TextView) view.findViewById(R.id.txt_description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(TAG_COURSEID, courseID);
in.putExtra(TAG_TITLE, Title);
in.putExtra(TAG_INSTRUCTOR, instructor);
in.putExtra(TAG_LENGTH, length);
in.putExtra(TAG_RATING, rating);
in.putExtra(TAG_SUBJECT, subject);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});//lv.SetOnclickListener
}//onCreate
}// Activity
in this case, i'll get the Arrays, objects... Hope this give you ideas...