在SQLite数据库中插入值时,应用程序崩溃了

时间:2018-01-14 13:47:01

标签: java android

我无法在insertContact方法中找到错误,因为当我插入值时,它会崩溃,这就是为什么我在try catch块中插入我的代码但问题仍然存在。

 private static final String table_create = "create table" + table_name + "(" + key_id + "integer primary key" + key_name + "text"
                + key_email + "text" + key_uname + "text" + key_pass + "text";
        SQLiteDatabase sqLiteDatabase;     
                public DatabaseHandler(Context context) {     
            super(context, database_name, null, database_version);    
        }   
                @Override    
        public void onCreate(SQLiteDatabase sqLiteDatabase) {    
                    sqLiteDatabase.execSQL(table_create);     
            this.sqLiteDatabase = sqLiteDatabase;   
        }    
                public void insertContact(Contact contact) {
            try {
                sqLiteDatabase = this.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("name", contact.getName());
                values.put("email", contact.getEmail());
                values.put("uname", contact.getUname());
                values.put("pass", contact.getPass());
                sqLiteDatabase.insert(table_name, null, values);
                sqLiteDatabase.close();
            }
            catch (Exception e){e.printStackTrace();}
        }
                public String searchPass(String uname) {
            String b="";
            try {
                sqLiteDatabase = this.getReadableDatabase();
                String query = "select uname, pass from" + table_name;
                Cursor cursor = sqLiteDatabase.rawQuery(query, null);
                String a;
                b = "Not found ";
                if (cursor.moveToFirst()) {
                    do {
                        a = cursor.getString(0);

                        if (a.equals(uname)) {
                            b = cursor.getString(1);
                            break;
                        }
                    }
                    while (cursor.moveToNext());
                }
             }
            catch (Exception e){e.printStackTrace();}
            return b;
        }

2 个答案:

答案 0 :(得分:0)

你应该改变你的创建顺序,如下所示:

            @Override    
    public void onCreate(SQLiteDatabase sqLiteDatabase) { 
                this.sqLiteDatabase = sqLiteDatabase;    
                sqLiteDatabase.execSQL(table_create);       
    }  

答案 1 :(得分:0)

对于onCreate方法,请执行以下操作:

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(create_table);
}

另外,更改

的名称
this.sqLiteDatabase 

与不同的东西。干杯!