Skip to content

Instantly share code, notes, and snippets.

Created January 4, 2013 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4451519 to your computer and use it in GitHub Desktop.
Save anonymous/4451519 to your computer and use it in GitHub Desktop.
package com.kustomrtr.dolarparalelovenezuela;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Json extends AsyncTask<String, Float, JSONObject> {
private String json_url = "";
private MainActivity myMainActivity;
private Context contexto;
private Activity activity;
public Json(MainActivity activity) {
myMainActivity = activity;
this.activity = activity;
contexto = myMainActivity.getApplicationContext();
}
public JSONObject getJSON(String url) {
// inicialización
InputStream is = null;
String result = "";
JSONObject jArray = null;
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// convertir respuesta a string
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = sb.toString();
// parseando string a un objeto JSON
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jArray;
}
protected void onPreExecute() {
Toast toast = Toast.makeText(contexto, "Ejecutando thread",
Toast.LENGTH_LONG);
toast.show();
}
@Override
protected JSONObject doInBackground(String... uri) {
json_url = uri[0];
JSONObject jstring = null;
try {
jstring = this.getJSON(uri[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jstring;
}
@Override
protected void onProgressUpdate(Float... progress) {
Toast toast = Toast.makeText(contexto, "Progreso: " + progress[0],
Toast.LENGTH_LONG);
toast.show();
}
@Override
protected void onPostExecute(JSONObject result) {
/*
* Toast toast = Toast.makeText(contexto, "Thread terminado. ",
* Toast.LENGTH_LONG); toast.show();
*/
// Arraylist initialitation
ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String, String>>();
// Array of strings "titulos"
String titulos[] = { "Dolar (Transferencia)", "Euro (Transferencia)",
"Dolar (Efectivo)", "Euro (Efectivo)", "Dolar (cúcuta)",
"Euro (cucuta)" };
try {
JSONObject json = result; // result is a JSONObject and the source is located here: https://dl.dropbox.com/u/8102604/dolar.json
JSONObject root = json.getJSONObject("root");
JSONArray items = root.getJSONArray("item");
int j = 0;
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
String key = item.getString("key");
String mount = item.getString("mount");
if (key.equals("TS") || key.equals("TE") || key.equals("EE")
|| key.equals("CE") || key.equals("ES")
|| key.equals("CS")) { // i did this since i only need the items where the key is equal to TS, TE, EE, CE, ES or CS.
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", String.valueOf(i));
map.put(key, mount);
lista.add(map);
System.out.println(titulos[j] + "(" + key + "). BsF = " + mount); // just for debugging purposes
j++; // add 1 to j if key is equal to TS, TE, EE, CE, ES or CS. In this way i can associate the two arrays (item and titulos)
}
}
ListView lv = (ListView) myMainActivity.findViewById(R.id.listView1); // create a list view
lv.setAdapter(new ArrayAdapter<String>(contexto, android.R.layout.simple_list_item_1, lista)); // set adapter to the listview (not working)
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
package com.kustomrtr.dolarparalelovenezuela;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Json(this).execute("http://192.168.1.5/dolar.json");
} // on create
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment