· 9 years ago · Nov 19, 2016, 10:36 PM
1package com.herprogramacion.alquileres;
2
3import android.database.Cursor;
4import android.os.Bundle;
5import android.support.design.widget.FloatingActionButton;
6import android.support.design.widget.Snackbar;
7import android.support.v4.app.LoaderManager;
8import android.support.v4.content.CursorLoader;
9import android.support.v4.content.Loader;
10import android.support.v7.app.AppCompatActivity;
11import android.support.v7.widget.LinearLayoutManager;
12import android.support.v7.widget.RecyclerView;
13import android.support.v7.widget.Toolbar;
14import android.view.Menu;
15import android.view.MenuItem;
16import android.view.View;
17
18import com.herprogramacion.alquileres.provider.Contrato.Alquileres;
19
20public class ActividadListaAlquileres extends AppCompatActivity implements AdaptadorAlquileres.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {
21
22private RecyclerView listaUI;
23private LinearLayoutManager linearLayoutManager;
24private AdaptadorAlquileres adaptador;
25
26@Override
27protected void onCreate(Bundle savedInstanceState) {
28 super.onCreate(savedInstanceState);
29 setContentView(R.layout.actividad_lista_alquileres);
30 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
31 setSupportActionBar(toolbar);
32
33 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
34 fab.setOnClickListener(new View.OnClickListener() {
35 @Override
36 public void onClick(View view) {
37 Snackbar.make(view, "Filtro...", Snackbar.LENGTH_LONG)
38 .setAction("Acción", null).show();
39 }
40 });
41
42 // Preparar lista
43
44
45 listaUI = (RecyclerView) findViewById(R.id.lista);
46
47
48 listaUI.setHasFixedSize(true);
49
50 linearLayoutManager = new LinearLayoutManager(this);
51
52
53 listaUI.setLayoutManager(linearLayoutManager);
54
55
56 adaptador = new AdaptadorAlquileres(this, this);
57
58
59 listaUI.setAdapter(adaptador);
60
61
62 // Iniciar loader
63 getSupportLoaderManager().restartLoader(1, null, this);
64
65}
66
67@Override
68public boolean onCreateOptionsMenu(Menu menu) {
69 getMenuInflater().inflate(R.menu.menu_actividad_lista_alquileres, menu);
70 return true;
71}
72
73@Override
74public boolean onOptionsItemSelected(MenuItem item) {
75 int id = item.getItemId();
76
77 if (id == R.id.action_settings) {
78 return true;
79 }
80
81 return super.onOptionsItemSelected(item);
82}
83
84@Override
85public void onClick(AdaptadorAlquileres.ViewHolder holder, String idAlquiler) {
86 Snackbar.make(findViewById(android.R.id.content), ":id = " + idAlquiler,
87 Snackbar.LENGTH_LONG).show();
88}
89
90
91@Override
92public Loader<Cursor> onCreateLoader(int id, Bundle args) {
93 return new CursorLoader(this, Alquileres.URI_CONTENIDO, null, null, null, null);
94}
95
96@Override
97public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
98 if (adaptador != null) {
99 adaptador.swapCursor(data);
100 }
101}
102
103@Override
104public void onLoaderReset(Loader<Cursor> loader) {
105}
106}
107
108package com.herprogramacion.alquileres;
109
110import android.content.Context;
111import android.database.Cursor;
112import android.support.v7.widget.RecyclerView;
113import android.view.LayoutInflater;
114import android.view.View;
115import android.view.ViewGroup;
116import android.widget.ImageView;
117import android.widget.TextView;
118
119import com.bumptech.glide.Glide;
120
121
122
123public class AdaptadorAlquileres extends RecyclerView.Adapter<AdaptadorAlquileres.ViewHolder> {
124private final Context contexto;
125private Cursor items;
126
127private OnItemClickListener escucha;
128
129interface OnItemClickListener {
130 public void onClick(ViewHolder holder, String idAlquiler);
131}
132
133public class ViewHolder extends RecyclerView.ViewHolder
134 implements View.OnClickListener {
135 // Referencias UI
136 public TextView viewNombre;
137 public TextView viewUbicacion;
138 public TextView viewDescripcion;
139 public TextView viewPrecio;
140 public ImageView viewFoto;
141
142 public ViewHolder(View v) {
143 super(v);
144 viewNombre = (TextView) v.findViewById(R.id.nombre);
145 viewUbicacion = (TextView) v.findViewById(R.id.ubicacion);
146 viewDescripcion = (TextView) v.findViewById(R.id.descripcion);
147 viewPrecio = (TextView) v.findViewById(R.id.precio);
148 viewFoto = (ImageView) v.findViewById(R.id.foto);
149 v.setOnClickListener(this);
150 }
151
152 @Override
153 public void onClick(View view) {
154 escucha.onClick(this, obtenerIdAlquiler(getAdapterPosition()));
155 }
156}
157
158private String obtenerIdAlquiler(int posicion) {
159 if (items != null) {
160 if (items.moveToPosition(posicion)) {
161 return items.getString(ConsultaAlquileres.ID_ALQUILER);
162 }
163 }
164
165 return null;
166}
167
168public AdaptadorAlquileres(Context contexto, OnItemClickListener escucha) {
169 this.contexto = contexto;
170 this.escucha = escucha;
171
172}
173
174@Override
175public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
176 View v = LayoutInflater.from(parent.getContext())
177 .inflate(R.layout.item_lista_alquiler, parent, false);
178 return new ViewHolder(v);
179}
180
181@Override
182public void onBindViewHolder(ViewHolder holder, int position) {
183 items.moveToPosition(position);
184
185 String s;
186
187 // Asignación UI
188 s = items.getString(ConsultaAlquileres.NOMBRE);
189 holder.viewNombre.setText(s);
190
191 s = items.getString(ConsultaAlquileres.UBICACION);
192 holder.viewUbicacion.setText(s);
193
194 s = items.getString(ConsultaAlquileres.DESCRIPCION);
195 holder.viewDescripcion.setText(s);
196
197 s = items.getString(ConsultaAlquileres.PRECIO);
198 holder.viewPrecio.setText(String.format("%s", s));
199
200 s = items.getString(ConsultaAlquileres.URL);
201 Glide.with(contexto).load(s).centerCrop().signature(new StringSignature(UUID.randomUUID().toString())).into(holder.viewFoto);
202
203
204
205}
206
207@Override
208public int getItemCount() {
209 if (items != null)
210 return items.getCount();
211 return 0;
212}
213
214public void swapCursor(Cursor nuevoCursor) {
215 if (nuevoCursor != null) {
216 items = nuevoCursor;
217 notifyDataSetChanged();
218 }
219}
220
221public Cursor getCursor() {
222 return items;
223}
224
225interface ConsultaAlquileres {
226 int ID_ALQUILER = 1;
227 int NOMBRE = 2;
228 int UBICACION = 3;
229 int DESCRIPCION = 4;
230 int PRECIO = 5;
231 int URL = 6;
232}
233}
234
235package com.herprogramacion.alquileres.provider;
236
237import android.content.ContentValues;
238import android.content.Context;
239import android.database.sqlite.SQLiteDatabase;
240import android.database.sqlite.SQLiteException;
241import android.database.sqlite.SQLiteOpenHelper;
242import android.provider.BaseColumns;
243
244import com.herprogramacion.alquileres.provider.Contrato.Alquileres;
245
246
247public class BaseDatos extends SQLiteOpenHelper {
248
249static final int VERSION = 1;
250
251static final String NOMBRE_BD = "alquileres.db";
252
253
254interface Tablas {
255 String APARTAMENTO = "alquiler";
256}
257
258public BaseDatos(Context context) {
259 super(context, NOMBRE_BD, null, VERSION);
260}
261
262@Override
263public void onCreate(SQLiteDatabase db) {
264 db.execSQL(
265 "CREATE TABLE " + Tablas.APARTAMENTO + "("
266 + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
267 + Alquileres.ID_ALQUILER + " TEXT UNIQUE NOT NULL,"
268 + Alquileres.NOMBRE + " TEXT NOT NULL,"
269 + Alquileres.UBICACION + " TEXT NOT NULL,"
270 + Alquileres.DESCRIPCION + " TEXT NOT NULL,"
271 + Alquileres.PRECIO + " REAL NOT NULL,"
272 + Alquileres.URL_IMAGEN + " TEXT NOT NULL)");
273
274 // Registro ejemplo #1
275 ContentValues valores = new ContentValues();
276 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
277 valores.put(Alquileres.NOMBRE, "Mis representantes");
278 valores.put(Alquileres.UBICACION, "México");
279 valores.put(Alquileres.DESCRIPCION, "Conoce a los posibles candidatos a la presidencia de México 2018");
280 valores.put(Alquileres.PRECIO, "¿Quiénes son?");
281 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/misrepresentantes.jpg");
282 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
283
284 // Registro ejemplo #2
285 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
286 valores.put(Alquileres.NOMBRE, "Elecciones");
287 valores.put(Alquileres.UBICACION, "México");
288 valores.put(Alquileres.DESCRIPCION, "Las elecciones federales de México de 2018, denominadas oficialmente por la autoridad electoral como el Proceso Electoral Federal 2017 — 2018...");
289 valores.put(Alquileres.PRECIO, "¡Enterate!");
290 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/elecciones.jpg");
291 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
292
293 // Registro ejemplo #3
294 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
295 valores.put(Alquileres.NOMBRE, "Reformas y leyes");
296 valores.put(Alquileres.UBICACION, "México");
297 valores.put(Alquileres.DESCRIPCION, "Enterate de las reformas federales vigentes asi como las proximas a tratar");
298 valores.put(Alquileres.PRECIO, "¿En que nos afectan?");
299 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/reformasyleyes.jpg");
300 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
301
302 // Registro ejemplo #4
303 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
304 valores.put(Alquileres.NOMBRE, "Noticias");
305 valores.put(Alquileres.UBICACION, "México");
306 valores.put(Alquileres.DESCRIPCION, "Noticias en tiempo real y anuncios clasificados de todo lo relacionado a las elecciones 2018");
307 valores.put(Alquileres.PRECIO, "Mantente enterado");
308 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/noticias.jpg");
309 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
310
311 // Registro ejemplo #5
312 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
313 valores.put(Alquileres.NOMBRE, "MovilÃzate");
314 valores.put(Alquileres.UBICACION, "México");
315 valores.put(Alquileres.DESCRIPCION, "Enterate que puedes hacer por tu pais, movilizate!!!");
316 valores.put(Alquileres.PRECIO, "¿Por qué?");
317 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/movilizate.jpg");
318 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
319
320 // Registro ejemplo #6
321 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
322 valores.put(Alquileres.NOMBRE, "¿Porqué participar?");
323 valores.put(Alquileres.UBICACION, "México");
324 valores.put(Alquileres.DESCRIPCION, "No te preguntes qué puede hacer tu paÃs por ti, pregúntate que puedes hacer tú por tu paÃs");
325 valores.put(Alquileres.PRECIO, "¡Animate!");
326 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/porqueparticipar.jpg");
327 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
328
329 // Registro ejemplo #7
330 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
331 valores.put(Alquileres.NOMBRE, "¿Quiénes somos?");
332 valores.put(Alquileres.UBICACION, "México");
333 valores.put(Alquileres.DESCRIPCION, "Somos una asociacion civil comprometida con nuestro pais, y el futuro que conlleva un nuevo presidente");
334 valores.put(Alquileres.PRECIO, "Conócenos");
335 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/quienessomos.jpg");
336 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
337
338 // Registro ejemplo #8
339 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
340 valores.put(Alquileres.NOMBRE, "Ubica tu casilla");
341 valores.put(Alquileres.UBICACION, "México");
342 valores.put(Alquileres.DESCRIPCION, "¿No sabes donde esta tu casilla? Enterate ahora!!!");
343 valores.put(Alquileres.PRECIO, "¡Qué no se te pase!");
344 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/ubicatucasilla.jpg");
345 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
346
347}
348
349@Override
350public void onUpgrade(SQLiteDatabase db, int i, int i1) {
351 try {
352 db.execSQL("DROP TABLE IF EXISTS " + Tablas.APARTAMENTO);
353 } catch (SQLiteException e) {
354 // Manejo de excepciones
355 }
356 onCreate(db);
357}
358}
359
360package com.herprogramacion.alquileres.provider;
361
362 import android.net.Uri;
363
364 import java.util.UUID;
365
366
367 public class Contrato {
368
369interface ColumnasAlquiler {
370 String ID_ALQUILER = "idAlquiler"; // Pk
371 String NOMBRE = "nombre";
372 String UBICACION = "ubicacion";
373 String DESCRIPCION = "descripcion";
374 String PRECIO = "precio";
375 String URL_IMAGEN ="urlImagen";
376}
377
378
379// Autoridad del Content Provider
380public final static String AUTORIDAD = "com.herprogramacion.alquileres";
381
382// Uri base
383public final static Uri URI_CONTENIDO_BASE = Uri.parse("content://" + AUTORIDAD);
384
385
386/**
387 * Controlador de la tabla "alquiler"
388 */
389public static class Alquileres implements ColumnasAlquiler {
390
391 public static final Uri URI_CONTENIDO =
392 URI_CONTENIDO_BASE.buildUpon().appendPath(RECURSO_ALQUILERES).build();
393
394 public final static String MIME_RECURSO =
395 "vnd.android.cursor.item/vnd." + AUTORIDAD + "/" + RECURSO_ALQUILERES;
396
397 public final static String MIME_COLECCION =
398 "vnd.android.cursor.dir/vnd." + AUTORIDAD + "/" + RECURSO_ALQUILERES;
399
400
401 /**
402 * Construye una {@link Uri} para el {@link #ID_ALQUILER} solicitado.
403 */
404 public static Uri construirUriAlquiler(String idApartamento) {
405 return URI_CONTENIDO.buildUpon().appendPath(idApartamento).build();
406 }
407
408 public static String generarIdAlquiler() {
409 return "A-" + UUID.randomUUID();
410 }
411
412 public static String obtenerIdAlquiler(Uri uri) {
413 return uri.getLastPathSegment();
414 }
415}
416
417// Recursos
418public final static String RECURSO_ALQUILERES = "alquileres";
419
420}
421
422package com.herprogramacion.alquileres.provider;
423
424import android.content.ContentProvider;
425import android.content.ContentResolver;
426import android.content.ContentValues;
427import android.content.UriMatcher;
428import android.database.Cursor;
429import android.database.sqlite.SQLiteDatabase;
430import android.net.Uri;
431import android.text.TextUtils;
432
433import com.herprogramacion.alquileres.provider.BaseDatos.Tablas;
434import com.herprogramacion.alquileres.provider.Contrato.Alquileres;
435
436
437
438public class ProviderApartamentos extends ContentProvider {
439
440// Comparador de URIs
441public static final UriMatcher uriMatcher;
442
443// Casos
444public static final int ALQUILERES = 100;
445public static final int ALQUILERES_ID = 101;
446
447static {
448 uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
449 uriMatcher.addURI(Contrato.AUTORIDAD, "alquileres", ALQUILERES);
450 uriMatcher.addURI(Contrato.AUTORIDAD, "alquileres/*", ALQUILERES_ID);
451}
452
453private BaseDatos bd;
454private ContentResolver resolver;
455
456
457@Override
458public boolean onCreate() {
459 bd = new BaseDatos(getContext());
460 resolver = getContext().getContentResolver();
461 return true;
462}
463
464@Override
465public String getType(Uri uri) {
466 switch (uriMatcher.match(uri)) {
467 case ALQUILERES:
468 return Alquileres.MIME_COLECCION;
469 case ALQUILERES_ID:
470 return Alquileres.MIME_RECURSO;
471 default:
472 throw new IllegalArgumentException("Tipo desconocido: " + uri);
473 }
474}
475
476@Override
477public Cursor query(Uri uri, String[] projection, String selection,
478 String[] selectionArgs, String sortOrder) {
479 // Obtener base de datos
480 SQLiteDatabase db = bd.getWritableDatabase();
481 // Comparar Uri
482 int match = uriMatcher.match(uri);
483
484 Cursor c;
485
486 switch (match) {
487 case ALQUILERES:
488 // Consultando todos los registros
489 c = db.query(Tablas.APARTAMENTO, projection,
490 selection, selectionArgs,
491 null, null, sortOrder);
492 c.setNotificationUri(resolver, Alquileres.URI_CONTENIDO);
493 break;
494 case ALQUILERES_ID:
495 // Consultando un solo registro basado en el Id del Uri
496 String idApartamento = Alquileres.obtenerIdAlquiler(uri);
497 c = db.query(Tablas.APARTAMENTO, projection,
498 Alquileres.ID_ALQUILER + "=" + "'" + idApartamento + "'"
499 + (!TextUtils.isEmpty(selection) ?
500 " AND (" + selection + ')' : ""),
501 selectionArgs, null, null, sortOrder);
502 c.setNotificationUri(resolver, uri);
503 break;
504 default:
505 throw new IllegalArgumentException("URI no soportada: " + uri);
506 }
507 return c;
508}
509
510@Override
511public int delete(Uri uri, String selection, String[] selectionArgs) {
512 return 0;
513}
514
515@Override
516public Uri insert(Uri uri, ContentValues values) {
517 return null;
518}
519
520@Override
521public int update(Uri uri, ContentValues values, String selection,
522 String[] selectionArgs) {
523 return 0;
524}
525}