To read your JSON
on android an alternative is by means of a Asynctask
, there are other libraries like retrofit , volley .
In this case I will show you how to do it with an Asynctask ( see documentation )
and then show your data in a listview
to verify that it reads them, then you can perform the action you want. removing listview
, etc
// declaramos dos variables para manejar el tiempo de conexión y un String para almacenar-mostrar los datos depues en el listview
String pregrespcomment;
ListView mostrarr;
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
private class leer_datos extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(ganancias_totales.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tConsultando...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
url = new URL("http://www.tu_sitio/tu_archivo.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(ganancias_totales.this);
alertaDeError.setTitle("Error");
alertaDeError.setMessage("Ups, no se han podido cargar los datos. Intentelo de nuevo.");
alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertaDeError.create();
alertaDeError.show();
} else {
//Existen Datos
List<String> preguntas = new ArrayList<String>();
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject preguntaDatos = null;
try {
preguntaDatos = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
assert preguntaDatos != null;
pregrespcomment =" datos: " + "\n" +">+ preguntaDatos.getString("pkusu"),preguntaDatos.getString("pass");
} catch (JSONException e) {
e.printStackTrace();
}
preguntas.add(pregrespcomment);
}
//crear el Adapter.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ejemplo.this, android.R.layout.simple_list_item_1, preguntas);
mostrarr.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(ganancias_totales.this);
alertaDeError.setTitle("Error");
alertaDeError.setMessage("Ups, no existen datos. Intentelo de nuevo.");
alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertaDeError.create();
alertaDeError.show();
}
}
}
}