2

Adicionei uma coluna na tabela Users, invited é um inteiro. Preciso fazer um select na tabela filtrando este campo, e me aparece o seguinte erro:

android.database.sqlite.SQLiteException: no such column: invited (code 1): , while compiling: SELECT * FROM users WHERE invited = '0' OR invited = null

Segue os códigos abaixo:

public ArrayList<UserCommunity> getUsersToInvite() {
    ArrayList<UserCommunity> users = new ArrayList<>();

    // 1. build the query
    String query = "SELECT * FROM " + TABLE_USERS +
            "  WHERE invited = '0' OR invited = null";

    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. go over each row, build book and add it to list
    UserCommunity user = null;
    if (cursor.moveToFirst()) {
        do {
            user = new UserCommunity();
            user.id = Integer.parseInt(cursor.getString(0));
            user.name = cursor.getString(1);
            user.email = cursor.getString(2);
            //user.distance = Integer.parseInt(cursor.getString(9));

            // Add book to books
            users.add(user);
        } while (cursor.moveToNext());
    }

    Log.d("getUsersNearCoordinat()", users.toString());

    // return books
    return users;
}

View:

    public InvitePresenter(InviteView inviteView){

        inflater = (LayoutInflater)inviteView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        serviceDB = new UsersMySQLiteHelper(AppController.getAppContext());

        RequestManager.Users(new FutureCallback<JsonObject>() {
            @Override
            public void onCompleted(Exception e, JsonObject result) {
                SessionManager sessionManager = new SessionManager();
                if (!sessionManager.getInvitedUser()) {
                    usersList = new Gson().fromJson(result.get("data"), new TypeToken<ArrayList<UserCommunity>>() {
                    }.getType());
                    sessionManager.setInvitedUser(true);
                }else{
                    usersList = serviceDB.getUsersToInvite();
                }
                notifyDataSetChanged();
            }
        });
        this.inviteView = inviteView;
}

Criação do banco:

@Override public void onCreate(SQLiteDatabase db) {

String CREATE_USERS_TABLE = "CREATE TABLE if not exists users ( " +
        "id INTEGER PRIMARY KEY, " +
        "name TEXT, "+
        "email TEXT, "+
        "company TEXT, "+
        "photo_url TEXT, "+
        "departure_time TEXT, "+
        "arrival_time TEXT, "+
        "address_lat DOUBLE,"+
        "address_lng DOUBLE,"+
        "invited INTEGER)";

// create books table
db.execSQL(CREATE_USERS_TABLE);

}

1
  • 1
    Você dropou a tabela antiga? Tem que dropar antes de adicionar a coluna senão não adianta
    – Sorack
    28/11/2016 às 20:53

2 Respostas 2

3

Seu CREATE está com if not exists. Se você não deletar a tabela antiga ele nunca irá criar a coluna nova. Ou você deleta a antiga:

DROP TABLE users;

Ou você usa o seguinte comando para adicionar a coluna:

ALTER TABLE users ADD COLUMN invited INTEGER;
1
  • obrigado pela resposta, acabei resolvendo alterando a constante DATA_BASE_VERSION, utilizada no método onUpgrade
    – Henrique
    29/11/2016 às 12:14
1

Resolvi a questão alterando a constante

private static final int DATABASE_VERSION,

implementando o método:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older books table if existed
    db.execSQL("DROP TABLE IF EXISTS users");

    // create fresh books table
    this.onCreate(db);
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .