java.lang.Runtimeexception: An error occured while executing doInBackground()

Asked

Viewed 806 times

0

Once the user informs some data about the book, the app displays a list of the Google Books API with information about the book, was doing some tests and some words correctly return the listing and such, but some words like "Passion" for example, crashes the app and returns this error.

Updated request

package com.example.android.listadelivros;

import android.text.TextUtils;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public final class ConsultaRequisicao {

    private static final String LOG_TAG = ConsultaRequisicao.class.getSimpleName();

    private ConsultaRequisicao() {
    }

    public static List<DadosLivro> buscarDadosLivro(String pedidoUrl) {

        URL url = criarUrl(pedidoUrl);

        String jsonResposta = null;
        try {
            jsonResposta = fazerPedidoHttp(url);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problemar ao criar um pedido HTTP.", e);
        }

        List<DadosLivro> livros = extrairDadosJson(jsonResposta);
        return livros;
    }

    private static URL criarUrl(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Problema na contrução da URL.", e);
        }
        return url;
    }

    private static String fazerPedidoHttp(URL url) throws IOException {

        String jsonResposta = "";

        if (url == null) {
            return jsonResposta;
        }

        HttpURLConnection conexao = null;
        InputStream inputStream = null;

        try {
            conexao = (HttpURLConnection) url.openConnection();
            conexao.setReadTimeout(1000);
            conexao.setConnectTimeout(1500);
            conexao.setRequestMethod("GET");
            conexao.connect();

            if (conexao.getResponseCode() == 200) {
                inputStream = conexao.getInputStream();
                jsonResposta = converterInputStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Erro na resposta do código: " + conexao.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problemas ao recuperar o resultado dos livros - JSON " + e);
        } finally {
            if (conexao != null) {
                conexao.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return jsonResposta;
    }


    private static String converterInputStream(InputStream inputStream) throws IOException {
        StringBuilder saida = new StringBuilder();

        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader ler = new BufferedReader(inputStreamReader);

            String linha = ler.readLine();
            while (linha != null) {
                saida.append(linha);
                linha = ler.readLine();
            }
        }
        return saida.toString();
    }

    private static List<DadosLivro> extrairDadosJson(String dadosLivrosJson) {

        if (TextUtils.isEmpty(dadosLivrosJson)) {
            return null;
        }

        List<DadosLivro> informacoesLivro = new ArrayList<>();

        try {
            JSONObject respostaJason = new JSONObject(dadosLivrosJson);
            JSONArray dadosLivroArray = respostaJason.optJSONArray("items");

            for (int i = 0; i < dadosLivroArray.length(); i++) {

                JSONObject livroAtual = dadosLivroArray.optJSONObject(i);
                JSONObject informacaoVolume = livroAtual.optJSONObject("volumeInfo");

                String titulo = informacaoVolume.optString("title");
                String descricao = informacaoVolume.optString("description");

                JSONArray listaAutor = informacaoVolume.optJSONArray("authors");
                String autor = (String) listaAutor.get(0);

                DadosLivro inforLivro = new DadosLivro(titulo, descricao, autor);
                informacoesLivro.add(inforLivro);
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Problema ao analisar os resultados JSON", e);
        }
        return informacoesLivro;
    }
}

Error

at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                                                           at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                                                           at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
                                                                                           at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                                           at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                           at java.lang.Thread.run(Thread.java:818)
05-09 14:59:12.901 25630-25785/com.example.android.listadelivros E/ConsultaRequisicao: Problema ao analisar os resultados JSON
                                                                                       org.json.JSONException: No value for authors
                                                                                           at org.json.JSONObject.get(JSONObject.java:389)
                                                                                           at org.json.JSONObject.getJSONArray(JSONObject.java:584)
                                                                                           at com.example.android.listadelivros.ConsultaRequisicao.extrairDadosJson(ConsultaRequisicao.java:127)
                                                                                           at com.example.android.listadelivros.ConsultaRequisicao.buscarDadosLivro(ConsultaRequisicao.java:39)
                                                                                           at com.example.android.listadelivros.DadosLivrosLoader.loadInBackground(DadosLivrosLoader.java:31)
                                                                                           at com.example.android.listadelivros.DadosLivrosLoader.loadInBackground(DadosLivrosLoader.java:9)
                                                                                           at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                                                           at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                                                           at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
                                                                                           at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                                           at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                           at java.lang.Thread.run(Thread.java:818)
  • Please post the error text instead of an image.

  • if it’s to meet as code, you’re done.

  • @ramaral sorry about writing the issue, I didn’t notice

  • I’m new around here, I’m not sure how things work

  • Aline, the error says Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object org.json.JSONArray.get(int)' on a null object reference

  • Can’t debug the code? The error must be in the method extrairDadosJson?

  • yes, I did and it’s not null, just in time return informacoesLivro; it hangs, but is receiving values.

  • @jbueno posted the debug, I don’t know if it is this way, but there you can see the data being extracted correctly.

  • But it is at this moment that the error occurs?

  • it pulls the data properly and displays the message Object has been collected Cannot evaluate org.json.JSONObject.toString()

Show 5 more comments

1 answer

1


You have not initialized your Jsonarray list correctly.

Eliminate the line:

JSONArray listaAutor = null;

And replace the line that feeds that variable with:

JSONArray listaAutor = informacaoVolume.optJSONArray("authors");
  • had already done so and the error continues, it returns the JSON value correctly, but the same error appears. Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object org.json.JSONArray.get(int)' on a null object reference

  • Make this change that I said and edit the question with the code and the full bug updated to see exactly where the bug is. The way it is in the question, the error is due to this null object initialization and, if it still continues after the edit I suggested, the optJSONArray() method may be returning null and it will give error in the next get() same.

  • All right, I’ll do it, the funny thing is that if you insert a few words, it works perfectly and with others, it just closes. I already change the question. obg

  • I have seen here and editing. The error really is in get() because optJSONArray() must have returned null. I have already worked with Google Books API once. The authors took it as follows: String Authors = volumeInfo.getJSONArray("Authors"). Join(", "). replace(""", "");

  • friend, it worked! What a relief to thank you really, it’s working, but tbm is releasing an excesses, I’ll edit for you to see.

  • Looking at the Jsonarray documentation here, maybe you should have used getString(0) instead of get(0).

  • but if I do, it presents the error Problema ao analisar os resultados JSON org.json.JSONException: No value for authors

  • I see here the new exception. Since you must have used getJSONArray instead of optJSONArray, it generates an exception when it does not find the "Authors" string in JSON. The optJSONArray method simply returns null and does not generate an exception, but will error in the next line if you do not check the Author list variable before trying to use get() or getString(). My conclusion is that some book returned by API has no author defined, so your method is crashing because it is not treating this possibility.

  • I used opt Yes JSONArray listaAutor = informacaoVolume.optJSONArray("authors");

  • Can you tell me why the api returns only 10 items in listVie? pq probably have dozens

  • I edited my previous answer. Returns 10 books because it is the limit for free keys.

  • thanks anyway, I’ll check the array and see if it solves. :)

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.