Acredito que a classe ControllerClientes
não está gerando corretamente o ArrayList
, dando erro na criação do Spinner
. Falta a conexão com o banco da `DBCreate.Erro:
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
public class DBCreate extends SQLiteOpenHelper {
private static final String NOME_BANCO = "db_pv.db";
protected static final String TABELA = "clientes";
protected static final String ID = "_id";
protected static final String HANDLE = "handle";
protected static final String NOME = "nome";
private static final int VERSAO = 1;
public DBCreate(Context context) {
super(context, NOME_BANCO, null, VERSAO);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABELA + " ("
+ ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,"
+ HANDLE + " INT NOT NULL UNIQUE,"
+ NOME + " TEXT NOT NULL,"NULL"
+ ")";
db.execSQL(sql);
insereTeste(db);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABELA);
onCreate(sqLiteDatabase);
}
public void insereTeste(SQLiteDatabase db) {
db.execSQL("INSERT INTO clientes (handle, nome) VALUES (1,'Cliente 1')");
db.execSQL("INSERT INTO clientes (handle, nome) VALUES (2,'Cliente 2')");
db.execSQL("INSERT INTO clientes (handle, nome) VALUES (3,'Cliente 3')");
db.execSQL("INSERT INTO clientes (handle, nome) VALUES (4,'Cliente 4')");
}
}
public class ControllerClientes {
SQLiteDatabase sqLiteDatabase;
DBCreate banco;
public ControllerClientes(Context context){
banco = new DBCreate(context);
}
public ArrayList<String> getClientes(){
sqLiteDatabase = banco.getReadableDatabase();
ArrayList<String> clientes = new ArrayList<String>();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM clientes",null);
if(cursor != null && cursor.moveToFirst()){
do{
clientes.add(cursor.getString(cursor.getColumnIndex("_id")));
}while(cursor.moveToNext());
}
return clientes;
}
}
public class NovoRegistro extends AppCompatActivity {
Spinner spnClientes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_novo_registro);
spnClientes = findViewById(R.id.spnClientes);
spinnerClientes();
}
public void spinnerClientes() {
ControllerClientes ctClientes = new ControllerClientes(this);
ArrayList<String> clientes = ctClientes.getClientes();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, clientes);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnClientes.setAdapter(adapter);
}
}