1

I'm working on a small app that uses SQLite. Could you please tell me why is the app crashing after I press the Buttons View and Delete?? And also why is ADD button not creating new data.

    public class MainActivity extends AppCompatActivity {
        DatabaseHelper myDB;
        EditText editTextObsah, editTextNazev, editTextID;
        Button buttonAdd, buttonView,buttonUpdate, buttonDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDB = new DatabaseHelper(this);

        editTextNazev = (EditText)findViewById(R.id.editTextObsah);
        editTextObsah = (EditText)findViewById(R.id.editTextNazev);
        editTextID = (EditText)findViewById(R.id.editTextID);
        buttonAdd = (Button)findViewById(R.id.buttonAdd);
        buttonView = (Button)findViewById(R.id.buttonView);
        buttonUpdate = (Button)findViewById(R.id.buttonUpdate);
        buttonDelete = (Button)findViewById(R.id.buttonDelete);
        insertData();
        viewAll();
        updateData();
        deleteData();
    }
    public void deleteData(){
        buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer deletedRows = myDB.deleteData(editTextID.getText().toString());
                if(deletedRows > 0)
                    Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(MainActivity.this,"Data not Deleted",Toast.LENGTH_LONG).show();
            }
        });
    }
    public void updateData(){
        buttonUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               boolean isUpdated =  myDB.updateData(editTextID.getText().toString(),editTextNazev.getText().toString(),editTextObsah.getText().toString());
            if(isUpdated == true)
                Toast.makeText(MainActivity.this,"Data Updated",Toast.LENGTH_LONG).show();
                else
                Toast.makeText(MainActivity.this,"Data not Updated",Toast.LENGTH_LONG).show();

            }
        });
    }
    public void insertData(){
        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               boolean isInserted =  myDB.insertData(editTextNazev.getText().toString(),editTextObsah.getText().toString());
                if(isInserted == true)
                    Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
            }
        });
    }
    public void viewAll() {
        buttonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor res = myDB.getAllData();
                if(res.getCount() == 0){
                    //show message
                    showMessage("Error","No data found");
                    return;
                }
                StringBuffer buffer = new StringBuffer();
                while (res.moveToNext()) {
                    buffer.append("Id :"+ res.getString(0)+"\n");
                    buffer.append("Caption :"+ res.getString(1)+"\n");
                    buffer.append("Content :"+ res.getString(2)+"\n\n");
                }
                // Show all data
                showMessage("Data",buffer.toString());
            }
        });
    }
    public void showMessage(String title, String Message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    }

}

My Database class:

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "notes.db";
    public static final String TABLE_NAME = "notes_table.db";
    public static final String ID = "ID";
    public static final String CAPTION = "CAPTION";
    public static final String CONTENT = "CONTENT";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

            db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAZEV TEXT,OBSAH TEXT)");

    }

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

    public boolean insertData(String caption, String content){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues CV = new ContentValues();
        CV.put(CAPTION,caption);
        CV.put(CONTENT,content);
        long result = db.insert(TABLE_NAME,null,CV);
        if(result == -1)
            return false;
        else
            return true;
    }
    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
        return res;
    }

    public boolean updateData(String id, String caption, String content){
try {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues CV = new ContentValues();
    CV.put(ID,id);
    CV.put(CAPTION,caption);
    CV.put(CONTENT,content);
    db.update(TABLE_NAME, CV, "ID = ?",new String[]{ id });
}catch (Exception e) {
}
        return true;
    }
    public Integer deleteData(String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_NAME,"ID = ?",new String[]{ id });

}}

Error Log

05-23 14:11:04.821 12666-12666/com.example.qwasyx0.semestralka E/SQLiteLog: (1) no such table: notes_table.db
05-23 14:11:04.821 12666-12666/com.example.qwasyx0.semestralka E/SQLiteDatabase: Error inserting CAPTION=Obsah CONTENT=Název
                                                                                 android.database.sqlite.SQLiteException: no such table: notes_table.db (code 1): , while compiling: INSERT INTO notes_table.db(CAPTION,CONTENT) VALUES (?,?)
                                                                                     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                     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:1472)
                                                                                     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
                                                                                     at com.example.qwasyx0.semestralka.DatabaseHelper.insertData(DatabaseHelper.java:43)
                                                                                     at com.example.qwasyx0.semestralka.MainActivity$3.onClick(MainActivity.java:65)
                                                                                     at android.view.View.performClick(View.java:5637)
                                                                                     at android.view.View$PerformClick.run(View.java:22429)
                                                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
qwasyx0
  • 13
  • 4
  • Use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare May 23 '17 at 13:59
  • Ok it says: no such table: notes_table.db do you know why is it not creating the db? Error should be in getAllData() method – qwasyx0 May 23 '17 at 14:01
  • Where are you opening and closing the Database ? – someengr May 23 '17 at 14:04
  • Don't really understand the question, but I call the methods in onCreate in MainActivity – qwasyx0 May 23 '17 at 14:07
  • Post the full logcat error – Denny May 23 '17 at 14:09
  • here are too many possibilities your table name also suspicious "notes_table.db" need complete logcat – Pavan May 23 '17 at 14:10
  • Change your table name name by removing .db and reinstall app and check – Pavan May 23 '17 at 14:14
  • Still says no such table but error is now in insertData() long result = db.insert(TABLE_NAME,null,CV); and insertData() in the boolean row – qwasyx0 May 23 '17 at 14:16
  • why there is diff column name in create table and in insert value columns you can debug app to get idea what happening https://developer.android.com/studio/debug/index.html – Pavan May 23 '17 at 14:35
  • Thanks didnt notice that, but didnt change anything. Gonna try to debug – qwasyx0 May 23 '17 at 14:40

2 Answers2

1

change your create query because column name are diff in create and other queries make that unique

 db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,"+CAPTION+" TEXT,"+CONTENT+" TEXT)");

and also table name

public static final String TABLE_NAME = "notes_table";

also put database version in final variable

private static final int DBVERSION=1; 


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DBVERSION);
    }

uninstall existing app and then install to check effect or you can increase DBVERSION too

Pavan
  • 5,016
  • 1
  • 26
  • 30
0

I'm guessing that it has something to do with your database version.

In your constructor

public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

you should use a local variable (DATABASE_VERSION for example) that needs to be incremented every time you make a change to the DB structure, so that the tables are dropped and recreated.

So use something like this

// the database version
static final int DATABASE_VERSION = 2; 
.....
public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }
andreid
  • 225
  • 4
  • 13