0

I can't extract data from this json. I believe it is because it is an array. I read about it but I didn't find anything specific for this case.

I just need to take the values ​​individually each time I close {}.

Eg: result [0] .getLoterias();

== INSTANTANEA

The connection is being made normally, I just can't extract the data.

httpservice2.java

package br.com.matheuscastiglioni.blog.requisicao_http.service;

import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;

public class HttpService2 extends AsyncTask<Void, Void, CEP2> {


    private final String cep;
    private final String token;

    public HttpService2(String cep, String token) {
        this.cep = token;
        this.token = cep;

    }

    @Override
    protected CEP2 doInBackground(Void... voids) {
        StringBuilder resposta = new StringBuilder();



            try {
                URL url = new URL( "A" + this.cep + "&token=" + this.token);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-type", "application/json");
                connection.setRequestProperty("Accept", "application/json");
                connection.setDoOutput(true);
                connection.setConnectTimeout(5000);
                connection.connect();

                Scanner scanner = new Scanner(url.openStream());
                while (scanner.hasNext()) {
                    resposta.append(scanner.next());
                }



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }



            return new Gson().fromJson(resposta.toString(), CEP2.class);
    }



}

Main3Activity.java:

package br.com.matheuscastiglioni.blog.requisicao_http;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.concurrent.ExecutionException;

import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
import br.com.matheuscastiglioni.blog.requisicao_http.service.HttpService2;

public class Main3Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);


        final TextView resposta = findViewById(R.id.etMain_resposta2);
        final TextView cep = findViewById(R.id.etMain_resposta3);
        final TextView token = findViewById(R.id.etMain_resposta4);
        Bundle extras = getIntent().getExtras();
        String respostatoken = extras.getString("token");
        String respostaid = extras.getString("id");

        cep.setText(respostaid);
        token.setText(respostatoken);
//alert(cep.getText().toString() + token.getText().toString());
          try {
              CEP2 retorno = new HttpService2(cep.getText().toString(), token.getText().toString()).execute().get();
              String loteria = retorno.getIdloteria();
            resposta.setText(loteria);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    private void alert(String s) {
        Toast.makeText(this,s,Toast.LENGTH_LONG).show();
    }
}

CEP2.java:

package br.com.matheuscastiglioni.blog.requisicao_http.model;



public class CEP2 {


    private String idloteria;

    public String getIdloteria() {
        return idloteria;
    }

    public void setIdloteria(String idloteria) {
        this.idloteria = idloteria;
    }



}

currently:

I changed

return new Gson().fromJson(resposta.toString(), CEP2.class);

per

Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;

httpservic2 new:

package br.com.matheuscastiglioni.blog.requisicao_http.service;

import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;

public class HttpService2 extends AsyncTask<Void, Void, CEP2> {


    private final String cep;
    private final String token;

    public HttpService2(String cep, String token) {
        this.cep = token;
        this.token = cep;

    }

    @Override
    protected CEP2 doInBackground(Void... voids) {
        StringBuilder resposta = new StringBuilder();



            try {
                URL url = new URL( "A" + this.cep + "&token=" + this.token);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-type", "application/json");
                connection.setRequestProperty("Accept", "application/json");
                connection.setDoOutput(true);
                connection.setConnectTimeout(5000);
                connection.connect();

                Scanner scanner = new Scanner(url.openStream());
                while (scanner.hasNext()) {
                    resposta.append(scanner.next());
                }



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }



               Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
        List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
        return cep2List;
    }



}

I need to change the return from doinbackground However, I'm lost

1 Answers1

1

It seems you only want the idloteria from the response which should be fine. But as you say it's an array and it should be parsed as an array or a List.

The:

return new Gson().fromJson(resposta.toString(), CEP2.class);

Should be

Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;

If you want the response be parsed as a list.

Another possibility is to get the data parsed as an array:

CEP2[] cep2Array = new Gson().fromJson(resposta.toString(), CEP2[].class);
return cep2Array;

and you'll need to change the return of the doInBackground in accordance with the response type you choose.

Lets choose to return a list. In this case change AsyncTask<Void, Void, CEP2> to AsyncTask<Void, Void, List<CEP2>> and also protected CEP2 doInBackground to protected List<CEP2> doInBackground. The returned list will be received in onPostExecute parameter onPostExecute(List<CEP2> cep2List). And in this onPostExecute you can save the list, print it or do whatever you want to do with the received data.

But keep in mind that AsyncTask are deprecated in API level R. It's recommended using standard java.util.concurrent or Kotlin concurrency utilities instead.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
  • Thank you for your help! I haven't programmed on android for a long time, I believe you noticed with the use of AsyncTaks that it is already obsolete. I understood the concept and did some tests, but I never passed a matrix and I have no idea what to put in the return of doInBackground. Could you help me with that too? thankful – mateus anjos May 02 '20 at 20:10
  • No problem, I've updated the answer with more info about this. If you still need more help/info tomorrow and nobody has provided it yet I'll try to help you, here is late and I have to wake up soon tomorrow. – jeprubio May 02 '20 at 21:25
  • Everything is fine, but the connection fails when I switch to (app closes): CEP2 retorno = new HttpService2(cep.getText().toString(), token.getText().toString()).execute().get(); for List retorno = new HttpService2(cep.getText().toString(), token.getText().toString()).execute().get(); – mateus anjos May 03 '20 at 21:56
  • Could you provide the [stack trace](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this/23353174#23353174) of that last crash? – jeprubio May 04 '20 at 05:48
  • https://github.com/mateusanjost/teste-pilha.git or at at br.com.matheuscastiglioni.blog.requisicao_http.service.HttpService2.doInBackground(HttpService2.java:65) at br.com.matheuscastiglioni.blog.requisicao_http.service.HttpService2.doInBackground(HttpService2.java:20) ? P.S: it is the first time that I do a stack trace in android studio, I hope I did it correctly. Thank you – mateus anjos May 04 '20 at 06:15
  • Line: public class HttpService2 extends AsyncTask> { and List cep2List = new Gson().fromJson(resposta.toString(), cep2ListType); – mateus anjos May 04 '20 at 06:21