Error saving Sqlite Data (in such table)

Asked

Viewed 2,553 times

2

Databasehelper class:

public class DatabaseHelper extends SQLiteOpenHelper {
private static final String BANCO_DADOS = "MakeRequestApp";
private static int VERSAO = 1;

public DatabaseHelper(Context context){
    super(context, BANCO_DADOS, null, VERSAO);
}

@Override
public void onCreate(SQLiteDatabase db){
    db.execSQL("CREATE TABLE mesa (_id INTEGER PRIMARY KEY, descricao TEXT)");
    db.execSQL("CREATE TABLE pedido(_id INTEGER PRIMARY KEY, numero_mesa_id INTEGER, " +
            "FOREIGN KEY(numero_mesa_id) REFERENCES mesa(_id))");
    db.execSQL("CREATE TABLE itens_pedido (_id INTEGER PRIMARY KEY, produto_id INTEGER, quantidade INTEGER," +
            "FOREIGN KEY(produto_id) REFERENCES produto(_id))");
    db.execSQL("CREATE TABLE pedido(_id INTEGER PRIMARY KEY, numero_mesa_id INTEGER)" +
            "FOREIGN KEY(numero_mesa_id) REFERENCES mesa(_id)");
    db.execSQL("CREATE TABLE produto (_id INTEGER PRIMARY KEY, descricao TEXT, valor DOUBLE)");
}

Class of my Activity:

public class MesaActivity extends AppCompatActivity {
private DatabaseHelper helper;
private EditText descricao;
public static final String MESA_ID = "_id";
private String id;

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

    descricao = (EditText)findViewById(R.id.edtDescricao);
    helper = new DatabaseHelper(this);

    id = getIntent().getStringExtra(MESA_ID);

    if (id != null){
        prepararEdicao();
    }
}

private void prepararEdicao(){

}

@Override
protected void onDestroy(){
    helper.close();
    super.onDestroy();
}

public void salvarMesa(View view){
    SQLiteDatabase db = helper.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("descricao", descricao.getText().toString());

    long resultado;


    if (id == null){
        resultado = db.insert("mesa", null, values);
    } else {
        resultado = db.update("mesa", values, "_ID= ?", new String[]{id});
    }

    if (resultado != -1){
        Toast.makeText(this, "Dados salvos com sucesso!", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "Erro ao salvar dados!", Toast.LENGTH_SHORT).show();
    }
}

While trying to save data gives the following error:

E/SQLiteLog: (1) no such table: mesa
E/SQLiteDatabase: Error inserting descricao=8
              android.database.sqlite.SQLiteException: no such table: mesa (code 1): , while compiling: INSERT INTO mesa(descricao) VALUES (?)
              #################################################################
              Error Code : 1 (SQLITE_ERROR)
              Caused By : SQL(query) error or missing database.
                (no such table: mesa (code 1): , while compiling: INSERT INTO mesa(descricao) VALUES (?))
  • Change the value of VERSION to 2(private static int VERSAO = 2;) and test again.

  • 2

    I believe it will still cause problems if it was an addition. You need to create a migration script to not try to generate tables that already exist.

  • 2

    @Wakim You’re right, AP does not show the implementation of the method onUpgrade(). I assumed that the drop of all tables.

  • Has my table not been created?

  • You changed the version number as I suggested?

  • I tested your code and the only mistake you made was table pedido already exists. In fact you are creating the "request" table twice, see on onCreate() of the Databasehelper.

Show 1 more comment

2 answers

5


The only thing wrong I see in your code (regarding the creation of the bank) is that you are creating the "request" table twice.

Due to this, when I tested your code I received the error:

android.database.sqlite.Sqliteexception: table pedido already exists (code 1): , while compiling: CREATE TABLE pedido(_id INTEGER PRIMARY KEY, numero_mesa_id INTEGER)FOREIGN KEY(numero_mesa_id) REFERENCES mesa(_id)

Otherwise your code works as expected.

If by chance the table "table" has been added after the database has been created, you need to increment the version number and implement the method onUpdate() so that changes can be made.

Alternatively, if existing data in the database can be discarded, uninstall the application and re-install.

During the development process the implementation of the method onUpdate() can only do the DROP and re-create them.

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String BANCO_DADOS = "MakeRequestApp";
    private static int VERSAO = 1;

    public DatabaseHelper(Context context) {
        super(context, BANCO_DADOS, null, VERSAO);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        criaTabelas(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("Drop Table IF EXISTS produto");
        db.execSQL("Drop Table IF EXISTS itens_pedido");
        db.execSQL("Drop Table IF EXISTS pedido");
        db.execSQL("Drop Table IF EXISTS mesa");

        criaTabelas(db);
    }

    private void criaTabelas(SQLiteDatabase db){
        db.execSQL("CREATE TABLE mesa (_id INTEGER PRIMARY KEY, descricao TEXT)");
        db.execSQL("CREATE TABLE pedido(_id INTEGER PRIMARY KEY, numero_mesa_id INTEGER, " +
                "FOREIGN KEY(numero_mesa_id) REFERENCES mesa(_id))");
        db.execSQL("CREATE TABLE itens_pedido (_id INTEGER PRIMARY KEY, produto_id INTEGER, quantidade INTEGER," +
                "FOREIGN KEY(produto_id) REFERENCES produto(_id))");

        db.execSQL("CREATE TABLE produto (_id INTEGER PRIMARY KEY, descricao TEXT, valor DOUBLE)");
    }
}
  • It worked, thank you very much.

1

From what you understand you try to create 2 tables with the name pedido, so see below the error occurrence below:

Sqliteexception: table pedido already exists (code 1): while compiling: CREATE TABLE request(_id INTEGER PRIMARY KEY, numero_mesa_id INTEGER) FOREIGN KEY(numero_mesa_id) REFERENCES table(_id)

I made the change in your method onCreate() removing the row that tries to create the second table with the name pedido and was thus below:

 @Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE mesa (_id INTEGER PRIMARY KEY, descricao TEXT)");
    db.execSQL("CREATE TABLE pedido(_id INTEGER PRIMARY KEY, numero_mesa_id INTEGER, " +
            " FOREIGN KEY(numero_mesa_id) REFERENCES mesa(_id))");
    db.execSQL("CREATE TABLE itens_pedido (_id INTEGER PRIMARY KEY, produto_id INTEGER, quantidade INTEGER," +
            " FOREIGN KEY(produto_id) REFERENCES produto(_id))");
    db.execSQL("CREATE TABLE produto (_id INTEGER PRIMARY KEY, descricao TEXT, valor DOUBLE)");
}

I even made a method to return all values entered in the table mesa in the DatabaseHelper and returns perfectly the column values descricao:

public List<String> getAll() {
    List<String> todos = new ArrayList<String>();
    String selectQuery = "SELECT * FROM mesa";

    Log.e("HELPER", selectQuery);

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);

    if (c.moveToFirst()) {
        do {
            String item = c.getString((c.getColumnIndex("descricao")));
            // adding to todo list
            todos.add(item);
        } while (c.moveToNext());
    }
    return todos;
}
  • I know that participation in the OS has associated some (a lot) competition but one thing I never do is take advantage of a comment from another to post a response. Besides that the error that the AP presents has nothing to do with the duplication of the table "requested". I already had a prepared answer that I will put.

  • @ramaral but it is very serious, I had not read it. Maybe in the time when I was solving the question, you inserted it. But I don’t want to cause a dispute here, considering that for me the only goal is to help, and of course, to learn too.

  • @And frankly, I don’t remember ever taking advantage of someone else’s comment to publish a reply. Maybe you’re a little too hasty to think that it happened, because you’re not actually on this side of the screen to notice whether or not it actually happened. I did not have an answer ready, I began to analyze the question at the time when the reward appeared. If you already had an answer, I nor anyone could guess, even if they guessed, maybe it would be with another code alternative, etc.

  • I believe you have not seen the comment, do not worry about it. I face these situations as competition even(in sports). You can only comment on the situation. The question is not to answer, but to answer the same as in my comment. I had not yet put an answer because I was waiting for the feedback do AP. I wanted to answer the question and not just signal the question of the table "requested". This is what I did in my reply, suggesting some solutions to solve the question.

Browser other questions tagged

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