Loading [MathJax]/extensions/TeX/AMSsymbols.js

9 de mayo de 2012

JSON en Android

Ingeniería de Dispositivos Móviles
Laboratorio: Publicación 16
Esta publicación esta relacionada con la anterior de creación de un Tab Bar para la aplicación de Android, para no copiar de nuevo todos los códigos solo puse los dos en los cuales se hacen cambios significativos.

package ramon.app;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Principal extends ListActivity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = jsonfunctions.getJSONfromURL("http://mobileapp.comuf.com/userdata/test");
try {
JSONArray earthquakes = json.getJSONArray("blogger");
for (int i=0;i<earthquakes.length();i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", e.getString("titulo"));
map.put("magnitude", "Fecha: " + e.getString("fecha"));
mylist.add(map);
}
} catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(Principal.this, "ID '" + /*o.get("id") +*/ "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
view raw Principal.java hosted with ❤ by GitHub

Esta es la que tiene la conexión en sí y parsea los datos que recibimos desde el enlace que se menciona en el código anterior.

package ramon.app;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class jsonfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}


Nota: La imagen esta cortada porque es una versión anterior a la que tengo actualmente, y no quiero mover cosas antes de presentar mi proyecto.

Relacionados
Uso de JSON

1 comentario:

Nota: solo los miembros de este blog pueden publicar comentarios.