Android obteniendo cadenas de la base de datos sqlite a autocompletetextview
Estoy trabajando en un proyecto de base de datos sqlite en android. Y es mi primer proyecto sqlite. He leído un montón de artículos y creado mi aplicación, pero hay un problema que no puedo encontrar una manera de resolverlo. Espero que puedas mostrarme un camino para mí. El problema es cuando llamo a la actividad haciendo clic en un botón, el dispositivo enciende un mensaje ("desafortunadamente, la aplicación se detuvo").
Estoy tratando de obtener cadenas de sqlite base de datos a autocompletetextview.
- ¿Cómo insertar datos en la base de datos SQLite en android?
- No puede ver datos Sqlite con adaptador simple
- ¿Cuál es la mejor estrategia de clave primaria para una aplicación móvil en línea / offline multi-cliente con base de datos SQLite y Azure SQL como almacén central?
- ¿Qué diferencia hay entre SQLite y SQL?
- Cómo guardar la ruta de recursos en SQLite
Códigos de la clase Sqlite databasehelper
package com.example.matik; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class Veritabani extends SQLiteOpenHelper { private static final String VERITABANI="KAYISGDATA.db"; private static final int SURUM=1; public static final String TABLE_TODO = "nace"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_CATEGORY = "KOD"; public static final String COLUMN_SUMMARY = "ACK"; public static final String COLUMN_DESCRIPTION = "TEH"; private static final String DB_DROP = "DROP TABLE IF EXISTS nace"; private static final String DATABASE_CREATE = "create table " + TABLE_TODO + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_CATEGORY + " text not null, " + COLUMN_SUMMARY + " text not null," + COLUMN_DESCRIPTION + " text not null" + ");"; public Veritabani(Context con, String name, CursorFactory factory, int version) { super(con, VERITABANI, null, SURUM); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(DATABASE_CREATE); db.execSQL("INSERT INTO nace (KOD,ACK,TEH) VALUES('01.11.07','Baklagillerin yetiştirilmesi','Tehlikeli')");} @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DB_DROP); onCreate(db); } }
Clases de la clase de actividad
package com.example.matik; import java.util.ArrayList; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; public class Matik extends Activity { AutoCompleteTextView auto; EditText nc; EditText th; Veritabani VB; private ArrayAdapter<String> arrayAdapter; ArrayList<String> Liste = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_matik); Liste = new ArrayList<String>(); doldur(); nc = (EditText) findViewById(R.id.editText2); th = (EditText) findViewById(R.id.editText3); auto = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1); arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item, Liste); auto.setThreshold(1); auto.setAdapter(arrayAdapter); } private void doldur() { SQLiteDatabase Db = VB.getReadableDatabase(); Cursor c = Db.rawQuery("Select ACT From nace", null); Db.isOpen(); while(c.moveToNext()){ Liste.add(c.getString(c.getColumnIndex("ACT"))); }; } }
- Utilizando un botón para exportar sqlite db a un archivo excel-readable (quizás csv)?
- Android SQLite Error "solicitando nombre de columna con nombre de tabla"
- ¿Hay alguna forma de implementar la búsqueda de texto completo (FTS) en SQlite de la plataforma Android?
- Cómo escapar caracteres especiales como 'en sqlite en android
- ¿Por qué ContentValues tiene un método put que admite booleanos?
- Cómo abrir / cerrar SQLite db en Android correctamente
- ¿Por qué un delete rawQuery necesita un moveToFirst para eliminar realmente las filas?
- Almacenamiento en caché de los datos descargados de JSON en la base de datos SQLite - ¿es una buena idea?
Utilice un SimpleCursorAdapter, como se muestra en este artículo .
_descriptionText = (AutoCompleteTextView) findViewById(R.id.description); final int[] to = new int[]{android.R.id.text1}; final String[] from = new String[]{VehicleDescriptionsTable.DESCRIPTION}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to); // This will provide the labels for the choices to be displayed in the AutoCompleteTextView adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() { @Override public CharSequence convertToString(Cursor cursor) { final int colIndex = cursor.getColumnIndexOrThrow(VehicleDescriptionsTable.DESCRIPTION); return cursor.getString(colIndex); } }); // This will run a query to find the descriptions for a given vehicle. adapter.setFilterQueryProvider(new FilterQueryProvider() { @Override public Cursor runQuery(CharSequence description) { String vehicle = getSelectedVehicle(); Cursor managedCursor = _helper.getDescriptionsFor(vehicle, description.toString()); Log.d(TAG, "Query has " + managedCursor.getCount() + " rows of description for " + vehicle); return managedCursor; } }); _descriptionText.setAdapter(adapter);
Desde aquí, sólo tiene que agregar una función para devolver un cursor a su base de datos y agregar el adaptador a su AutoTextCompleteTextView. Usted tendrá que obtener _id de su consulta de diario, de hecho, usted podría considerar la posibilidad de obtener toda la fila ( SELECT * FROM table
). Si no tiene una columna _id, pruebe SELECT data, rowid AS _id FROM table
.
- Uso de Espresso 2.0 + Roboeléctrico en un proyecto de Android
- Desactivar la notificación de nivel de seguridad de sonido en android