I have an android app where I do a load from a database. In the following link I asked why my code gave me an error, for which the table with the query data was not loaded correctly.
After changing my code based on A.Cedano's answer, the program doesn't respond as it should. My code is the following:
@Override
public void onDateChanged(DatePicker view, int year, int month, int day){
String username = i.getStringExtra("us_usuario");
String password = i.getStringExtra("us_clave");
int Año = calendario.getYear();
int Mes = calendario.getMonth()+1;
int Dia = calendario.getDayOfMonth();
String fecha = Año+"-"+Mes+"-"+Dia;
Response.Listener<String> responseListener = new Response.Listener<String>(){
@Override
public void onResponse(String response){
ArrayList<String> arrayRespuesta = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
String hora_inicio, fecha, nombre, apellidos, prestacion;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
hora_inicio = jsonObject.getString("hora_inicio");
fecha = jsonObject.getString("fecha");
nombre = jsonObject.getString("nombre");
apellidos = jsonObject.getString("apellidos");
prestacion = jsonObject.getString("prestacion");
int[] comprobarFecha = separarFecha(fecha);
if(comprobarFecha[0] == calendario.getYear() && comprobarFecha[1] == calendario.getMonth()+1 && comprobarFecha[2] == calendario.getDayOfMonth()){
arrayRespuesta.add(hora_inicio);
arrayRespuesta.add(nombre);
arrayRespuesta.add(apellidos);
arrayRespuesta.add(prestacion);
}
}
}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();
}
if(!arrayRespuesta.isEmpty()){
tablePaciente.removeAllViews();
TablaPacientes tabla = new TablaPacientes(Usuario.this, tablePaciente);
tabla.agregarCabecera(R.array.tabla_pacientes);
agregarFila(arrayRespuesta);
}else{
tablePaciente.removeAllViews();
Toast t = Toast.makeText(getApplicationContext(), "No hay pacientes para esta fecha", Toast.LENGTH_LONG);
t.show();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, password, fecha, responseListener);
RequestQueue queue = Volley.newRequestQueue(Usuario.this);
queue.add(registerRequest);
}
The addRow method is as follows, further down in the same class (to do this I used the information from the following question: Create columns dynamically in Android ):
public void agregarFila(ArrayList<String> elementos){
int num_cols = 4;
TableRow.LayoutParams layoutCelda;
tablePaciente = (TableLayout) findViewById(R.id.tablePaciente);
TableRow fila = new TableRow(this);
for(int i=0; i<elementos.size(); i++){
TextView texto = new TextView(this);
texto.setText(String.valueOf(elementos.get(i)));
texto.setGravity(Gravity.START);
layoutCelda = new TableRow.LayoutParams(obtenerAnchoPixelesTexto(texto.getText().toString()), TableRow.LayoutParams.WRAP_CONTENT);
texto.setLayoutParams(layoutCelda);
fila.addView(texto);
for (int j=0; j<num_cols; j++){
TableRow tableRow = new TableRow(this);
tablePaciente.addView(tableRow);
}
}
tablePaciente.addView(fila);
}
And the result that the json gives is the following:
[
{
"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"
},
{
"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"
}
]
However, it only shows me the first query, that is, when I select the date of October 29, it only shows me the JACINTO data, as seen in the following image:
Any idea how to make it show me all the queries?
(Edited from @A.Cedano's answer)
When creating the RecyclerViewAdapterUser class, the RecyclerView class does not recognize me.
The code of my Gradle file is the following (my minimum version is 15 and the maximum is 26)
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.tigestion.guillermo.prueba"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
}
Do I have to import something special or do something to get the RecyclerView to recognize me?
Ok, solved the RecyclerView error, it is solved by doing Build->Clean Project and then Build->Rebuild Project.
Android allows to implement
RecyclerView
for this type of operations. Its use opens up a whole world of possibilities that would be long to explain now, but it is something that you will be able to delve into later.I will make you a proposal based on this methodology, without dwelling too much on the details of how you obtain the data.
Step 0: Configuration required
RecyclerView
it is part of the V7 support library.gradle
For it to work, you need to add this dependency in the app file . You don't have to add anotherdependencies
section, but look for that section and put in this line:compile 'com.android.support:recyclerview-v7:21.0.+'
.For more compatibility details you can refer to this Android link .
Step 1:
We will call the activity where you want to display the table
TablaActivity
.We are going to create a layout
activity_tabla
that will contain theRecyclerView
:Step 2
We create a layout that will contain the different columns of the table. In this example we will have a layout with two columns. We will call you
table_layout
. This is two textView inside a linearlayout:Step 3:
Let's create a data model.
Data models are a highly recommended practice. Generally a data model represents a complete entity of our application, for example, a database table.
The convenience of handling data models is impressive in any case, for example with the Gson library you could get your JSON objects into the data model
Usuarios
directly.For them
RecyclerView
we will also see their importance and the clarity they bring to the code.Imaginemos un modelo de datos simple... Luego lo puedes adaptar.
Este modelo tendrá todos los métodos que quieras, de forma que lo uses para todo lo que sea relativo a usuarios.
Paso 4:
Crearemos un adaptador que hará de intermediario entre el
RecyclerView
y nuestro modelo de datos:Paso 5:
¡Al fin! Ahora viene lo bueno.
Nótese que todo lo anterior es algo que tendremos fijo en nuestra App. Ahora vamos a cosechar las ventajas de haber trabajado tanto.
Este sería un modelo de
TablaActivity
, la actividad principal que mencionaba en el Paso 1. Aunque este código lo podemos implementar desde cualquier otra parte de la App donde necesitemos manejarUsuarios
presentándolos en una tabla.The result is a table of users... and clicking on any of them displays their id in the toaster.
This code can be adapted, for example to show more details of a specific user when clicking on it, to show a
CardView
, to add or remove users from the table, etc.The possibilities of this way of obtaining and using data are enormous.
Links:
There are many interesting tutorials on the subject. Here are some: