Search code examples
androidsqlitecursor

Android - Cursor not properly working


I have an app that inserts data into a database with 2 tables (project and alvara) The insertion method for the second table depends on what type the first table gets. (1 or 2) for resumed idea.

This is a method that I made for looking into the second table with cursor. If it finds, it sets in setters from alvara_db class. And later on, I use getters to show info on textviews in another activity. The issue is that it's not setting info at all. Is anything wrong in my Cursor?

Thanks in advance!

public ArrayList<alvara_db> getAlvaras(){
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<alvara_db> projects = new ArrayList<>();
    String[] project = new String[]{String.valueOf(tipoprojetoid)};

    Cursor cur = db.rawQuery("SELECT placa, proj_exec, resp_tec, rtnum, parecer FROM alvara WHERE projetoid = ?", project);
    cur.moveToFirst();

    alvara_db alvaras = new alvara_db();
    alvaras.setPlaca(cur.getInt(cur.getColumnIndex("placa")));
    alvaras.setProj_exec(cur.getInt(cur.getColumnIndex("proj_exec")));
    alvaras.setResp_tec(cur.getString(cur.getColumnIndex("resp_tec")));
    alvaras.setRtnum(cur.getInt(cur.getColumnIndex("rtnum")));
    alvaras.setParecer(cur.getString(cur.getColumnIndex("parecer")));
    projects.add(alvaras);

    return projects;
}

Fragment where I call getAlvaras method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detalhes_projeto_alvara);
    db.getAlvaras();

    placa = alvaras.getPlaca();
    resp_tec = alvaras.getResp_tec();
    proj_exec = alvaras.getProj_exec();
    rtnum = alvaras.getRtnum();
}

Solution

  • You are not using the returned value from db.getAlvaras().

    Instead the alvaras variable in your second snippet is something that is likely not initialized - the code you posted does not show that exactly.

    (In addition, you might want to check the return value of moveToFirst() in case the query matches no rows, and add a do-while loop to retrieve more than one row.)