Problema em receber JSON e tratar com GSON

Na pagina 245 da apostila tem um metodo doInBackground

que tem a linha

String jsonDasProvas = new WebClient(endereco).get();

essa linha parece estar errada nao sei porque o eclipse nao passa essa linha de jeito nenhum.

Tem outras classes com nome parecido, mas nenhuma com o metodo get.

Alguem sabe oque eu posso fazer?

eu estava usando o jar gson 2.2.2 e mudei para o jar que é citado na apostila gson 2.1. Não adiantou

O erro foi o seguinte, na apostila bem antes fala sobre uma classe WebClient que nao tem nada ver com o gson 2.1.

no exercicio 9.4 fala sobre a classe, porem eu pedi um metodo get, e no exercicio esta post. Esta em algum lugar o metodo get? alguem esta com a apostila ae? kkk

Porque a quando eu faço essa linha

List<Produto> produtos =  BuscaProdutosTask(this).execute();

nao posso enviar this???

Principal

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Principal extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_principal);
		acoes();
	}

	private void acoes() {
		// TODO Auto-generated method stub
		Button listar = (Button) findViewById(R.id.btLista);
		Button cadastro = (Button) findViewById(R.id.btCadastro);
		listar.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Principal.this, Lista.class);
				startActivity(intent);
			}
		});
		cadastro.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Principal.this, Formulario.class);
				startActivity(intent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_principal, menu);
		return true;
	}
}

Lista

[code]public class Lista extends Activity {
private List lista;

@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.lista);
	//carregaLista();
	carregaJson();
}

private void carregaJson() {
	// TODO Auto-generated method stub
	List<Produto> produtos =  BuscaProdutosTask(this).execute();
}

@Override
protected void onResume() {
	// TODO Auto-generated method stub
	super.onResume();
	//carregaLista();
	carregaJson();
}
private void carregaLista() {
	// TODO Auto-generated method stub
	ListView listaDeProdutos = (ListView) findViewById(R.id.listaDeProdutos);
	ProdutoDAO dao = new ProdutoDAO(this);
	lista = dao.getLista();
	ArrayAdapter<Produto> adapter = new ArrayAdapter<Produto>(this,
			android.R.layout.simple_list_item_1, lista);
	listaDeProdutos.setAdapter(adapter);
}

}[/code]

WebClient

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class WebClient {
	private final String url;

	public WebClient(String url) {
		this.url = url;
	}

	public String post(String json) {
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			post.setEntity(new StringEntity(json));

			post.setHeader("Accept", "Application/json");
			post.setHeader("Content-type", "application/json");

			HttpResponse response = httpClient.execute(post);
			String jsonDeResposta = EntityUtils.toString(response.getEntity());
			return jsonDeResposta;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public String get() {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			
			HttpGet httpGet = new HttpGet(url);
			try {
				HttpResponse response = httpclient.execute(httpGet);
				
				String jsonRetorno = EntityUtils.toString(response.getEntity());
				
				return jsonRetorno;
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

BuscaProduto

public class BuscaProdutosTask extends AsyncTask<String, Object, List<Produto>> {
	private final FragmentActivity activity;
	private final String endereco = "endinesystem.com.br/android/";
	private ProgressDialog progress;

	public BuscaProdutosTask(FragmentActivity activity) {
		this.activity = activity;
		this.progress = ProgressDialog.show(activity, "Aguarde...",
				"Buscando os dados", true);
	}

	protected List<Produto> doInBackground(String... params) {
		try {
			String jsonDosProdutos = new WebClient(endereco).get();
			List<Produto> produtos = new ProdutoConverter()
					.listFromJson(jsonDosProdutos);
			return produtos;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

Ja coloquei o código todo porque estou com mta duvida nessa parte de conexao, esta muito obscuro

pessoal alguem sabe porque simplesmente fecha o app sem mandar nem um log?

	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// carregaLista();
		new Thread() {
			public void run() {
				carregaJson();
			}
		}.start();

pls help kkkk

Denis,

Qual exercicio você estava tentando fazer?

9.4 usando gson

o problema é que eu to usando essa thread mas ele simplesmente fecha assim que abre aquela tela de listagem

Você está enviando os dados via post ou você quer obter os dados via get?

obter via get

Segue oque eu estou fazendo com o get da classe WebClient
classe Lista

public class Lista extends Activity {
	private List<Produto> lista;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lista);
		// carregaLista();
		new Thread() {
			public void run() {
				carregaJson();
			}
		}.start();
	}

	private void carregaJson() {
		// TODO Auto-generated method stub
		ListView listaDeProdutos = (ListView) findViewById(R.id.listaDeProdutos);
		String json = new WebClient("www.enginesystem.com.br/android/").get();
		lista = new ProdutoConverter().listFromJson(json);
		ArrayAdapter<Produto> adapter = new ArrayAdapter<Produto>(this,
				android.R.layout.simple_list_item_1, lista);
		listaDeProdutos.setAdapter(adapter);
	}
}

WebClient

package com.example.pdv;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class WebClient {
	private final String url;

	public WebClient(String url) {
		this.url = url;
	}

	public String post(String json) {
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			post.setEntity(new StringEntity(json));

			post.setHeader("Accept", "Application/json");
			post.setHeader("Content-type", "application/json");

			HttpResponse response = httpClient.execute(post);
			String jsonDeResposta = EntityUtils.toString(response.getEntity());
			return jsonDeResposta;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public String get() {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			
			HttpGet httpGet = new HttpGet(url);
			try {
				HttpResponse response = httpclient.execute(httpGet);
				
				String jsonRetorno = EntityUtils.toString(response.getEntity());
				
				return jsonRetorno;
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

Para obter via get seria algo desse tipo aquele método get.

Da uma lida no Cap. 14 na Seção 1.

Segue o código do get:

public class WebClient {
	private final String url;

	public WebClient(String url) {
		this.url = url;
	}

	public String get() {
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet get = new HttpGet("http://www.caelum.com.br/mobile/provas");
			get.setHeader("Accept", "application/json");
			get.setHeader("Content-type", "application/json");
			HttpResponse response = httpClient.execute(get);
			String jsonDeResposta = EntityUtils.toString(response.getEntity());
			
			return jsonDeResposta;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

afffff eu tinha feito tudo certo, da uma olhada no get que eu tinha feito…
tem dois try, com uma macarronada dentro.

VLW cara funcionou perfeitamente, busca o json certinho e lista certinho.

vlw

ultima pergunta.
como posso fazer um jsonFromList?

este é listFromjson

	public List<Produto> listFromJson(String jsonDosProdutos) {
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();

		Type listType = new TypeToken<List<Produto>>() {
		}.getType();
		List<Produto> produtos = gson.fromJson(jsonDosProdutos, listType);
		return produtos;
	}

só usar o método toJson.

estou com um problema.

Ele fecha o app toda vez que abro a Lista.

vou postar o codigo todo

public class Lista extends Activity {

	private List<Produto> lista;

	String url = "www.enginesystem.com.br/android/";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lista);
		new Thread() {  
            public void run() {  
                carregaLista();  
            }  
        }.start();  
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		new Thread() {  
            public void run() {  
                carregaLista();  
            } 
        }.start();
	}

	private void carregaLista() {
		ListView listaDeProdutos = (ListView) findViewById(R.id.listaDeProdutos);  
        String json = new WebClient("www.enginesystem.com.br/android/").get();  
        lista = new ProdutoConverter().listFromJson(json);  
        ArrayAdapter<Produto> adapter = new ArrayAdapter<Produto>(this,  
                android.R.layout.simple_list_item_1, lista);  
        listaDeProdutos.setAdapter(adapter);
	}

	private void carregaLista2() {
		// TODO Auto-generated method stub
		ListView listaDeProdutos = (ListView) findViewById(R.id.listaDeProdutos);
		ProdutoDAO dao = new ProdutoDAO(Lista.this);
		lista = dao.getLista();
		ArrayAdapter<Produto> adapter = new ArrayAdapter<Produto>(this,
				android.R.layout.simple_list_item_1, lista);
		listaDeProdutos.setAdapter(adapter);
	}
}

public class WebClient {
	private final String url;

	public WebClient(String url) {
		this.url = url;
	}

	public String post(String json) {
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			post.setEntity(new StringEntity(json));

			post.setHeader("Accept", "Application/json");
			post.setHeader("Content-type", "application/json");

			HttpResponse response = httpClient.execute(post);
			String jsonDeResposta = EntityUtils.toString(response.getEntity());
			return jsonDeResposta;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public String get() {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpGet);
			String jsonRetorno = EntityUtils.toString(response.getEntity());
			return jsonRetorno;

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

public class ProdutoConverter {
	public List<Produto> listFromJson(String jsonDosProdutos) {
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();

		Type listType = new TypeToken<List<Produto>>() {
		}.getType();
		List<Produto> produtos = gson.fromJson(jsonDosProdutos, listType);
		return produtos;
	}
}

log do código acima

11-09 14:32:29.215: W/dalvikvm(31698): threadid=11: thread exiting with uncaught exception (group=0x40bd71f8)