sqlite 我添加数据库代码后,我的应用程序不断停止- Android Studio

rta7y2nd  于 2023-02-09  发布在  SQLite
关注(0)|答案(2)|浏览(145)

I don't know what is the problem of my database, my app keep stopping after i added the data base code. Please can you help with to fix that. I have tried many times to figure it out but still not getting anywhere.
This is my data base code : public class databaseOpenHelper extends SQLiteOpenHelper{

// Country table name
private static final String TABLE_NAME= "contacts";

// Country Table Columns names
private static final String KEY_ID = "id";
private static final String NAME = "Name";
private static final String PHONENO = "PhoneNo";

public databaseOpenHelper(Context context){
    super(context,"Login.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase myDB) {
    myDB.execSQL("create Table users(username Text primary key,password Text)");

    // create the table for the first time
    String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
            + PHONENO + " TEXT" + ")";
    myDB.execSQL(CREATE_COUNTRY_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase myDB, int i, int i1) {
    myDB.execSQL("drop Table if exists users");
}

public Boolean isertData(String username,String password){
    SQLiteDatabase myDB = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("username",username);
    contentValues.put("password",password);
    long result = myDB.insert("users",null,contentValues);

    if(result == -1){
        return false;
    }
    else {
        return true;
    }
}

public Boolean checkusername(String username){
    SQLiteDatabase myDB = this.getWritableDatabase();
    Cursor cursor = myDB.rawQuery("select * from users where username = ?",new String[] {username});
    if (cursor.getCount()>0){
        return true;
    }
    else {
        return false;
    }
}

public Boolean checkusernamePassword(String username,String password){
    SQLiteDatabase myDB = this.getWritableDatabase();
    Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?",new String[] {username,password});
    if (cursor.getCount()>0){
        return true;
    }
    else{
        return false;
    }
}


// method to add the contact
public void addcontact(ContactModel contact){
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues c=new ContentValues();
    c.put(NAME,contact.getName());
    c.put(PHONENO,contact.getPhoneNo());
    db.insert(TABLE_NAME,null,c);
    db.close();
}

// method to retrieve all the contacts in List
public List<ContactModel> getAllContacts(){
    List<ContactModel> list=new ArrayList<>();
    String query="SELECT * FROM "+TABLE_NAME;
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor c=db.rawQuery(query,null);
    if(c.moveToFirst()) {
        do {

            list.add(new ContactModel(c.getInt(0),c.getString(1),c.getString(2)));

        } while (c.moveToNext());
    }
    return list;
}

// get the count of data, this will allow user
// to not add more that five contacts in database
public int count(){
    int count=0;
    String query="SELECT COUNT(*) FROM "+TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c=db.rawQuery(query,null);
    if(c.getCount()>0){
        c.moveToFirst();
        count=c.getInt(0);
    }
    c.close();
    return count;
}
// Deleting single country
public void deleteContact(ContactModel contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i=db.delete(TABLE_NAME,KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getId()) });

    db.close();
}

}
And this is my logcat : FATAL EXCEPTION: main Process: com.example.localisation, PID: 11700 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.localisation/com.example.localisation.phone}: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:201) at android.os.Looper.loop(Looper.java:288) at android.app.ActivityThread.main(ActivityThread.java:7839) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1047) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:654) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590) at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:62) at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1546) at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1485) at com.example.localisation.databaseOpenHelper.getAllContacts(databaseOpenHelper.java:108) at com.example.localisation.phone.onCreate(phone.java:81) at android.app.Activity.performCreate(Activity.java:8051) at android.app.Activity.performCreate(Activity.java:8031) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loopOnce(Looper.java:201)  at android.os.Looper.loop(Looper.java:288)  at android.app.ActivityThread.main(ActivityThread.java:7839)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 

axkjgtzd

axkjgtzd1#

故障是指没有一个名为contacts的表,根据

Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts

运行代码,然后使用错误的getAllContacts方法,如日志中所示:-

at com.example.localisation.databaseOpenHelper.getAllContacts(databaseOpenHelper.java:108)

工作。
因此,很可能是您在之前运行应用程序后添加了联系人电缆,并且创建了数据库。数据库将持续存在,因此从一次运行到另一次运行仍将存在。因此,不会调用**onCreate方法,因为它仅在创建数据库时调用一次。
简单的解决方法是卸载应用程序并重新运行。但是,这将删除所有现有数据。
如果您需要保留任何数据,则应
a)增加版本号,然后b)onUpgrade**方法添加代码以创建新表(相同的代码)。
例如:

  • (a)*
public databaseOpenHelper(Context context){
   super(context,"Login.db",null,2 /*<<<<<<<<<< CHANGED */);
}
  • (b)*
@Override
public void onUpgrade(SQLiteDatabase myDB, int i, int i1) {
   //myDB.execSQL("drop Table if exists users");
   if (i1 == 2) {
      String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
             + KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
             + PHONENO + " TEXT" + ")";
      myDB.execSQL(CREATE_COUNTRY_TABLE);

   }
}

您可以看到联系人表已使用App Inspection创建,例如

i7uq4tfw

i7uq4tfw2#

根据你上传的错误代码,我注意到这个SELECT * FROM contacts这意味着你没有表命名为联系人在你的sqlite数据库,所以我建议你,测试你应该使用sqlite浏览器创建数据库,并添加数据到它,然后使用它在你的android studio项目.如果你有任何问题害怕不要犹豫,问它在评论谢谢.

相关问题