Error converting String to int

Asked

Viewed 377 times

0

I need to convert String urlImagem for int, because the image will be loaded in a Adapter and only accepts int, or there is some way to make the conversion of id in String?

The code below returns the error

java.lang.Numberformatexception: Invalid int: "http:.."

Because the cast of String for int can’t be done.

In Logcat this error

Attempt to invoke virtual method 'java.lang.String org.json.Jsonobject.optString(java.lang.String)' on a null Object Reference`

Adapter

    package com.example.android.listadelivros;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class DadosLivrosAdapter extends ArrayAdapter<DadosLivro> {

    public DadosLivrosAdapter(Context contexto, List<DadosLivro> informacoesLivros){
        super(contexto, 0 , informacoesLivros);
    }

    @Override
    public View getView(int posicao, View converteVisualizacao, ViewGroup parente) {

        View visualizacao = converteVisualizacao;
        if(visualizacao == null){
            visualizacao = LayoutInflater.from(getContext()).inflate(R.layout.dados_livros_lista,
                    parente, false);
        }

        DadosLivro listaLivros = getItem(posicao);

        TextView titulo = (TextView) visualizacao.findViewById(R.id.titulo);
        titulo.setText(listaLivros.getTitulo());

        TextView descricao = (TextView) visualizacao.findViewById(R.id.descricao);
        descricao.setText(listaLivros.getDescricao());

        TextView autor = (TextView) visualizacao.findViewById(R.id.autor);
        autor.setText(listaLivros.getAutor());

        ImageView imagem = (ImageView) visualizacao.findViewById(R.id.imagem);

        if(listaLivros.temImagem()){
            imagem.setImageResource(listaLivros.getImagem());
            imagem.setVisibility(View.VISIBLE);
        } else {
            imagem.setVisibility(View.GONE);
        }

        return visualizacao;
    }
}

HTTP request and JSON conversion

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");

                JSONObject imagem = informacaoVolume.optJSONObject("imageLinks");
                String urlImagem = imagem.optString("thumbnail");

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

                String autor;
                JSONArray listaAutor = informacaoVolume.optJSONArray("authors");
                if (listaAutor != null && listaAutor.length() > 0) {
                    autor = listaAutor.getString(0);
                } else {
                    autor = "Autor Desconhecido";
                }

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

In Adapter, the imaogem will be loaded by an Imageview, obviously, and the class constructor for img is int, because it is xml ID, but in JSON conversion the url comes as String, giving type incompatibility. My question would be whether it exists as the xml component to be pulled as String instead of an int ID, or whether you can convert the JSON URL to int? I tried to convert JSON, but it informs the above errors.

  • Aline, I don’t know if it is possible to represent a String Base64 coded in Integer. However, it seems that the urlImage is null. Your test there urlImage is not working because you have not opened keys. {. You can only use the contracted form if (without keys) if the statement is only 1 line. Try this: if(urlImagem != null) {&#xA; //aqui dentro o try.&#xA;}. I’m pretty sure the image is null.

  • @Andrewribeiro I had done this way before and the result was the same, debugged and the urlImagem receives the value of Jsonobject, the problem must ta in the same conversion :/

  • " componente do xml ser puxado como String ao inves de um ID int", why not use javascript to go to the node where the ID and no longer need to convert anything. Ex:x = xmlDoc.getElementsByTagName("title")[0];&#xA;y = x.childNodes[0];

  • I believe I have to install the JS plugin to be able to use in Android Studio, it would be a lot of work, there must be some class that pulls the img view as String and not as int ID, I know there

  • Try it like this : urlImagem.getText().toString();&#xA; int result = Integer.parseInt(urlImagem);

  • Error : Caused by: java.lang.NumberFormatException: Invalid int: "http://books.google.com/books/content?..."

Show 1 more comment

2 answers

1

Aline,

the listLivros.getImage() returns what type of object?

the ideal way to load the image in imageView from a url is to download the image and create a bitmap

public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;

try {
    in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
    copy(in, out);
    out.flush();

    final byte[] data = dataStream.toByteArray();
    BitmapFactory.Options options = new BitmapFactory.Options();
    //options.inSampleSize = 1;

    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
    Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
    closeStream(in);
    closeStream(out);
}

return bitmap;
}

With the return of this method insert into Imageview

Imageview.setImageBitmap(retornoDoMetodo)
  • I’m using Picasso, a more correct way to bring the URL image straight to an Imageview, it worked out rs

0

Hello, Aline.

I do not see much sense in what you want to do and I request that an example of the cited Adapter be put forward, because I believe the problem lies in the way the Adapter is being used and so I can help better.

You can obviously turn a int for String and can even transform a number that is in the format String for int, as "123". But I don’t see it as a String URL can be transformed into int.

NOTE: There is an error in your code which is the lack of keys in If. I believe you know, but I will explain to you in case you do not know. If you do not use keys in If, he would only exercise the condition for the first expression following his statement, in which case it would be only the try {. All the rest of the code below is outside of what is called the scope of If:

    imagemURL = Integer.parseInt(urlImagem);
} catch (NumberFormatException e) {
    Log.e(LOG_TAG, "Problema na url da imagem", e);
}

It is good practice to always define the scope of If, that is to say, it is good practice to always use keys, even you wanted the If is really valid only for the first expression below.

I look forward to your release with Adapter!

  • edited, take a look there Please.

Browser other questions tagged

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