studio programacion móviles libro desarrollo curso aplicaciones android database sqlite android-layout android-cursoradapter

android - programacion - Adaptador de cursor y ejemplo sqlite



programacion android pdf 2018 (3)

Hola, estoy buscando un código de muestra en el que se usa el adaptador de cursor con sqlite.


Ejemplo realmente simple.

Aquí hay un ejemplo muy simple, pero muy efectivo. Una vez que tenga los elementos básicos abajo, puede construir fácilmente desde allí.

Hay dos partes principales para usar un Adaptador de Cursor con SQLite:

  1. Crea un Cursor apropiado desde la Base de Datos.

  2. Cree un Adaptador de Cursor personalizado que tome los datos del Cursor de la base de datos y los vincule con la Vista con la que pretende representar los datos.

1. Crea un Cursor apropiado desde la Base de Datos.

En tu actividad:

SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper( context, DATABASE_NAME, null, DATABASE_VERSION); SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase(); String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing '';'' Cursor cursor = sqLiteDatabase.rawQuery(query, null); ClientCursorAdapter adapter = new ClientCursorAdapter( this, R.layout.clients_listview_row, cursor, 0 ); this.setListAdapter(adapter);

2. Crea un adaptador de cursor personalizado.

Nota: Al extender desde ResourceCursorAdapter supone que usa XML para crear sus vistas.

public class ClientCursorAdapter extends ResourceCursorAdapter { public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) { super(context, layout, cursor, flags); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView name = (TextView) view.findViewById(R.id.name); name.setText(cursor.getString(cursor.getColumnIndex("name"))); TextView phone = (TextView) view.findViewById(R.id.phone); phone.setText(cursor.getString(cursor.getColumnIndex("phone"))); } }


Ejemplo de CursorAdapter con Sqlite

... DatabaseHelper helper = new DatabaseHelper(this); aListView = (ListView) findViewById(R.id.aListView); Cursor c = helper.getAllContacts(); CustomAdapter adapter = new CustomAdapter(this, c); aListView.setAdapter(adapter); ... class CustomAdapter extends CursorAdapter { // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :) public CustomAdapter(Context context, Cursor c) { super(context, c); } public void bindView(View view, Context context, Cursor cursor) { String id = cursor.getString(0); String name = cursor.getString(1); // Get all the values // Use it however you need to TextView textView = (TextView) view; textView.setText(name); } public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate your view here. TextView view = new TextView(context); return view; } } private final class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "db_name"; private static final int DATABASE_VERSION = 1; private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_TIMELINE); db.execSQL("INSERT INTO ddd (name) VALUES (''One'')"); db.execSQL("INSERT INTO ddd (name) VALUES (''Two'')"); db.execSQL("INSERT INTO ddd (name) VALUES (''Three'')"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public Cursor getAllContacts() { String selectQuery = "SELECT * FROM table_name; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); return cursor; } }


En Android, Cómo utilizar un cursor con una consulta sin formato en sqlite:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " + "where Age > 10 LIMIT 5", null); if (c != null ) { if (c.moveToFirst()) { do { String firstName = c.getString(c.getColumnIndex("FirstName")); int age = c.getInt(c.getColumnIndex("Age")); results.add("" + firstName + ",Age: " + age); }while (c.moveToNext()); } } c.close();