应用程序"不幸停止"通过单击按钮插入数据时

时间:2017-07-02 07:03:25

标签: android sqlite sqliteopenhelper android-database

所以,这是我的数据库助手类

public class DBHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME =  "EventManager.db";
    public static final String TABLE_NAME =  "EventManager";
    public static final String Col_1 =  "NAME";
    public static final String Col_2 =  "DATE";
    public static final String Col_3 =  "TIME";
    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME + " (NAME TEXT, DATE TEXT, TIME 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 name, String date, String time){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(Col_1, name);
        contentValues.put(Col_2, date);
        contentValues.put(Col_3, time);
        db.insert(TABLE_NAME, null, contentValues);
        return true;
    }
}

我试图从另一个类调用insertData(),如:

public void addData(View view){
    if(dbHelper.insertData(editTitle.getText().toString(), date.getText().toString(), 
                    time.getText().toString())) 
        Toast.makeText(AddEventActivity.this, "Event saved", Toast.LENGTH_LONG).show();                
    else 
        Toast.makeText(AddEventActivity.this, "Event not saved", Toast.LENGTH_LONG).show();
}

单击按钮时会调用addData()。

因此,每当我尝试使用代码保存数据时,我的应用程序都会崩溃。 问题是数据库连接,我检查了所有的editTexts,按钮调用,一切都很好。它仅在涉及数据库时崩溃,当我尝试没有数据库和在点击按钮上显示editText值的简单toast时,它工作正常。 请帮忙。

Logcat:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.yogith.exampleevent.DBHelper.insertData(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
                                                                               at com.example.yogith.exampleevent.AddEventActivity.addData(AddEventActivity.java:87)
                                                                               at java.lang.reflect.Method.invoke(Native Method) 
                                                                               at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                                               at android.view.View.performClick(View.java:5201) 

错误

07-02 12:56:37.235 9949-9949/com.example.yogith.exampleevent W/System: ClassLoader referenced unknown path: /data/app/com.example.yogith.exampleevent-1/lib/arm

解决: DBHelper对象,' dBHelper'使用调用addData()没有被正确声明。 感谢

0 个答案:

没有答案