Problems with reading database [Sqlite]

Asked

Viewed 337 times

0

Day number 3. The app insists on "crashing" its startup and the Frustration is strong at the moment. The problem, I believe, is found in the getFromDb() method, more specifically in the line where I call the db.getReadableDatabase() method since the app runs NORMALLY without the stretch between " /? */ " highlighted in the code below.

Follow the problematic code.

    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;

    public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "productsManager";
    private static final String TABLE_PRODUCTS = "products";

    private static final String _PRODUCT = "product";

    public DatabaseHandler(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE products (id INTEGER PRIMARY KEY AUTO_INCREMENT, product TEXT )";
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);

        onCreate(db);
    }

    public void addToDb(String product){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues valor = new ContentValues();
        valor.put(_PRODUCT, product);

        db.insert(TABLE_PRODUCTS, null, valor);
        db.close();
    }

    public ArrayList<String> getFromDb(){
        ArrayList<String> stringList = new ArrayList<String>();
/*        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_PRODUCTS, null, null, null, null, null, null);

        if(cursor.getCount() > 0){
            cursor.moveToFirst();
            do{
                stringList.add(cursor.getString(1));
            }while(cursor.moveToNext());
        }

        cursor.close();*/
        return  stringList;
    }
}

Can anyone please tell me what’s wrong? If needed I can add more information later.

  • Ask the question the error log.

  • Great Ramaral, by the way! I read the error log and the problem was that the getFromDb() method was being called for an unspecified Arraylist object in main_activity... You won.

2 answers

0


Yeah, it really lacks information, but from what I could see in the code posted, you should have done something like:

   public ArrayList<String> getFromDb(){
    ArrayList<String> stringList = new ArrayList<String>();
    SQLiteDatabase db = this.getReadableDatabase();
    String sqlCmd = "SELECT * FROM "+TABLE_PRODUCTS+";";
    // se voce tiver alguma clausula WHERE, acrecenta a mesma na linha acima
    Cursor cursor = db.query(sqlCmd);

    if(cursor.getCount() > 0){
        cursor.moveToFirst();
        do{
          stringList.add(cursor.getString(cursor.getColumnIndex("codigo")));
          stringList.add(cursor.getString(cursor.getColumnIndex("descricao")));
          stringList.add(cursor.getString(cursor.getColumnIndex("categoria")));
          stringList.add(cursor.getString(cursor.getColumnIndex("preco")));
            // e quantos campos mais voce quiser, lembrando que:
            // ...(getColumnIndex('campo') se refere ao indice de uma
            // coluna da tabela referenciada pelo seu nome
        }while(cursor.moveToNext());
    }
    cursor.close();
    return  stringList;
}

If there’s a problem, let me know
in the case of data manipulation in a db, whatever it is, the good practice insists on creating constant variables with the names of the tables, it is easier for you to manipulate your code, since being a constant variable and the same being referenced in several points of the code, If you change the constant Voce consequently will also change its references.

  • Thanks for the time and tips. As for its function, it presents the same problem as mine, the this.getReadableDatabase method that causes the app to crash before it can execute the other instructions...

  • this problem must be because Voce needs to instantiate the class "Databasehandler" first in Activity that calls it, something like List<String> dados = new ArrayList<String>(); DabaseHandler meudb = new DatabaseHandler; after that, as the getFromDb() method returns an arraylist, Voce calls it using dados = getFromDb(); tries there and returns if this is it for me to edit the answer.

  • That was exactly the problem. The error log itself reported and I didn’t know how to read it.

  • good that has solved man, Voce can also use db.rawQuery(sql, null);as in friend tip @Felipe Xavier that works too

0

Already tried using rawQuery instead of query?

SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM "+TABLE_PRODUCTS;
Cursor cursor = db.rawQuery(query, null);
  • yeah, problem can’t be that, because the program can’t get past this.getReadableDatabase instruction()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.