android - error while parsing JSON response from server - android
I'll try be to brief, please ask if something is unclear. I'm getting a user's audio list from vk.com (a large social network in case someone doesn't know). The response looks like:
{"response":[{
"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
Usually it is much longer since a user can have hundreds or even thousands of tracks on his profile. Artist and title can also contain cyrillic letters, that's why I used UTF-8 in the Parser. I'm not really familiar with JSON, I'm trying to parse the response using the following:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public static JSONObject getJSONFromUrl(String url) {
try {
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, "UTF-8"), 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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
But the app crashes with an IllegalArgumentException exception (Illegal character in scheme at index 0):
02-27 10:37:35.870: E/AndroidRuntime(21038): FATAL EXCEPTION: main
02-27 10:37:35.870: E/AndroidRuntime(21038): java.lang.RuntimeException: Unable to resume activity {com.vadim.android.vk_player/com.vadim.android.vk_player.MainActivity}: java.lang.IllegalArgumentException: Illegal character in scheme at index 0: {"response":[{"aid":191819427,"owner_id":13590837,"artist":"Buena Vista Social Club","title":"El Cuarto de Tula","duration":445,"url":"http:\/\/cs548.userapi.com\/u361189\/audios\/b8c6a3bdb0bb.mp3","lyrics_id":"1133390"},{"aid":191477921,"owner_id":13590837,"artist":"Buena Vista Social Club","title":"Hasta Siempre Comandante Che Guevara","duration":193,"url":"http:\/\/cs4515.userapi.com\/u7198823\/audios\/5fafa2136e16.mp3","lyrics_id":"2876258"},{"aid":190900891,"owner_id":13590837,"artist":"Slade","title":"Oh la la in L.A.","duration":229,"url":"http:\/\/cs4962.userapi.com\/u9811745\/audios\/ed7445d38bef.mp3"},{"aid":188976833,"owner_id":13590837,"artist":"PR-MEX","title":"У Билли Гейтса","duration":126,"url":"http:\/\/cs5002.userapi.com\/u4693819\/audios\/a1899ebb7716.mp3","lyrics_id":"5201762"},{"aid":186998450,"owner_id":13590837,"artist":"The Best Latino Dance","title":"2Sweet-Bomba Latina","duration":213,"url":"http:\/\/cs4341.userapi.com\/u49441496\/audios\/788cd8243842.mp3"},{"aid":186486990,"owner_id":13590837,"artist":"001 Track No05 Latin music 9","title":"001 Track No05 Latin music 9","duration":226,"url":"http:\/\/cs4341.userapi.com\/u25293142\/audios\/277e46d451d4.mp3"},{"aid":185813300,"owner_id":13590837,"artist":"Латино ?? ","title":" Самбо","duration":190,"url":"http:\/\/cs4206.userapi.com\/u2183525\/audios\/678fe97a8700.mp3","lyrics_id":"4944025"},{"aid":185805191,"owner_id":13590837,"artist":"Дженифер Лопес","title":"Латино","duration":212,"url":"http:\/\/cs4220.userapi.com\/u33799853\/audios\/685f4bc7024d.mp3","lyrics_id":"3985793"},{"aid":185355131,"owner_id":13590837,"artist":"Latino","title":"Afa-Na-Na","duration":174,"url":"http:\/\/cs548.userapi.com\/u406078\/audios\/5e771c6958c4.mp3","lyrics_id":"8840070"},{"aid":185167860,"owner_id":13590837,"artist":"Batuka-Latino_StepMIX(137bpm)","title":"demo","duration":232,"url":"http:\/\/cs4863.userapi.com\/u43189860\/audios\/b6a08490146a.mp3","lyrics_id":"10200160"},{"aid":185143167,"owner_id":13590837,"artist":"Pr, Mex","title":"Ставил Windows программист","duration":130,"url":"http:\/\/cs4246.userapi.com\/u3476823\/audios\/75161ed38448.mp3","lyrics_id":"2012814"},{"aid":185141056,"owner_id":13590837,"artist":"Antony Melnyk, Sergiy Tykhanskyy ","title":"Debugging Song","duration":234,"url":"http:\/\/cs6126.userapi.com\/u42350435\/audios\/f83f20d8d754.mp3","lyrics_id":"36053942"},{"aid":185141033,"owner_id":13590837,"artist":"админ","title":"чистый дос","duration":173,"url":"http:\/\/cs4429.userapi.com\/u9853602\/audios\/2b77464f9193.mp3"},{"aid":184547392,"owner_id":13590837,"artist":"Geri Halliwell","title":"Mi chico latino (samba)","duration":194,"url":"http:\/\/cs5057.userapi.com\/u8186180\/audios\/67119f2af914.mp3"},{"aid":184022338,"owner_id":13590837,"artist":"Elena Paparizou","title":"My number one","duration":176,"url":"http:\/\/cs1092.userapi.com\/u830723\/audios\/25552d1f7e40.mp3","lyrics_id":"6640643"},{"aid":183519519,"owner_id":13590837,"artist":"Latino - Samba - Elena Paparizou","title":"Gigolo","duration":203,"url":"http:\/\/cs4405.userapi.com\/u3609345\/audios\/5255ecdda950.mp3","lyrics_id":"7216473"},{"aid":183219402,"owner_id":13590837,"artist":"David Bisbal ","title":" Llorare las penas (самба)","duration":260,"url":"http:\/\/cs5003.userapi.com\/u32245826\/audios\/fe718c40aed1.mp3"},{"aid":183110662,"owner_id":13590837,"artist":"Juanes","title":"La soledad","duration":193,"url":"http:\/\/cs4615.userapi.com\/u400878\/audios\/40abd9dcb4f5.mp3","lyrics_id":"7753114"},{"aid":180455728,"owner_id":13590837,"artist":"Guns N' Roses","title":"Sweet Child O' Mine","duration":356,"url":"http:\/\/cs5125.userapi.com\/u1412326\/audios\/1fc190388445.mp3","lyrics_id":"5582681"},{"aid":180317426,"owner_id":1359083
Any ideas what I'm doing wrong and what would be the correct way to parse the response of given format? There are a lot of apps using the same API so the JSON is correct.. No clue what's wrong here
Illegal Argument Exception comes in JSON case while reading it. So invalid json because of those urls. Also for next communication, place the logcat as the text pls.
Try to display the JSON response in JSONlint.com without this url part of :
"url": "http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"
You will find, the response will be validated properly.
I think there is some space characters present in the url part (between audio\/ and d100f76cb84e.mp3) which is coming from response:
"url": "http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"
Related
Downloading a JSON Array from a URL in Android
I'm trying to download a JSON file in this format [ { "CRN":"10001", "Course":"REG1" }, { "CRN":"10002", "Course":"REG2" } ] I understand how to use a JSONArray class once it is created but I don't know how to create the JSONArray object from the file. If the URL location of the file were to be "www.test.com" how would I go about downloading it in background upon the launch of my application so as to not interfere with the launching of the app but not require the user to manually download it themselves.
You might want to check out this helpful library: Retrofit It makes grabbing and parsing JSON data easy!
I think you should look for Android Web Service example. Where you can find info about 1.How to make a HTTP request to server (using URL eg. www.google.com) 2. How to handle Response from Server 3. How to parse JSON/XML response from Server etc. Here is the Simple Tutorial I Found for you. Android Web service for Log-in and Registration Just go through step by step. In the example we are making request to server for login and getting response then going ahead in app. Here is the code snipp. public class JSONParser { static InputStream is = null; static JSONObject jObj = 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("JSON", 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; } }
A good way to download the JSON file automatically, would be to launch an AsyncTask during your onCreate method of the home activity. JSON files are nothing more than text files in a special format, so the could be easily downloaded as a response from a HttpURLConnection, and then be treated as a String. A suggestion for parsing the JSON objets into Java objects would be the Jackson JSON Processor. You could use the class ObjectMapper of this library to automatically create the objects. If you are planing to implement the server side by yourself, and you also need a library to send JSON objects, you could use Jersey on both server and client.
Memory leak with Android app?
I have a simple Android app that reads some JSON data from a php file on my local server. It's very simple and up until about an hour ago it was working fine. However, after a little break (I didn't even turn my PC off), it's suddenly struggling with what seems like a memory leak, although I'm no expert on the subject. I'm not sure why all of a sudden this is happening, as I didn't change any code. But when I run the app my logcat slowly starts to fill with messages like this: "GC_CONCURRENT freed, 910K, 53% free 3167K/6727K....." The app eventually runs, but only after about 1-2 minutes of waiting. Anyway, I was wondering if someone could check my code or advise me what maybe causing this to happen. public static JSONArray getJSONfromURL(String url) { // initialize InputStream is = null; JSONArray jArray = null; String result = ""; // http post try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } // convert response to string try { 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 + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jArray = new JSONArray(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return jArray; } The JSON data isn't very large at all. Thanks for any advice.
BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8); You've allocated a buffer size of 8 bytes. That is very small. Unless you really know what you're doing, just use the default size with the alternative single-argument constructor: public BufferedReader(Reader in)
Well I changed the 'While' loop to this and performance increased dramatically: int len; char[] chars = new char[4*1024]; while((len = reader.read(chars))>=0) { sb.append(chars, 0, len); } It's still slower than I'd like, but at least I'm heading in the right direction. I'm going to work on it some more. Thanks everyone.
android: create json object or array?
I'm learning everyday a little bit more about android developing and json code. But now I'm stuck on this; I can get my values from my online database and show it but I see the entire json code. And I would like to see just the part I want it to show. this is my code, I think it's really basic but i'm also learning :) As you can see I'm just getting the value from the webpage and putting it in my textview, but I would like to put it in a JSONObject or JSONArray don't know witch one is better. can somebody please assist me with this? With kind regards public class Bordje extends Activity{ public void onCreate (Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.bordje); //This is out textview element, obtained by id from XML Layout TextView myListView = (TextView)findViewById(R.id.netResult2); //Lets connect to the internet try { String result = ""; //create new client object HttpClient httpclient = new DefaultHttpClient(); //now post to the url HttpPost httppost = new HttpPost("http://www.wvvzondag2.nl/android/leesbordje.php"); //execute url HttpResponse response = httpclient.execute(httppost); //get message from the response HttpEntity entity = response.getEntity(); //get the content from message InputStream webs = entity.getContent(); //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } //slow our inputstream webs.close(); //puts the resut into a string result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //Parsing the JSON Data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); json_data.getString("introtext"); //Get an output to the screen //then here should be some code that displays text? //myListView.setText(Html.fromHtml(json_data)); ? } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } }catch(Exception e){ Log.e("log_tag", "Error in http connection"+e.toString()); } } catch (Exception e) { //this is the line of code that sends a real error message to the log Log.e("ERROR", "ERROR IN CODE: " + e.toString()); } }
It's not really a question of which one is better. A JSON object and JSON array are two different things. A JSON Array is an ordered sequence of (like) items (http://www.json.org/javadoc/org/json/JSONArray.html). JSONArray jsonArray = new JSONArray("[JSON TEXT]"); String textToDisplay = jsonArray.getString(index); //return String at index A JSON Object is a map (http://www.json.org/javadoc/org/json/JSONObject.html). JSONObject jsonObj = new JSONObject("[JSON TEXT]"); String textToDisplay = jsonObj.getString("key"); //returns String value Then after you have the data, set it in the text view like before. myListView.setText(textToDisplay);
If you are getting valid json from server you can simply make a JSONArray or JSONObject of it depending on whose object you are getting so there is no point of saying which one is better. However in your case it will most probably be a JSONArray. Well to achieve that you can use gson to convert a valid json string into JSONObject or JSONArray. you will be working with .toJson() and .fromJSON(object) methods.
Android app using data from webservice
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
Updateing Android application content via internet?
i want to develop an Android application that will take the content from internet (server) and present it in the application. (ex. i take the todays weather forecast, put the numbers in SQLite database or .txt file , put the database/txt file on internet server so when i open the application, the app connects&downloads the database via the net and presents me with todays forecast) If you can references me to some example/video tutorial/book that deals with this issue i will be very thankful!
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