6
respostas

Erro ao fazer insert no banco

Boa tarde! Até a aula 02 do módulo 02 o app funcionou normal, agora está apresentado o erro abaixo, pelo o que entendi o banco foi apagado e o insert dá erro, tenho que voltar a DAO para 0?

<10-26 16:13:54.225 8960-8960/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:13:54.225 8960-8960/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:13:55.035 4084-8947/com.google.android.gms.persistent E/WakeLock: GCM_HB_ALARM release without a matched acquire!
10-26 16:14:10.459 8972-8972/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:14:10.459 8972-8972/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:14:15.161 4084-8970/com.google.android.gms.persistent E/WakeLock: GCM_HB_ALARM release without a matched acquire!
10-26 16:14:26.835 8985-8985/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:14:26.835 8985-8985/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:14:43.027 8996-8996/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:14:43.027 8996-8996/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:14:59.361 9008-9008/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:14:59.361 9008-9008/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:15:15.538 9020-9020/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:15:15.538 9020-9020/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:15:31.780 9031-9031/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:15:31.780 9031-9031/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:16:04.853 9041-9041/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:16:04.854 9041-9041/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:16:11.526 8448-8484/br.com.pslc.agenda E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa1f2f40
10-26 16:16:15.080 8448-8484/br.com.pslc.agenda E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa1f2e00
10-26 16:16:15.156 3353-4305/com.android.inputmethod.latin E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa20ba4a0
10-26 16:16:17.545 2170-9066/? E/OMXNodeInstance: setConfig(1e:google.vorbis.decoder, ConfigPriority(0x6f800002)) ERROR: Undefined(0x80001001)
10-26 16:16:19.887 2170-2470/? E/CameraService: disconnect: Disconnect called on already disconnected client for device 1
10-26 16:16:20.819 8881-8908/com.android.camera E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa19c6e0
10-26 16:16:22.601 9069-9069/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:16:22.602 9069-9069/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:16:39.603 9080-9080/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-26 16:16:39.603 9080-9080/? E/android.os.Debug: failed to load memtrack module: -2
10-26 16:17:05.248 8448-8448/br.com.pslc.agenda E/SQLiteLog: (1) table Alunos has no column named caminhoFoto
10-26 16:17:05.249 8448-8448/br.com.pslc.agenda E/SQLiteDatabase: Error inserting caminhoFoto=/storage/emulated/0/Android/data/br.com.pslc.agenda/files/1540570573702.jpg nome=Paulo Sergio nota=0.0 endereco=Rua Cristovao Bezerra Dantas, 203 site=www,google.com telefone=(11) 984261179
    android.database.sqlite.SQLiteException: table Alunos has no column named caminhoFoto (code 1): , while compiling: INSERT INTO Alunos(caminhoFoto,nome,nota,endereco,site,telefone) VALUES (?,?,?,?,?,?)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
        at br.com.pslc.agenda.dao.AlunoDAO.insere(AlunoDAO.java:47)
        at br.com.pslc.agenda.FormularioActivity.onOptionsItemSelected(FormularioActivity.java:94)
        at android.app.Activity.onMenuItemSelected(Activity.java:2908)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowC>
6 respostas

Poste aqui o método onUpgrade da classe AlunoDAO.

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "";
        switch (oldVersion){
            case 1:
                sql = "ALTER TABLE Alunos ADD COLUMN caminhoFoto TEXT;";
                db.execSQL(sql);
        }
    }

A versão atual do banco é 2?

Olá Eduardo,

Posta aqui pra gente o conteúdo completo da sua classe AlunoDAO, por favor?

A pergunta sobre a versão do banco que o Edson fez é bem relevante e pode ser a causa do problema.

Tenho quase certeza que é isso, porque o banco foi apagado, não consigo recriá-lo, mudo a versão para 1 dá erro, tem algum lugar que a versão ficou marcada como 1. Para mim esse problema aconteceu quando ocorreu o Alter Table. Segue código abaixo: package br.com.pslc.agenda.dao;

import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull;

import java.util.ArrayList; import java.util.List;

import br.com.pslc.agenda.modelo.Aluno;

public class AlunoDAO extends SQLiteOpenHelper { public AlunoDAO(Context context) { super(context, "Agenda", null, 2); }

@Override
public void onCreate(SQLiteDatabase db) {
    String sql = "CREATE TABLE Alunos(id INTEGER PRIMARY KEY," +
            " nome TEXT NOT NULL," +
            " endereco TEXT, " +
            "telefone TEXT, " +
            "site TEXT, " +
            "nota REAL, " +
            "camihoFoto TEXT);";
    db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String sql = "";
    switch (oldVersion){
        case 1:
            sql = "ALTER TABLE Alunos ADD COLUMN caminhoFoto TEXT";
            db.execSQL(sql);
    }
}

public void insere(Aluno aluno) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues dados = pegaDadosDoAluno(aluno);

    db.insert("Alunos", null, dados);
}

@NonNull
private ContentValues pegaDadosDoAluno(Aluno aluno) {
    ContentValues dados = new ContentValues();
    dados.put("nome",aluno.getNome());
    dados.put("endereco",aluno.getEndereco());
    dados.put("telefone",aluno.getTelefone());
    dados.put("site",aluno.getSite());
    dados.put("nota",aluno.getNota());
    dados.put("caminhoFoto", aluno.getCaminhoFoto());
    return dados;
}

public List<Aluno> buscaAlunos() {
    String sql = "SELECT * FROM Alunos;";
    SQLiteDatabase db = getReadableDatabase();
    Cursor c = db.rawQuery(sql, null);

    List<Aluno> alunos = new ArrayList<Aluno>();
    while (c.moveToNext()){
        Aluno aluno = new Aluno();
        aluno.setId(c.getLong(c.getColumnIndex("id")));
        aluno.setNome(c.getString(c.getColumnIndex("nome")));
        aluno.setEndereco(c.getString(c.getColumnIndex("endereco")));
        aluno.setTelefone(c.getString(c.getColumnIndex("telefone")));
        aluno.setSite(c.getString(c.getColumnIndex("site")));
        aluno.setNota(c.getDouble(c.getColumnIndex("nota")));
        aluno.setCaminhoFoto(c.getString(c.getColumnIndex("caminhoFoto")));

        alunos.add(aluno);
    }
    c.close();
    return alunos;
}

public void deleta(Aluno aluno) {
    SQLiteDatabase db = getWritableDatabase();

    String[] params = {aluno.getId().toString()};
    db.delete("Alunos","id = ?", params);
}

public void altera(Aluno aluno) {
    SQLiteDatabase db = getWritableDatabase();

    String[] params = {aluno.getId().toString()};
    ContentValues dados = pegaDadosDoAluno(aluno);
    db.update("Alunos", dados, "id = ?", params);

}

}

Limpe os dados da aplicação no emulador/celular e tente novamente.