I'm looking for the Sqlite database records and displaying in a Spinner, however the Spinner is displaying all records in the table, and I need to display only the records of a particular column.
I tried changing the query:
From:
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
To:
String selectQuery = "SELECT modelo FROM " + TABLE_LABELS;
But there was an error in the cursor.
Erro : Failed to read row 0, column 1 from a CursorWindow which has 12 rows, 1 columns.
java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Below is code:
package com.example.d2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "Medidores";
private static final String TABLE_LABELS = "labels";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_MODELO = "modelo";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_MODELO + " TEXT)"; // removi o modelo e seu tipo
db.execSQL(CREATE_CATEGORIES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
onCreate(db);
}
public void insertLabel(String nome,String modelo) { // alterei de void para long
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME , nome);
values.put(KEY_MODELO, modelo);
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public List<String> BuscaModelos() {
List<String> modelos = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
modelos.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return modelos;
}
}