This is my first posting on the forum, I hope I am not inflicting any rules. I'm starting in Android programming, so I'm trying to develop a CRUD . So far I've done the registration and listing, but the latter insists on making the code even seemingly correct ... (Consistent with instructions from sites like DevMidia). I would like help finding what I am doing wrong, thank you in advance! :)
BANK CLASS CODE:
public class Banco extends SQLiteOpenHelper{
static final String NOME_BANCO = "banco.db";
static final String TABELA = "pacientes";
static final String ID = "id";
static final String PACIENTE = "paciente";
static final String LEITO = "leito";
static final int VERSAO = 1;
public Banco(Context context) { // local do banco
super(context,NOME_BANCO, null, VERSAO);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("" +
"create table pacientes(id integer primary key autoincrement, paciente text not null" +
", leito text not null);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS pacientes");
onCreate(db);
}
CRUD CODE
public class CRUD {
SQLiteDatabase db;
Banco banco;
public CRUD (Context context){
banco = new Banco(context);
}
public String insert(String paciente, String leito){
//responsável por inserir
ContentValues valores;
long resultado;
db=banco.getWritableDatabase();
//gravar no banco
valores = new ContentValues();
valores.put(Banco.PACIENTE, paciente);
valores.put(Banco.LEITO, leito);
resultado = db.insert(Banco.TABELA, null, valores);
db.close();
if (resultado ==-1)
return "Erro ao inserir registro";
else
return "Cadastrado :)";
}
public Cursor carregaDados(){
Cursor cursor;
String campos[] = {banco.PACIENTE,banco.LEITO,banco.ID};
db = banco.getReadableDatabase();
cursor = db.query(banco.TABELA, campos, null, null, null, null, null, null);
if(cursor!=null)
{
cursor.moveToFirst();
}
db.close();
return cursor;
}
DATA LISTING CODE
public class Consulta extends AppCompatActivity {
ListView lista;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consulta);
CRUD crud = new CRUD (getBaseContext());
Cursor cursor = crud.carregaDados();
String [] nomecampos = new String [] {Banco.PACIENTE, Banco.LEITO,Banco.ID};
int [] idViews = new int [] {R.id.idPaciente, R.id.idLeito,R.id.idId};
SimpleCursorAdapter adaptador = new SimpleCursorAdapter(getBaseContext(),
R.layout.formatador, cursor, nomecampos,idViews,0);
lista = (ListView)findViewById(R.id.listinha);
lista.setAdapter(adaptador);
}
}