Search code examples
javaandroidandroid-sqlite

multiple tables in android


I want to use two tables in my SQLite database but when I try to read the second table my app crashes.

I have a table for the items in a storage and another table for the employees of the storage.

Here is my database class:

public class Database extends SQLiteOpenHelper {

protected static final String DATABASE_NAME = "Storage";
protected static final String KEY_ID = "id";
protected static final String KEY_DESCRIPTION = "description";
protected static final String KEY_CATEGORY = "category";
protected static final String KEY_ORIGIN = "origin";
protected static final String KEY_DATE = "date";
protected static final String KEY_BRAND = "brand";
protected static final String TAB_NAME = "items";

protected static final String KEY_ID2 = "id2";
protected static final String KEY_SURNAME = "surname";
protected static final String KEY_NAME = "name";
protected static final String KEY_USERNAME = "username";
protected static final String KEY_PASSWORD = "password";
protected static final String TAB_NAME2 = "employees";
protected static final int VERSION = 1;

public Database(Context context) {
    super(context, DATABASE_NAME, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_ITEMS_TABLE = "CREATE TABLE " + TAB_NAME + " ("
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + KEY_DESCRIPTION + " TEXT, "
            + KEY_CATEGORY + " TEXT, "
            + KEY_ORIGIN + " TEXT, "
            + KEY_DATE + " TEXT, "
            + KEY_BRAND + " TEXT)";

    String CREATE_DIPENDENTI_TABLE = "CREATE TABLE " + TAB_NAME2 + " ("
            + KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + KEY_SURNAME + " TEXT, "
            + KEY_NAME + " TEXT, "
            + KEY_USERNAME + " TEXT, "
            + KEY_PASSWORD + " TEXT)";

    db.execSQL(CREATE_ITEMS_TABLE);
    db.execSQL(CREATE_DIPENDENTI_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME2);
    this.onCreate(db);
}

public void Add(String des, String cat, String pro, String data, String brand) {
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_DESCRIPTION, des);
    contentValues.put(KEY_CATEGORY, cat);
    contentValues.put(KEY_ORIGIN, pro);
    contentValues.put(KEY_DATE, data);
    contentValues.put(KEY_BRAND, brand);

    sqLiteDatabase.insert(TAB_NAME,null, contentValues);

    sqLiteDatabase.close();
}

public void Add(String cog, String nom, String user, String pass) {
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_SURNAME, cog);
    contentValues.put(KEY_NAME, nom);
    contentValues.put(KEY_USERNAME, user);
    contentValues.put(KEY_PASSWORD, pass);

    sqLiteDatabase.insert(TAB_NAME2,null, contentValues);

    sqLiteDatabase.close();
}

public Cursor getInfo() {
    SQLiteDatabase sqLiteDatabase = getReadableDatabase();
    String query = "SELECT * FROM " + TAB_NAME + ";";
    return sqLiteDatabase.rawQuery(query, null);
}

public ArrayList getInfoDip() {
    SQLiteDatabase sqLiteDatabase = getReadableDatabase();
    ArrayList<String> al=new ArrayList<>();

    Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM " +TAB_NAME2, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()){
        al.add(cursor.getString(cursor.getColumnIndex("surname")));
        al.add(cursor.getString(cursor.getColumnIndex("name")));
        al.add(cursor.getString(cursor.getColumnIndex("username")));
        al.add(cursor.getString(cursor.getColumnIndex("password")));
        cursor.moveToNext();
    }
    return al;
}

public void Modify(int cod,String des, String cat, String pro, String dat, String bran){
    SQLiteDatabase db = this.getWritableDatabase();

    if(!des.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME+" SET description = "+"'"+des+"' "+ "WHERE id = "+"'"+cod+"'");
    if(!cat.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME+" SET categoria = "+"'"+cat+"' "+ "WHERE id = "+"'"+cod+"'");
    if(!pro.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME+" SET origin = "+"'"+pro+"' "+ "WHERE id = "+"'"+cod+"'");
    if(!dat.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME+" SET date = "+"'"+dat+"' "+ "WHERE id = "+"'"+cod+"'");
    if(!bran.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME+" SET brand = "+"'"+bran+"' "+ "WHERE id = "+"'"+cod+"'");
}

public void Modify(int cod, String cog, String nom, String user, String pass){
    SQLiteDatabase db = this.getWritableDatabase();

    if(!cog.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME2+" SET surname = "+"'"+cog+"' "+ "WHERE id2 = "+"'"+cod+"'");
    if(!nom.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME2+" SET name = "+"'"+nom+"' "+ "WHERE id2 = "+"'"+cod+"'");
    if(!user.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME2+" SET username = "+"'"+user+"' "+ "WHERE id2 = "+"'"+cod+"'");
    if(!pass.isEmpty())
        db.execSQL("UPDATE "+TAB_NAME2+" SET password = "+"'"+pass+"' "+ "WHERE id2 = "+"'"+cod+"'");
}

public void Delete(int cod){
    SQLiteDatabase db = this.getWritableDatabase();

    db.execSQL("DELETE FROM "+TAB_NAME+" WHERE id= "+"'"+cod+"'");
}

public void DeleteDip(int cod){
    SQLiteDatabase db = this.getWritableDatabase();

    db.execSQL("DELETE FROM "+TAB_NAME2+" WHERE id2= "+"'"+cod+"'");
}

public Cursor Search(int cod){
    SQLiteDatabase sqLiteDatabase = getReadableDatabase();
    String query = "SELECT * FROM " + TAB_NAME + " WHERE id = "+"'"+cod+"';";
    return sqLiteDatabase.rawQuery(query, null);
}

public Cursor Search(String des){
    SQLiteDatabase sqLiteDatabase = getReadableDatabase();
    String query = "SELECT * FROM " + TAB_NAME + " WHERE description = "+"'"+des+"';";
    return sqLiteDatabase.rawQuery(query, null);
}

public void DeleteAll() {
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delete from " + TAB_NAME);
}
}

and here is the activity where I try to get the ArrayList with the data:

private Database db= new Database(this);
private ArrayList<String> al=new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

    db.Add("admin","admin","admin","admin");
    al.addAll(db.getInfoDip());

But when I try to put the data in the ArrayList the app crashes. Can anyone help me out?


Solution

  • Well so far, how I learned that the best practice for formating queries is to use String.format function. Here your example:

    String query = "SELECT * FROM " + TAB_NAME + ";";
    

    Best practice:

    String query = String.format("SELECT * FROM %s", TAB_NAME);
    

    So let's get to the getInfoDip method, you should try this:

       public List<ContentValues> getInfoDip() {
            SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
            String query = String.format("SELECT * FROM %s", TAB_NAME2);
            Cursor res = db.rawQuery(query, null);
            res.moveToFirst();
            List<ContentValues> list = new ArrayList<>(res.getCount());
            while (!res.isAfterLast()){
                String surname = res.getString(res.getColumnIndex(KEY_SURNAME));
                String name = res.getString(res.getColumnIndex(KEY_NAME));
                String username = res.getString(res.getColumnIndex(KEY_USERNAME));
                String password = res.getString(res.getColumnIndex(KEY_PASSWORD));
                list.add(new ContentValues(surname, name, username, password));
                res.moveToNext();
            }
            return list;
        }
    

    Here is my whole SQLite test program, check out maybe it helps you:

    package com.example.vezba09;
    
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    import androidx.annotation.Nullable;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Database extends SQLiteOpenHelper {
    
        private static final String DATABASE_FILE_NAME = "contact_database";
    
        public Database(@Nullable Context context) {
            super(context, DATABASE_FILE_NAME, null, 1);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            String query = String.format(
                    "CREATE TABLE IF NOT EXISTS %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT)",
                    ContactModel.TABLE_NAME,
                    ContactModel.COLUMN_CONTACT_ID,
                    ContactModel.COLUMN_CONTACT_NAME,
                    ContactModel.COLUMN_CONTACT_EMAIL,
                    ContactModel.COLUMN_CONTACT_PHONE
            );
            db.execSQL(query);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int i, int i1) {
            String query = String.format("DROP TABLE IF EXISTS %s", ContactModel.TABLE_NAME);
            db.execSQL(query);
            onCreate(db);
        }
    
        //Dodavanje kontakta
        public void addContact(String name, String email, String phone) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
    
            cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
            cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
            cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
    
            db.insert(ContactModel.TABLE_NAME, null, cv);
        }
    
        //Izmena
        public void editContact(int contactId, String name, String email, String phone) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
    
            cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
            cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
            cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
    
            db.update(ContactModel.TABLE_NAME,
                    cv,
                    ContactModel.COLUMN_CONTACT_ID + "=?",
                    new String[]{String.valueOf(contactId)});
        }
    
        public int deleteContact(int contactId) {
            SQLiteDatabase db = this.getWritableDatabase();
            return db.delete(ContactModel.TABLE_NAME,
                    ContactModel.COLUMN_CONTACT_ID + "=?",
                    new String[]{String.valueOf(contactId)});
        }
    
        public ContactModel getContactById(int contactId) {
            SQLiteDatabase db = this.getReadableDatabase();
            String query = String.format("SELECT * FROM %s WHERE %s = ?",
                    ContactModel.TABLE_NAME,
                    ContactModel.COLUMN_CONTACT_ID);
    
            Cursor res = db.rawQuery(query, new String[] {String.valueOf(contactId)});
            if(res.moveToFirst()) {
                String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
                String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
                String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
                return new ContactModel(contactId, name, email, phone);
            }
            else {
                return null;
            }
        }
    
        public List<ContactModel> getAllContacts() {
            SQLiteDatabase db = this.getReadableDatabase();
            String query = String.format("SELECT * FROM %s", ContactModel.TABLE_NAME);
            Cursor res = db.rawQuery(query, null);
            res.moveToFirst();
            List<ContactModel> list = new ArrayList<>(res.getCount());
            while(!res.isAfterLast()) {
                int contactId = res.getInt(res.getColumnIndex(ContactModel.COLUMN_CONTACT_ID));
                String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
                String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
                String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
    
                list.add(new ContactModel(contactId, name, email, phone));
                res.moveToNext();
            }
            return list;
        }
    }
    

    Try this and feel free to ask more questions :)

    Best regards, Sanady