I'm parsing this url and I've got an exception and don't know how to skip it over... I need to get only names of 100 the most popular apps. There is key "im:name" and inside of it key "lebel", but as I see it is invalid JsonArray, so I need to find the way to get names by the key "im:name"... has smb any ideas how can I fix this?
This is my AsyncTask.class
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
String jsonStringUrl = "https://itunes.apple.com/br/rss/topfreeapplications/limit=100/json";
JSONArray dataJsonArr = null;
@Override
protected void onPreExecute() {}
@Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(jsonStringUrl);
// get the array of users
//HERE I NEED TO CHANGE SOMETHING
dataJsonArr = json.getJSONArray("feed"); // probably wrong
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String name = c.getString("im:name");//probably wrong
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
and this is the log
09-10 20:04:03.013 18211-18241/com.yuretsrodik.top100apps E/JsonParser.java﹕ Error parsing data org.json.JSONException: Unterminated array at character 115 of {"feed":{"author":{"name":{"label":"iTunes Store"}, "uri":{"label":"http://www.apple.com/br/itunes/"}}, "entry":[n{"im:name":{"label":"Messenger"}, "im:image":[n{"label":"http://a474.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.53x53-50.png", "attributes":{"height":"53"}}, n{"label":"http://a990.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.75x75-65.png", "attributes":{"height":"75"}}, n{"label":"http://a1675.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.100x100-75.png", "attributes":{"height":"100"}}], "summary":{"label":"lcance instantaneamente as pessoas na sua vida, gratuitamente. O Messenger é como mensagens de texto, mas você não precisa pagar por cada mensagem (funciona com o seu plano de dados). \n\nNão é só para amigos no Facebook: envie mensagens para as pessoas na sua agenda de contatos e basta inserir um número de telefone para adicionar um novo contato.\n\nBate-papos em grupo: crie grupos para as pessoas a quem você mais envia mensagens. Dê um nome a eles, defina fotos para o grupo e os mantenha em um só lugar.\n\nFotos e vÃdeos: grave vÃdeos e tire selfies ou outras fotos diretamente do aplicativo e envie-os com um toque.\n\nLigações gratuitas: fale por quanto tempo quiser, mesmo com pessoas em outros paÃses. (Ligações são gratuitas somente através do Wi-Fi. Do contrário, cobranças de dados padrão são aplicáveis).\n\nMais formas de enviar mensagens: \nDê vida à s suas conversas com as figurinhas. \nVeja uma prévia das suas fotos e vÃdeos no rolo da câmera sem sair da conversa, e escolha as melhores para enviar.\nGrave mensagens de voz quando tiver mais para dizer\n\nRecursos adicionais:\nSaiba quando as pessoas viram suas mensagens.\nEncaminhe mensagens ou fotos para as pessoas que não estavam na conversa.\nProcure pessoas e grupos para entrar em contato com eles rapidamente.\nAtive a localização para que as pessoas saibam que você está nas imediações.\nVeja quem está disponÃvel no Messenger e quem está on-line no Facebook. \nDesative as notificações quando você estiver trabalhando, dormindo ou se precisar dar um tempo.\nFique conectado para nunca perder uma mensagem."}, "im:price":{"label":"Grátis", "attributes":{"amount":"0.00000", "currency":"USD"}}, "im:contentType":{"attributes":{"term":"Application", "label":"Aplicativo"}}, "rights":{"label":"© Facebook, Inc."}, "title":{"label":"Messenger - Facebook, Inc."}, "link":{"attributes":{"rel":"alternate", "type":"text/html", "href":"https://itunes.apple.com/br/app/messenger/id454638411?mt=8&uo=2"}}, "id":{"label":"https://itunes.apple.com/br/app/messenger/id454638411?mt=8&uo=2", "attributes":{"im:id":"454638411", "im:bundleId":"com.facebook.Messenger"}}, "im:artist":{"label":"Facebook, Inc.", "attributes":{"href":"https://itunes.apple.com/br/artist/facebook-inc./id284882218?mt=8&uo=2"}}, "category":{"attributes":{"im:id":"6005", "term":"Social Networking", "scheme":"https://itunes.apple.com/br/genre/ios-redes-sociais/id6005?mt=8&uo=2", "label":"Redes sociais"}}, "im:releaseDate":{"label":"2011-10-19T15:39:30-07:00", "attributes":{"label":"19/10/2011"}}}, n{"im:name":{"label":"WhatsApp Messenger"}, "im:image":[n{"label":"http://a1554.phobos.apple.com/us/r30/Purple1/v4/1f/94/ff/1f94ffd9-159e-a247-2c0f-059f86b6c6c9/mzl.ivmblqpq.53x53-50.png", "attributes":{"height":"53"}}, n{"label":"http://a422.phobos.apple.com/us/r30/Purple1/v4/1f/94/ff/1f94ffd9-159e-a247-2c0f-059f86b6c6c9/mzl.ivmblqpq.75x75-65.png", "attributes":{"height":"75"}}, n{"label":"http://a1251.phobos.apple.com/us/r30/Purple1/v4/1f/94/ff/1f94ffd9-159e-a247-2c0f-059f86b6c6c9/mzl.ivmblqpq.100x100-75.png", "attributes":{"height":"100"}}], "summary":{"label":"O WhatsApp Messenger é um mensageiro para smartphone
09-10 20:04:03.013 18211-18241/com.yuretsrodik.top100apps W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x42044e48)
09-10 20:04:03.023 18211-18241/com.yuretsrodik.top100apps E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.yuretsrodik.top100apps, PID: 18211
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.yuretsrodik.top100apps.AsyncTaskParseJson.doInBackground(AsyncTaskParseJson.java:32)
at com.yuretsrodik.top100apps.AsyncTaskParseJson.doInBackground(AsyncTaskParseJson.java:10)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Will be very very thanksful for the help!! Cuz I'm really stack(
Thanks to njzk2 for the advice to avoid using JSONParser
, so I've made all I needed in very shorter time and with less efforts.
I needed to get root JSONObject
- names of applications in iTunes
.
and insert it into database.
This is the full code of the method doInBackground
in AsyncTask.class
@Override
protected Boolean doInBackground(Void... params) {
Log.d(LOG, "AsyncTask. Do in background");
ContentValues cv = new ContentValues();
try {//Making a request to server getting entities
JSONObject json = new JSONObject(EntityUtils.toString(
new DefaultHttpClient().execute(
new HttpGet(url)).getEntity()));
//getting json root object
JSONObject feedObject = json.getJSONObject("feed");
//getting needed array in root json object
JSONArray entryArray = feedObject.getJSONArray("entry");
//moving though the array
for(int i = 0; i < entryArray.length(); i++){
//getting all objects in array
JSONObject entryObjects = entryArray.getJSONObject(i);
//taking objects with needed key
JSONObject nameObject = entryObjects.getJSONObject("im:name");
//getting string name
String name = nameObject.getString("label");
//putting data into ContentValues - name and id (for making a numbers
// next to records in ListView)
cv.put(DB.COL_NAME, name);
cv.put(DB.COL_ID, i+1);
mDB.insert(cv);
//just controlling in log
Log.d(LOG, "" + name);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}