1
Hello, I’m trying to list data from a web API, as I’ve never listed this way I’m finding problems to understand the solution of the listing, the API Url returns some values I want to list them in Activity Main, but when entering the line with the following excerpt:
arrayList.add((Coins) lCoins);
generating the following exception:
java.lang.RuntimeException: An error occured while executing doInBackground()
Up this line lCoins = new Gson().fromJson(resposta.toString(), new TypeToken<List<Coins>>(){}.getType() );
the data is recovered perfectly, however while trying to play it in the list for the user the error is presented. Below are the classes in question
public class MainActivity extends AppCompatActivity {
//ATRIBUTOS
private ArrayAdapter adapter;
private ListView listView;
private ArrayList<Coins> arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//********* CONFIGURANDO A LISTAGEM DAS MOEDAS **********/
listView = (ListView) findViewById(R.id.lv_coins);
arrayList = new ArrayList<>();
adapter = new CoinsAdapter(MainActivity.this, arrayList);
listView.setAdapter(adapter);
//********* FIM CONFIGURANDO A LISTAGEM DAS MOEDAS **********/
}
@Override
protected void onStart() {
super.onStart();
try{
Coins coins = new HTTPService(arrayList)
.execute()
.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
Adapter:
public class CoinsAdapter extends ArrayAdapter<Coins> {
//ATRIBUTOS
private Context context;
private ArrayList<Coins> arrayList;
public CoinsAdapter(@NonNull Context c, ArrayList<Coins> objects) {
super(c, 0,objects);
this.context = c;
this.arrayList = objects;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = null;
//VALIDANDO E CRIANDO A LISTA DE MOEDAS
if (arrayList != null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
//montando a view a partir do xml
view = inflater.inflate(R.layout.list_main, parent, false);
//RECUPERANDO OS COMPONENTES PARA EXIBICAO
TextView tvRank = view.findViewById(R.id.tv_rank);
TextView tvCoin = view.findViewById(R.id.tv_coin);
TextView tvPreco = view.findViewById(R.id.tv_preco);
TextView tvMarket = view.findViewById(R.id.tv_market);
TextView tvVol = view.findViewById(R.id.tv_vol);
TextView tv1hr = view.findViewById(R.id.tv_1h);
TextView tv24hr = view.findViewById(R.id.tv_24h);
TextView tv7d = view.findViewById(R.id.tv_7d);
//GRAVANDO OS DADOS DE ACORDOD COM A CLASSE MODELO
Coins coins = arrayList.get(position);
tvRank.setText(coins.getRank());
tvCoin.setText(coins.getName());
tvPreco.setText(coins.getPrice_usd());
tvMarket.setText(coins.getMarket_cap_usd());
tvVol.setText(coins.getVolume_usd_24h());
tv1hr.setText(coins.getPercent_change_1h());
tv24hr.setText(coins.getPercent_change_24h());
tv7d.setText(coins.getPercent_change_7d());
}
return view;
}
}
the class making the request with the webservice:
public class HTTPService extends AsyncTask<Void, Void, Coins> {
//ATRIBUTOS
private ArrayAdapter adapter;
private ListView listView;
private List<Coins> lCoins;
private ArrayList<Coins> arrayList;
public HTTPService(ArrayList<Coins> coins) {
this.arrayList = coins;
}
@Override
protected Coins doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try{
//URL QUE SERÁ CONSUMIDA
URL url = new URL("https://api.coinmarketcap.com/v1/ticker/?limit=10");
//---- ABRINDO A CONEXÃO ---
HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
conexao.setRequestMethod("GET");
conexao.setRequestProperty("Content-type","application/json");
conexao.setRequestProperty("Accept", "application/json");
conexao.setDoOutput(true);
conexao.setConnectTimeout(5000);
conexao.connect();
//----- LENDO AS INFORMAÇÕES -------
Scanner scanner = new Scanner(url.openStream());
arrayList.clear();
while (scanner.hasNext()){
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//CONVERTENDO O RETORNO PARA A CLASSE MODELO
lCoins = new Gson().fromJson(resposta.toString(), new TypeToken<List<Coins>>(){}.getType() );
//arrayList.add((Coins) lCoins);
return lCoins.size() > 0 ? lCoins.get(0) : null;
}
@Override
protected void onPostExecute(Coins coins) {
super.onPostExecute(coins);
for (int i = 0; i <= lCoins.size(); i++){
arrayList.add(lCoins.get(i));
}
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I made some changes and function, first I changed the return using the example you had suggested me in a previous post: return lCoins.size() > 0 ? lCoins.get(0) : null;
then put the for to retrieve the result and list line by line on onpostexecute and it worked out! Thank you very much!
You nay can manipulate the UI in the method
doInBackground
. For this it is necessary that you move your code responsible for displaying the data to the user for the methodonPostExecute
.– Valdeir Psr
Dude, it worked perfectly, if you want to put as a response the for for onpostexecute can put because you deserve positive points for it ! Thank you !
– Eduardo Rafael Moraes