我在 Android 应用程序中使用 JSONArray 对象来使用查询返回的内容动态填充表。问题是直到现在我都在使用一个 JSONObject,用它填充了表,但它只在获得的最后一个查询中完成,所以它对应用程序的最佳工作没有用处。
我即兴获得查询的代码(至少开始测试)如下(根据 Pablo Simon DiEstefano 的回答编辑):
Response.Listener<String> responseListener = new Response.Listener<String>(){
@Override
public void onResponse(String response){
try {
JSONArray jsonArray = new JSONArray(response);
String hora_inicio, hora_fin, fecha, nombre, apellidos, prestacion;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
hora_inicio = jsonObject.getString("hora_inicio");
hora_fin = jsonObject.getString("hora_fin");
fecha = jsonObject.getString("fecha");
nombre = jsonObject.getString("nombre");
apellidos = jsonObject.getString("apellidos");
prestacion = jsonObject.getString("prestacion");
String[] arrayRespuesta = {hora_inicio, hora_fin, nombre, apellidos, prestacion};
int[] comprobarFecha = separarFecha(fecha);
TablaPacientes tabla = new TablaPacientes(Usuario.this, tablePaciente);
if (comprobarFecha[0] == calendario.getYear() && comprobarFecha[1] == calendario.getMonth() + 1 && comprobarFecha[2] == calendario.getDayOfMonth()) {
//tablePaciente.removeAllViews();
tabla.agregarCabecera(R.array.tabla_pacientes);
cargarTabla(tabla, arrayRespuesta);
} else {
tablePaciente.removeAllViews();
Toast t = Toast.makeText(getApplicationContext(), "Año" + comprobarFecha[0] + "Mes" + comprobarFecha[1] + "Dia" + comprobarFecha[2], Toast.LENGTH_LONG);
t.show();
}
}
}catch(JSONException e){
tablePaciente.removeAllViews();
Toast t = Toast.makeText(getApplicationContext(), "No hay pacientes para esta fecha", Toast.LENGTH_LONG);
t.show();
}catch(ArrayIndexOutOfBoundsException e){
tablePaciente.removeAllViews();
AlertDialog.Builder builder = new AlertDialog.Builder(Usuario.this);
builder.setMessage("Error de excepción en el array "+e.getLocalizedMessage())
.setNegativeButton("Retry", null)
.create().show();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, password, fecha, responseListener);
RequestQueue queue = Volley.newRequestQueue(Usuario.this);
queue.add(registerRequest);
使用此代码,应用程序会给我一个错误,尽管它不是编程错误。开始时,理论上它应该给我的是两个表,一个接一个,用于查询的每个结果。但是,我第一次约会时,得到以下信息
出来的是与第二个查询对应的表,以及一个额外的标题。但是,当我再次点击日期时,我得到以下信息:
由于设备的大小,它不是很受欢迎,但在那一刻我得到了第一个结果(第一个表和标题)加上一个带有第一个结果的表,第二个和一个标题
知道如何解决这个问题吗?
这是我的 JSON 的结果
[
{
"us_usuario": "DONATE",
"us_clave": "DONATE",
"hora_inicio": "18:20",
"hora_fin": "18:35",
"fecha": "2017-10-29",
"nombre": "JUAN MANUEL",
"apellidos": "LLORENTE RODRIGO",
"prestacion": "REVISION OFTALMOLOGICA"
},
{
"us_usuario": "DONATE",
"us_clave": "DONATE",
"hora_inicio": "14:00",
"hora_fin": "14:15",
"fecha": "2017-10-29",
"nombre": "JACINTO",
"apellidos": "JARAMILLO ROMERO",
"prestacion": "FOTOCOAGULACION DR"
}
]
我认为错误来自这一行:
如果您注意到,jsonArray 的长度为 2:
因此,在这样做时:
您正在制作一个 -1 位置数组,这是不正确的。
要获取数据,您可以通过以下方式进行: