简体   繁体   English

SQLite数据库应用程序不断崩溃

[英]SQLite database app keep crashing

I'm working on a small app that uses SQLite. 我正在使用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)

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 卸载现有应用,然后安装以检查效果,或者您也可以增加DBVERSION

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. 您应该使用局部变量(例如,DATABASE_VERSION),该变量在每次更改数据库结构时都需要增加,以便删除并重新创建表。

So use something like this 所以用这样的东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM