-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCargarDatosListas.java
More file actions
351 lines (299 loc) · 13.7 KB
/
Copy pathCargarDatosListas.java
File metadata and controls
351 lines (299 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package com.example.pruebaderuta;
import static android.content.Context.MODE_PRIVATE;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.widget.ExpandableListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
/**
* Clase para cargar los datos de los diferentes fragments: Comer, Dormir, Senderismo, ...
* En caso de no conexión carga los datos de sqlite y reintenta la carga de datos hasta que tiene conexión.
* La carga de sqlite se hace una vez, para ello hay un controlador booleano.
*/
public class CargarDatosListas {
private static String fechaInsercion;
private static HashMap<String, List<GetSet>> datosHM;
private static Handler handler; // para la carga cada x tiempo al no haber datos.
private static Runnable reintento;
private static int INTERVALO_RECARGA_DATOS = 20000;
private static String tipoFragment = "";
private static boolean primeraCarga = true;
public interface OnDatosCargadosListener {
void onDatosCargados(HashMap<String, List<GetSet>> datos);
}
public static void cargarDatosDesdeFirestore(Context context, ExpandableListView expandableListView, String tipo, OnDatosCargadosListener listener) {
cancelarReintento();
if (!tipo.equals(tipoFragment)) {
primeraCarga = true;
tipoFragment = tipo;
}
FirebaseFirestore db = FirebaseFirestore.getInstance();
datosHM = new HashMap<>();
SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.prefs_file), MODE_PRIVATE);
String grupo = prefs.getString("grupo", "Predefinido");
CollectionReference datosRef = db.collection("grupos").document(grupo).collection("datos");
Query query = datosRef.whereEqualTo("tipo", tipo);
query.get().addOnSuccessListener(queryDocumentSnapshots -> {
boolean conexionInternet = hayConexionInternet(context);
if(!conexionInternet){
boolean datosCargados = enCasoDeNoInternet(context, tipo, expandableListView, listener, queryDocumentSnapshots);
if (datosCargados) return;
}
borrarTodosLosDatos(context, tipo);
for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
GetSet getSet = new GetSet(
doc.getId(),
doc.getString("nombre"),
doc.getString("descripcion"),
doc.getString("web"),
doc.getString("provincia"),
doc.getString("tipo"),
doc.getString("visitado"),
doc.getString("usuario")
);
insertarEnDbDatos(context,
doc.getId(),
doc.getString("nombre"),
doc.getString("descripcion"),
doc.getString("web"),
doc.getString("provincia"),
doc.getString("tipo"),
doc.getString("visitado"),
doc.getString("usuario")
);
String provincia = doc.getString("provincia");
if (!datosHM.containsKey(provincia)) {
datosHM.put(provincia, new ArrayList<>());
}
datosHM.get(provincia).add(getSet);
}
rellenarAdaptador(expandableListView, context, tipo, listener);
if (datosHM == null || datosHM.isEmpty()) {
Toast.makeText(context, "No hay datos registrados", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(e -> {
Log.e("jfc", "Error obteniendo datos: ", e);
Toast.makeText(context, "Error cargando datos. Intenta más tarde.", Toast.LENGTH_SHORT).show();
// Carga local en caso de error
datosHM = cargarDatosTemporales(context, tipo);
rellenarAdaptador(expandableListView, context, tipo, listener);
});
}
/**
* En caso de que no haya coexión a internet se ejecuta lo siguiente.
* @param context
* @param tipo
* @param expandableListView
* @param listener
* @param queryDocumentSnapshots
* @return
*/
private static boolean enCasoDeNoInternet(Context context, String tipo, ExpandableListView expandableListView,OnDatosCargadosListener listener, QuerySnapshot queryDocumentSnapshots) {
//como me cargaba los datos de caché de firestore, hago este booleano para comprobar si es el caso,
//y en caso afirmativo recupero de sqlite
boolean desdeCache = false;
if (!queryDocumentSnapshots.isEmpty()) {
desdeCache = queryDocumentSnapshots.getMetadata().isFromCache();
}else{
Toast.makeText(context, "Revisa tu conexión a internet", Toast.LENGTH_SHORT).show();
}
// Log.i("jfc", "Firestore entró. Documentos: " + queryDocumentSnapshots.size() + " ,¿desde caché?: " + desdeCache);
if (desdeCache) {
if(primeraCarga){
Log.w("jfc", "Datos vienen de la caché. Forzando carga desde SQLite");
datosHM = cargarDatosTemporales(context, tipo);
rellenarAdaptador(expandableListView, context, tipo, listener);
primeraCarga = false;
}else{
Log.i("jfc","Ya no es primera carga, no se hace nada.");
}
reintento(context,expandableListView,tipo,listener);
return true;
}
return false;
}
/**
* En este método se cargan los datos de sqlite, bbdd en el móvil, y se usan si no hay conexión en el móvil.
*
* @param context
* @return
*/
private static HashMap<String, List<GetSet>> cargarDatosTemporales(Context context, String tipoFragment) {
String tipoABuscar = primeraLetraMayuscula(tipoFragment);
HashMap<String, List<GetSet>> datosHM = new HashMap<>();
SQLiteDatabase db = new BaseDeDatos(context).getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT id, fechaInsercion, nombre, descripcion, web, provincia, tipo, visitado, usuario FROM datos WHERE tipo = ?",
new String[]{tipoABuscar});
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndexOrThrow("id"));
String nombre = cursor.getString(cursor.getColumnIndexOrThrow("nombre"));
String descripcion = cursor.getString(cursor.getColumnIndexOrThrow("descripcion"));
String web = cursor.getString(cursor.getColumnIndexOrThrow("web"));
String provincia = cursor.getString(cursor.getColumnIndexOrThrow("provincia"));
String tipo = cursor.getString(cursor.getColumnIndexOrThrow("tipo"));
String visitado = cursor.getString(cursor.getColumnIndexOrThrow("visitado"));
String usuario = cursor.getString(cursor.getColumnIndexOrThrow("usuario"));
fechaInsercion = cursor.getString(cursor.getColumnIndexOrThrow("fechaInsercion"));
GetSet getSet = new GetSet(id, nombre, descripcion, web, provincia, tipo, visitado, usuario);
if (!datosHM.containsKey(provincia)) {
datosHM.put(provincia, new ArrayList<>());
}
datosHM.get(provincia).add(getSet);
} while (cursor.moveToNext());
Toast.makeText(context, "SIN CONEXIÓN mostrando datos guardados el " + fechaInsercion, Toast.LENGTH_SHORT).show();
} else {
Log.e("jfc", "No se encontraron datos locales.");
Toast.makeText(context, "SIN CONEXIÓN y tampoco hay datos guardados", Toast.LENGTH_SHORT).show();
}
cursor.close();
db.close();
return datosHM;
}
private static void reintento(Context context, ExpandableListView expandableListView, String tipo, OnDatosCargadosListener listener){
handler = new Handler();
reintento = () -> {
Log.i("jfc", "Reintentando conexión con el servidor para ver: " + tipo);
cargarDatosDesdeFirestore(context, expandableListView, tipo, listener);
};
handler.postDelayed(reintento, INTERVALO_RECARGA_DATOS);
}
/**
* Método para cancelar el reintento de carga de datos.
*/
public static void cancelarReintento() {
if (handler != null && reintento != null) {
handler.removeCallbacks(reintento);
Log.i("jfc", "Reintento cancelado en: " + tipoFragment);
}
}
/**
* Método para rellenar el adaptador.
*
* @param expandableListView
* @param context
* @param tipo
* @param listener
*/
private static void rellenarAdaptador(ExpandableListView expandableListView, Context context, String tipo, OnDatosCargadosListener listener) {
Adaptador adaptador = new Adaptador(expandableListView, datosHM, context, tipo);
expandableListView.setAdapter(adaptador);
if (listener != null) {
listener.onDatosCargados(datosHM);
}
}
public static String primeraLetraMayuscula(String texto) {
if (texto == null || texto.isEmpty()) {
return texto;
}
return texto.substring(0, 1).toUpperCase() + texto.substring(1).toLowerCase();
}
/**
* Borrar db para luego insertar.
*
* @param context
*/
private static void borrarTodosLosDatos(Context context, String tipo) {
String tipoABorrar = primeraLetraMayuscula(tipo);
SQLiteDatabase db = new BaseDeDatos(context).getWritableDatabase();
db.delete("datos", "tipo = ?", new String[]{tipoABorrar});
db.close();
// Log.i("jfc", "Borrado de datos realizado en CargarDatosListas: " + tipo);
}
/**
* Métodopara insertar los datos traídos de la bbdd.
*
* @param context
* @param nombre
* @param descripcion
* @param web
* @param provincia
* @param tipo
* @param visitado
* @param usuario
*/
private static void insertarEnDbDatos(Context context, String id, String nombre, String descripcion, String web, String provincia, String tipo, String visitado, String usuario) {
String fechaActual = obtenerFechaHora();
SQLiteDatabase db = new BaseDeDatos(context).getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put("id", id);
valores.put("nombre", nombre);
valores.put("descripcion", descripcion);
valores.put("web", web);
valores.put("provincia", provincia);
valores.put("tipo", tipo);
valores.put("visitado", visitado);
valores.put("usuario", usuario);
valores.put("fechaInsercion", fechaActual);
long resultado = db.insert("datos", null, valores);
if (resultado == -1) {
Log.e("jfc", "Error al insertar en la base de datos en cargarDatosListas.java en el tipo " + tipo);
} else {
// Log.d("jfc", "Insertado correctamente en cargarDatosListas.java");
}
db.close();
}
/**
* Método para obtener la fecha y la hora actual.
*
* @return
*/
private static String obtenerFechaHora() {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
return sdf.format(new Date());
}
/**
* Boleano para comprobar si hay conexón a internet.
* @param context
* @return
*/
public static boolean hayConexionInternet(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) return false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = cm.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = cm.getNetworkCapabilities(network);
return capabilities != null &&
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET));
} else {
// Para versiones antiguas de Android (< Marshmallow)
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
}
}