· 9 years ago · Nov 19, 2016, 09:44 AM
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().into(holder.viewFoto);
202
203
204}
205
206@Override
207public int getItemCount() {
208 if (items != null)
209 return items.getCount();
210 return 0;
211}
212
213public void swapCursor(Cursor nuevoCursor) {
214 if (nuevoCursor != null) {
215 items = nuevoCursor;
216 notifyDataSetChanged();
217 }
218}
219
220public Cursor getCursor() {
221 return items;
222}
223
224interface ConsultaAlquileres {
225 int ID_ALQUILER = 1;
226 int NOMBRE = 2;
227 int UBICACION = 3;
228 int DESCRIPCION = 4;
229 int PRECIO = 5;
230 int URL = 6;
231}
232}
233
234package com.herprogramacion.alquileres.provider;
235
236import android.content.ContentValues;
237import android.content.Context;
238import android.database.sqlite.SQLiteDatabase;
239import android.database.sqlite.SQLiteException;
240import android.database.sqlite.SQLiteOpenHelper;
241import android.provider.BaseColumns;
242
243import com.herprogramacion.alquileres.provider.Contrato.Alquileres;
244
245
246public class BaseDatos extends SQLiteOpenHelper {
247
248static final int VERSION = 1;
249
250static final String NOMBRE_BD = "alquileres.db";
251
252
253interface Tablas {
254 String APARTAMENTO = "alquiler";
255}
256
257public BaseDatos(Context context) {
258 super(context, NOMBRE_BD, null, VERSION);
259}
260
261@Override
262public void onCreate(SQLiteDatabase db) {
263 db.execSQL(
264 "CREATE TABLE " + Tablas.APARTAMENTO + "("
265 + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
266 + Alquileres.ID_ALQUILER + " TEXT UNIQUE NOT NULL,"
267 + Alquileres.NOMBRE + " TEXT NOT NULL,"
268 + Alquileres.UBICACION + " TEXT NOT NULL,"
269 + Alquileres.DESCRIPCION + " TEXT NOT NULL,"
270 + Alquileres.PRECIO + " REAL NOT NULL,"
271 + Alquileres.URL_IMAGEN + " TEXT NOT NULL)");
272
273 // Registro ejemplo #1
274 ContentValues valores = new ContentValues();
275 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
276 valores.put(Alquileres.NOMBRE, "Mis representantes");
277 valores.put(Alquileres.UBICACION, "México");
278 valores.put(Alquileres.DESCRIPCION, "Conoce a los posibles candidatos a la presidencia de México 2018");
279 valores.put(Alquileres.PRECIO, "¿Quiénes son?");
280 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/misrepresentantes.jpg");
281 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
282
283 // Registro ejemplo #2
284 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
285 valores.put(Alquileres.NOMBRE, "Elecciones");
286 valores.put(Alquileres.UBICACION, "México");
287 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...");
288 valores.put(Alquileres.PRECIO, "¡Enterate!");
289 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/elecciones.jpg");
290 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
291
292 // Registro ejemplo #3
293 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
294 valores.put(Alquileres.NOMBRE, "Reformas y leyes");
295 valores.put(Alquileres.UBICACION, "México");
296 valores.put(Alquileres.DESCRIPCION, "Enterate de las reformas federales vigentes asi como las proximas a tratar");
297 valores.put(Alquileres.PRECIO, "¿En que nos afectan?");
298 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/reformasyleyes.jpg");
299 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
300
301 // Registro ejemplo #4
302 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
303 valores.put(Alquileres.NOMBRE, "Noticias");
304 valores.put(Alquileres.UBICACION, "México");
305 valores.put(Alquileres.DESCRIPCION, "Noticias en tiempo real y anuncios clasificados de todo lo relacionado a las elecciones 2018");
306 valores.put(Alquileres.PRECIO, "Mantente enterado");
307 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/noticias.jpg");
308 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
309
310 // Registro ejemplo #5
311 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
312 valores.put(Alquileres.NOMBRE, "MovilÃzate");
313 valores.put(Alquileres.UBICACION, "México");
314 valores.put(Alquileres.DESCRIPCION, "Enterate que puedes hacer por tu pais, movilizate!!!");
315 valores.put(Alquileres.PRECIO, "¿Por qué?");
316 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/movilizate.jpg");
317 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
318
319 // Registro ejemplo #6
320 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
321 valores.put(Alquileres.NOMBRE, "¿Porqué participar?");
322 valores.put(Alquileres.UBICACION, "México");
323 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");
324 valores.put(Alquileres.PRECIO, "¡Animate!");
325 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/porqueparticipar.jpg");
326 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
327
328 // Registro ejemplo #7
329 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
330 valores.put(Alquileres.NOMBRE, "¿Quiénes somos?");
331 valores.put(Alquileres.UBICACION, "México");
332 valores.put(Alquileres.DESCRIPCION, "Somos una asociacion civil comprometida con nuestro pais, y el futuro que conlleva un nuevo presidente");
333 valores.put(Alquileres.PRECIO, "Conócenos");
334 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/quienessomos.jpg");
335 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
336
337 // Registro ejemplo #8
338 valores.put(Alquileres.ID_ALQUILER, Alquileres.generarIdAlquiler());
339 valores.put(Alquileres.NOMBRE, "Ubica tu casilla");
340 valores.put(Alquileres.UBICACION, "México");
341 valores.put(Alquileres.DESCRIPCION, "¿No sabes donde esta tu casilla? Enterate ahora!!!");
342 valores.put(Alquileres.PRECIO, "¡Qué no se te pase!");
343 valores.put(Alquileres.URL_IMAGEN, "http://parkwebstudio.com/images/ubicatucasilla.jpg");
344 db.insertOrThrow(Tablas.APARTAMENTO, null, valores);
345
346}
347
348@Override
349public void onUpgrade(SQLiteDatabase db, int i, int i1) {
350 try {
351 db.execSQL("DROP TABLE IF EXISTS " + Tablas.APARTAMENTO);
352 } catch (SQLiteException e) {
353 // Manejo de excepciones
354 }
355 onCreate(db);
356}
357}
358
359package com.herprogramacion.alquileres.provider;
360
361 import android.net.Uri;
362
363 import java.util.UUID;
364
365
366 public class Contrato {
367
368interface ColumnasAlquiler {
369 String ID_ALQUILER = "idAlquiler"; // Pk
370 String NOMBRE = "nombre";
371 String UBICACION = "ubicacion";
372 String DESCRIPCION = "descripcion";
373 String PRECIO = "precio";
374 String URL_IMAGEN ="urlImagen";
375}
376
377
378// Autoridad del Content Provider
379public final static String AUTORIDAD = "com.herprogramacion.alquileres";
380
381// Uri base
382public final static Uri URI_CONTENIDO_BASE = Uri.parse("content://" + AUTORIDAD);
383
384
385/**
386 * Controlador de la tabla "alquiler"
387 */
388public static class Alquileres implements ColumnasAlquiler {
389
390 public static final Uri URI_CONTENIDO =
391 URI_CONTENIDO_BASE.buildUpon().appendPath(RECURSO_ALQUILERES).build();
392
393 public final static String MIME_RECURSO =
394 "vnd.android.cursor.item/vnd." + AUTORIDAD + "/" + RECURSO_ALQUILERES;
395
396 public final static String MIME_COLECCION =
397 "vnd.android.cursor.dir/vnd." + AUTORIDAD + "/" + RECURSO_ALQUILERES;
398
399
400 /**
401 * Construye una {@link Uri} para el {@link #ID_ALQUILER} solicitado.
402 */
403 public static Uri construirUriAlquiler(String idApartamento) {
404 return URI_CONTENIDO.buildUpon().appendPath(idApartamento).build();
405 }
406
407 public static String generarIdAlquiler() {
408 return "A-" + UUID.randomUUID();
409 }
410
411 public static String obtenerIdAlquiler(Uri uri) {
412 return uri.getLastPathSegment();
413 }
414}
415
416// Recursos
417public final static String RECURSO_ALQUILERES = "alquileres";
418
419}
420
421package com.herprogramacion.alquileres.provider;
422
423import android.content.ContentProvider;
424import android.content.ContentResolver;
425import android.content.ContentValues;
426import android.content.UriMatcher;
427import android.database.Cursor;
428import android.database.sqlite.SQLiteDatabase;
429import android.net.Uri;
430import android.text.TextUtils;
431
432import com.herprogramacion.alquileres.provider.BaseDatos.Tablas;
433import com.herprogramacion.alquileres.provider.Contrato.Alquileres;
434
435
436
437public class ProviderApartamentos extends ContentProvider {
438
439// Comparador de URIs
440public static final UriMatcher uriMatcher;
441
442// Casos
443public static final int ALQUILERES = 100;
444public static final int ALQUILERES_ID = 101;
445
446static {
447 uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
448 uriMatcher.addURI(Contrato.AUTORIDAD, "alquileres", ALQUILERES);
449 uriMatcher.addURI(Contrato.AUTORIDAD, "alquileres/*", ALQUILERES_ID);
450}
451
452private BaseDatos bd;
453private ContentResolver resolver;
454
455
456@Override
457public boolean onCreate() {
458 bd = new BaseDatos(getContext());
459 resolver = getContext().getContentResolver();
460 return true;
461}
462
463@Override
464public String getType(Uri uri) {
465 switch (uriMatcher.match(uri)) {
466 case ALQUILERES:
467 return Alquileres.MIME_COLECCION;
468 case ALQUILERES_ID:
469 return Alquileres.MIME_RECURSO;
470 default:
471 throw new IllegalArgumentException("Tipo desconocido: " + uri);
472 }
473}
474
475@Override
476public Cursor query(Uri uri, String[] projection, String selection,
477 String[] selectionArgs, String sortOrder) {
478 // Obtener base de datos
479 SQLiteDatabase db = bd.getWritableDatabase();
480 // Comparar Uri
481 int match = uriMatcher.match(uri);
482
483 Cursor c;
484
485 switch (match) {
486 case ALQUILERES:
487 // Consultando todos los registros
488 c = db.query(Tablas.APARTAMENTO, projection,
489 selection, selectionArgs,
490 null, null, sortOrder);
491 c.setNotificationUri(resolver, Alquileres.URI_CONTENIDO);
492 break;
493 case ALQUILERES_ID:
494 // Consultando un solo registro basado en el Id del Uri
495 String idApartamento = Alquileres.obtenerIdAlquiler(uri);
496 c = db.query(Tablas.APARTAMENTO, projection,
497 Alquileres.ID_ALQUILER + "=" + "'" + idApartamento + "'"
498 + (!TextUtils.isEmpty(selection) ?
499 " AND (" + selection + ')' : ""),
500 selectionArgs, null, null, sortOrder);
501 c.setNotificationUri(resolver, uri);
502 break;
503 default:
504 throw new IllegalArgumentException("URI no soportada: " + uri);
505 }
506 return c;
507}
508
509@Override
510public int delete(Uri uri, String selection, String[] selectionArgs) {
511 return 0;
512}
513
514@Override
515public Uri insert(Uri uri, ContentValues values) {
516 return null;
517}
518
519@Override
520public int update(Uri uri, ContentValues values, String selection,
521 String[] selectionArgs) {
522 return 0;
523}
524}