Tecnologia do Blogger.
RSS

Re: [androidbrasil-dev] CLASSE DownloadJsonAsyncTask com erro de setAdapter(adapter) .

Thiago, boa noite.

          Recomendo você utilizar a lib retrofit para fazer esta tarefa para você. É uma lib bem fácil de ser usada. 

Abraços !


2015-05-13 19:07 GMT-03:00 Thiago <thiagonascimento.rj@hotmail.com>:
Pessoal,
  Estou com um erro na Classe  DownloadJsonAsyncTask . 
  O erro causado é apenas na linha que contém o  setAdapter(adapter) .
  Alguém pode me ajudar ?

  Segue a classe abaixo:

  package com.example.exemplojson;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;


public class DownloadJsonAsyncTask extends AsyncTask<String, Void, List<Trend>>{
MainActivity myActivity = new MainActivity();
ProgressDialog dialog; 
protected void onPreExecute() { 
super.onPreExecute(); 
dialog = ProgressDialog.show(myActivity, "Aguarde", "Baixando JSON, Por Favor Aguarde...");

}
protected List<Trend> doInBackground(String... params) { 
String urlString = params[0]; HttpClient httpclient = new DefaultHttpClient(); 
HttpGet httpget = new HttpGet(urlString); try { 
HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); 
if (entity != null) { 
InputStream instream = entity.getContent(); 
String json = toString(instream); instream.close(); 
List<Trend> trends = getTrends(json); return trends; } } 
catch (Exception e) { Log.e("DEVMEDIA", "Falha ao acessar Web service", e); } 
return null; 

private List<Trend> getTrends(String jsonString) { 
List<Trend> trends = new ArrayList<Trend>(); 
try { 
JSONArray trendLists = new JSONArray(jsonString); 
JSONObject trendList = trendLists.getJSONObject(0); 
JSONArray trendsArray = trendList.getJSONArray("trends"); 
JSONObject trend; for (int i = 0; i < trendsArray.length(); i++) {
trend = new JSONObject(trendsArray.getString(i)); Log.i("DEVMEDIA", "nome=" + trend.getString("name")); Trend objetoTrend = new Trend(); objetoTrend.name = trend.getString("name"); objetoTrend.url = trend.getString("url"); trends.add(objetoTrend); } } catch (JSONException e) { Log.e("DEVMEDIA", "Erro no parsing do JSON", e); } return trends; 
}

@Override protected void onPostExecute(List<Trend> result) {
super.onPostExecute(result); dialog.dismiss(); 
if (result.size() > 0) { 
ArrayAdapter<Trend> adapter = new ArrayAdapter<Trend>( myActivity, android.R.layout.simple_list_item_1, result); 
setAdapter(adapter);  // ERRO AQUI.
//setListAdapter(adapter); 
else { 
AlertDialog.Builder builder = new AlertDialog.Builder(myActivity).setTitle("Atenção") .setMessage("Não foi possivel acessar essas informções...") .setPositiveButton("OK", null); builder.create().show(); 
} }

   
private String toString(InputStream is) throws IOException { 
byte[] bytes = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
int lidos; while ((lidos = is.read(bytes)) > 0) 
baos.write(bytes, 0, lidos); 
return new String(baos.toByteArray()); 
                                                       } 

}

class Trend { 
String name; String url; 
@Override public String toString() { 
return name; 
}






--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Thiago Lopes da SIlva
Recife-Pe

Skype: thiagoolsilva


Graduado em ciência da computação - FAPE
Especialização em dispositivos móveis com ênfase em Bada- Samsung
Especialização em dispositivos móveis - C.E.S.A.R. E.D.U.

Engenheiro de Sistemas - C.E.S.A.R.


"O rio corta a rocha não por causa de sua força, mas por causa de sua persistência"
                                                                                                        (Jim Watkins

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

0 comentários:

Postar um comentário