尝试将数据添加到数据库

时间:2018-10-20 00:45:44

标签: java android database sqlite

我正在尝试将数据添加到具有3列的数据库中,当我尝试添加多个值时,我收到一条吐司消息,该消息是我创建的:“发生了错误”,我知道我做错了,但是我我不确定。这是所有AddData方法都有错误的主要活动

btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newEntry = editText.getText().toString();
                String dateReleased=edtDateReleased.getText().toString();
                if (editText.length() != 0) {
                    AddData(newEntry,dateReleased);
                    editText.setText("");
                    edtDateReleased.setText("");
                } else {
                    toastMessage("You must put something in the text");
        btnViewData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
                startActivity(intent);
            }
        });
    }

    public void AddData(String newEntry,String dateReleased) {
        boolean insertData = mDatabaseHelper.addData(newEntry,dateReleased);
        if (insertData) {
            toastMessage("Data Successfully Inserted!");
        } else {
            toastMessage("Something went wrong");
        }
    }

这是DatabaseHelper类

 @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL2 +" TEXT, "
                +COL3+" TEXT,"
                +COL4+" TEXT)";
        db.execSQL(createTable);
    }

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

    public boolean addData(String title,String dateReleased) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, title);
        contentValues.put(COL3,dateReleased);
        String fileName="/sdcard/"+title+".mpg";
        contentValues.put(COL4,fileName);


        Log.d(TAG, "addData: Adding " + title + " to " + TABLE_NAME);

        long result = db.insert(TABLE_NAME, null, contentValues);

        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

1 个答案:

答案 0 :(得分:1)

您应该首先使用类的实例打开连接

SQLiteDatabase db =this.getWritableDatabase();
this.onOpen(db);
ContentValues contentValues = new ContentValues();
contentValues.put("column_name", "column_value");
long result = db.insert(TABLE_NAME, null, contentValues);
db.close();
相关问题