Error converting String to int [closed]

0

I need to convert String urlImagem to int , because the image will be loaded into an adapter and only accept int , or is there any way to convert id to% with%?

The code below returns the error

  

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

Because cast from String to String can not 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 translation

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 the adapter, the image will be loaded by an ImageView, of course, and the constructor of the class for img is int, because it is an xml ID, but in the conversion from JSON to url it comes as String, giving type mismatch. My question would be if there exists as the xml component to be pulled as String instead of an int ID, or if you can convert the JSON URL to int? I tried to do the JSON conversion, but it informs the above errors.

    
asked by anonymous 10.05.2017 / 04:44

2 answers

1

Aline,

theLibrary.getImage () list returns what object type?

The ideal to load the image in the imageView from an 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)
    
11.05.2017 / 01:48
0

Hello, Aline.

I do not see much sense in what you want to do and I ask you to put an example of such adapter mentioned, because I believe the problem is in the way the adapter is being used and so I can help you better.

You can obviously transform a int to String , and you can even transform a number that is in the format String to int , as "123" . But I do not see how a String URL can be transformed into int .

NOTE: There is an error in your code that is missing keys in If . I believe you know, but I'll explain if you do not know. If no keys are used in If , it will only exert the condition for the first following expression of its declaration, in this case it would only be the try { excerpt. All the rest of the code below is out 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's a good practice to always set the scope of If , ie it's a good practice to always use braces , even though you wanted If to be valid only for the first time following expression.

I await your editing with the adapter!

    
10.05.2017 / 13:37