3
I’m having trouble getting a file from the internet by JSON.
I have some data on this link http://www.sinestandar.com.br/maker/categorias.txt and I want to take to use in my application, the link returns something like:
{
   "Categorias":[
      {
         "nome":"Black",
         descricao:"Cortes de cabelo estilo Black",
         "icone":"http://mundomulheres.com/fotos/2013/10/dois-tipos-de-cortes-cacheados.jpg"
      },
      {
         "nome":"Casamento",
         descricao:"Cortes de cabelo para casamento",
         "icone":"http://www.belasdicas.com/wp-content/uploads/2012/07/penteados-para-casamento.jpg"
      }
   ]
}
I tried to do so
class DownloadJsonAsyncTask extends AsyncTask<String, Void, List<Trend>> {
    ProgressDialog dialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(ConsumirJsonTwitterActivity.this, "Aguarde", "Baixando JSON, Por Favor Aguarde...");
    }
    @Override
    protected List<Trend> doInBackground(String... params) {
        String urlString = params[0];
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(urlString);
        try {
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                String json = toString(instream);
                instream.close();
                List<Trend> trends = getTrends(json);
                return trends;
            }
        } catch (Exception e) {
            Log.e("DEVMEDIA", "Falha ao acessar Web service", e);
        }
        return null;
    }
    private List<Trend> getTrends(String jsonString) {
        List<Trend> trends = new ArrayList<Trend>();
        try {
            JSONArray trendLists = new JSONArray(jsonString);
            JSONObject trendList = trendLists.getJSONObject(0);
            JSONArray trendsArray = trendList.getJSONArray("trends");
            JSONObject trend;
            for (int i = 0; i < trendsArray.length(); i++) {
                trend = new JSONObject(trendsArray.getString(i));
                Log.i("DEVMEDIA", "nome=" + trend.getString("name"));
                Trend objetoTrend = new Trend();
                objetoTrend.name = trend.getString("name");
                objetoTrend.descricao = trend.getString("descricao");
                objetoTrend.icone = trend.getString("icone");
                trends.add(objetoTrend);
            }
        } catch (JSONException e) {
            Log.e("DEVMEDIA", "Erro no parsing do JSON", e);
        }
        return trends;
    }
    @Override
    protected void onPostExecute(List<Trend> result) {
        super.onPostExecute(result);
        dialog.dismiss();
        if (result.size() > 0) {
            ArrayAdapter<Trend> adapter = new ArrayAdapter<Trend>(ConsumirJsonTwitterActivity.this, android.R.layout.simple_list_item_1, result);
            setListAdapter(adapter);
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(ConsumirJsonTwitterActivity.this).setTitle("Atenção").setMessage("Não foi possivel acessar essas informções...").setPositiveButton("OK", null);
            builder.create().show();
        }
    }
But you’re making this mistake:
12-16 15:33:47.229  14947-14955/json.exemplo.com.testejson E/DEVMEDIA﹕ Erro no parsing do JSON
org.json.JSONException: Value {"Categorias":[{"icone":"http:\/\/mundomulheres.com\/fotos\/2013\/10\/dois-tipos-de-cortes-cacheados.jpg","descricao":"Cortes de cabelo estilo Black","nome":"Black"},{"icone":"http:\/\/www.belasdicas.com\/wp-content\/uploads\/2012\/07\/penteados-para-casamento.jpg","descricao":"Cortes de cabelo para casamento","nome":"Casamento"}]} of type org.json.JSONObject cannot be converted to JSONArray
        at org.json.JSON.typeMismatch(JSON.java:107)
        at org.json.JSONArray.<init>(JSONArray.java:91)
        at org.json.JSONArray.<init>(JSONArray.java:103)
        at json.exemplo.com.testejson.ConsumirJsonTwitterActivity$DownloadJsonAsyncTask.getTrends(ConsumirJsonTwitterActivity.java:76)
strange that it seems that it is taking the most data ta giving error in time to pass to the JSONArray trendLists;
To help anyone with the same problem I’m putting as I solved
private List<Categoria> getTrends(String jsonString) {
        List<Categoria> categorias = new ArrayList<Categoria>();
        try {
            JSONObject trendLists = new JSONObject(jsonString);
            JSONArray jArray = trendLists.getJSONArray("Categorias");
            for(int i=0; i<jArray.length(); i++){
                Categoria categoria = new Categoria();
                JSONObject json_data = jArray.getJSONObject(i);
                categoria.nome=json_data.getString("nome");
                categoria.descricao=json_data.getString("descricao");
                categoria.icone=json_data.getString("icone");
                categorias.add(categoria);
            }
        } catch (JSONException e) {
            Log.e("DEVMEDIA", "Erro no parsing do JSON", e);
        }
        return categorias;
    }
JSONArray trendListsshouldn’t be aJSONObject?– Lucas Lima
@Lucasnunes you were faster than me +1
– Guilherme Nascimento
I was looking from a website, I don’t know anything I’m trying to learn :/ , to well lost
– Ilgner de Oliveira
@Ilgnerdeoliveira I added an example too.
– Guilherme Nascimento