0

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(

Yurets
  • 3,999
  • 17
  • 54
  • 74
  • Seems like a JSON formating error http://stackoverflow.com/questions/10334385/json-exception-org-json-jsonexception-unterminated-array im not sure tho sorry – TehCoder Sep 10 '14 at 17:11
  • @TehCoder , yes, it is kinda like that, but I have to solve it. I can't make this JsonArray correct, because this is url... I need to skip it over and search there only for "im:name"... – Yurets Sep 10 '14 at 17:14
  • @meda, I haven't it, unfortunately, and this is a small app, so no needs... – Yurets Sep 10 '14 at 17:22
  • @meda, I gonna try it, I just thought must be much easier way... like "search in json's keys" or something... – Yurets Sep 10 '14 at 17:28
  • oh wait, does `JSONObject json = jParser.getJSONFromUrl(jsonStringUrl);` throw the error ? – meda Sep 10 '14 at 17:30
  • @meda, no, next line `dataJsonArr = json.getJSONArray("feed");` I've tried to change this key, but nothing works, because the exception comes before it found anything... – Yurets Sep 10 '14 at 17:34
  • @Yurets see my answer below, you can ignore my last comments I thought it was when downloading... – meda Sep 10 '14 at 17:42
  • The part that read the data is incorrect. you are replacing a `\n` by a `n` character, rendering it unreadable, making the poorly written parser return null, making you crash at the next line. – njzk2 Sep 10 '14 at 17:50
  • as a side note, your jsonparser class is also apparently reading the data in iso-8859-1 when it is clearly utf-8 (json is specified to be always in unicode, usually in utf-8). The `JsonParser` class that you use is very poorly written (I have seen it in other places), and you should stay well away from it. – njzk2 Sep 10 '14 at 17:54
  • 1
    I would recommend you replace `JSONObject json = jParser.getJSONFromUrl(jsonStringUrl);` with `JSONObject json = new JSONObject(EntityUtils.toString(new DefaultHttpClient().execute(new HttpGet(jsonStringUrl)).getEntity()));` and stop using that `JsonParser` entirely – njzk2 Sep 10 '14 at 17:57
  • But it will not resolve the problem – Indra Kumar S Sep 10 '14 at 17:59

3 Answers3

0

You are not accessing the values the right way, check this:

JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONFromUrl(jsonStringUrl);
JSONObject feeds = json.getJSONObject("feed");

dataJsonArr = feeds.getJSONArray("entry");
for (int i = 0; i < dataJsonArr.length(); i++) {
    JSONObject c = dataJsonArr.getJSONObject(i);
    String name = c.getString("im:name");
    Log.d("mylog", "name = " + name);
}

You probably want to append this data into an array list, otherwise you would be overwriting these variables.

Please note org.json is a limited library i have personally experienced its limitation when the json data is too large.

I suggest you to ditch it and use GSON or jackson which are fare more advanced.

meda
  • 45,103
  • 14
  • 92
  • 122
0

First You make a call get the result into a string called json. Then You have to convert the string into Json object

          String json = null;  
        JSONObject jsonObj = null;  JSONObject feedsObject = null;


     json = jParser.getJSONFromUrl(jsonStringUrl);
       if (json != null) {
    try {
         jsonObj = new JSONObject(json);

        feedObject = jsonObj.getJSONObject("feed");

For a better understanding visit http://json.parser.online.fr/beta/ and paste your json data there. On the right you have a settings button---> show types You can find what are objects, strings and arrays

See the image below. You were trying get a an object not an array

enter image description here

Indra Kumar S
  • 2,818
  • 2
  • 16
  • 27
  • unrelated to the question – njzk2 Sep 10 '14 at 17:52
  • njzk2 He is trying to get an object called feeds. But In his code, He wrote......... dataJsonArr = json.getJSONArray("feed"); // probably wrong ........... It should be corrected or not? – Indra Kumar S Sep 10 '14 at 17:54
  • the error is related to the fact that `JsonParser` returns null because the part that reads the data from the network is broken – njzk2 Sep 10 '14 at 17:59
  • @njzk2, yes, you got that correctly! I've checked this json is invalid.. do you know the way how I just can get those names in the most easier way according to code I've already wrote? and I changed encoding already, thanks! – Yurets Sep 10 '14 at 18:04
  • @Yurets: see my comments under the question. The networking part is the issue. I have posted in comment a much shorter way of obtaining the json object. – njzk2 Sep 10 '14 at 18:21
0

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;
    }
Community
  • 1
  • 1
Yurets
  • 3,999
  • 17
  • 54
  • 74