In un precedente articolo vi avevo mostrato come riempire uno Spinner in Android prendendo i dati in remoto in formato JSON.
Oggi vedremo come fare la stessa operazione con una ListView, che però inseriremo in un Fragment.
La base di partenza per i Fragment dentro a un Tab la potete trovare qua.
Adesso andremo a riempire il nostro Fragment con una ListView.
Prima però andiamo a prendere la classe Service per il recupero dei dati:
public class Service {
private final String remote = "http://www.example.com/";
public String login(String user, String pwd) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(remote + "login.php");
List nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("pwd", pwd));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
String result = null;
while ((line = reader.readLine()) != null) {
result = line;
}
reader.close();
return result;
}
public String getLastItems(String phpFile) throws ClientProtocolException, IOException, JSONException {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(remote + phpFile);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
}
Questo è il metodo che ci servirà nel Fragment, metodo a simile a quello spiegato in altri articoli, quindi non mi ci soffermo.