无法在Android

时间:2018-08-17 23:12:23

标签: android android-sqlite

我正在尝试将书对象插入数据库中,但是我一直遇到错误。我不知道我在做什么错。我有两节课。代码可以编译,但是当我尝试添加book对象时,它会在MySQLiteHelper类中的addbooks方法上引发错误,但是如果我删除了在ContentValues上插入“ date string”的行,则一切正常,并将book对象添加到数据库中。

AddBook.class

public class AddBooks extends BaseActivity implements View.OnClickListener {

private EditText mBookTitle, mBookAuthor, mBookISBN, mBookDate;
private Button upload;
private MySQLiteHelper db = new MySQLiteHelper(this);
private String title, author, isbn, date;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_books);


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (getSupportActionBar() != null)
            (getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
    }

    mBookTitle = findViewById(R.id.book_title_edit);
    mBookAuthor = findViewById(R.id.book_author_edit);
    mBookISBN = findViewById(R.id.book_isbn_edit);
    mBookDate = findViewById(R.id.book_date_edit);
    mBookDate.setOnClickListener(this);

    upload = findViewById(R.id.book_upload);
    upload.setOnClickListener(this);

}

private boolean checkField() {
    //get text from the editText fields
    boolean valid = true;
    View focusView = null;

    title = mBookTitle.getText().toString().trim();
    author = mBookAuthor.getText().toString().trim();
    isbn = mBookISBN.getText().toString().trim();
    date = mBookDate.getText().toString();

    //gives error report if the editText field is empty
    if (TextUtils.isEmpty(title)) {
        mBookTitle.setError(getString(R.string.empty_title));
        focusView = mBookTitle;
        valid = false;
    }
    if (TextUtils.isEmpty(author)) {
        mBookAuthor.setError(getString(R.string.empty_author));
        focusView = mBookAuthor;
        valid = false;
    }
    if (!valid) {
        focusView.requestFocus();
    }
    return valid;
}

@Override
public void onClick(View v) {
    //dialog popup for date selection on editText click
    if (v == mBookDate) {
        final Calendar calendar = Calendar.getInstance();
        int mYear = calendar.get(Calendar.YEAR);
        int mMonth = calendar.get(Calendar.MONTH);
        int mDay = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        mBookDate.setText(dayOfMonth + "-" + (month + 1) + "-" + year);
                    }
                }, mYear, mMonth, mDay);
        datePickerDialog.show();
    }

    if (v == upload) {
        if (checkField()) {
             Book book = new Book(author, title, isbn, date);

            //add books to the database
            db.addBook(book);

            Toast.makeText(this, getString(R.string.success_upload), Toast.LENGTH_SHORT).show();
            mBookDate.setText("");
            mBookTitle.setText("");
            mBookISBN.setText("");
            mBookAuthor.setText("");
        }
    }
}

/**
 * Take care of popping the fragment back stack or finishing the activity
 * as appropriate.
 */
@Override
public void onBackPressed() {
    super.onBackPressed();
}

}

MySQLiteHelper.class

public class MySQLiteHelper extends SQLiteOpenHelper {


// Database Name - BookDB
private static final String DATABASE_NAME = "BookDB";

// Table Name - books and users
private static final String TABLE_BOOKS = "books";


// Columns Names of books Table
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";
private static final String KEY_ISBN = "isbn";
private static final String KEY_DATE_PUB = "date";


// Database Version
private static final int DATABASE_VERSION = 1;

// Log TAG for debugging purpose
private static final String TAG = "SQLiteDebugLog";

// Constructor
public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_BOOK_TABLE = "CREATE TABLE books ( " + "id INTERGER PRIMARY KEY AUTOINCREMENT, " +
        "author TEXT, " + "title TEXT, " + "isbn TEXT, " + "date TEXT)";


    // execute an SQL statement to create the table
    db.execSQL(CREATE_BOOK_TABLE);
}

// onUpdate() is invoked when you upgrade the database scheme.

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older books table if existed
    db.execSQL("DROP TABLE IF EXISTS books");

    this.onCreate(db);
}
//******************************METHODS FOR BOOK*******************************************

public void addBook(Book book){
    Log.d(TAG, "addBook() - " + book.toString());
    //  get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    //  create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put(KEY_AUTHOR, book.getAuthor()); // get author
    values.put(KEY_TITLE, book.getTitle()); // get title
    values.put(KEY_ISBN, book.getIsbn()); // get isbn
    values.put(KEY_DATE_PUB, book.getDatePublish());

    //print the book details
    System.out.println("set title: " + book.getTitle());
    System.out.println("set author: " + book.getAuthor());
    System.out.println("set isbn: "+ book.getIsbn());
    System.out.println("set date: " + book.getDatePublish());
    //  insert
    db.insert(TABLE_BOOKS, // table
            null, //nullColumnHack
            values); // key/value -> keys = column names/ values = column values

    // 4. close - release the reference of writable DB
    db.close();
}

}

这是我每次尝试添加书时都会不断收到的表簿没有列日期的错误。

    D/SQLiteDebugLog: addBook() - com.android.nsuklib.data.Book@1c8cf0f
I/System.out: set title: cool things
              set author: Jamse
I/System.out: set isbn: REISUEY
              set date: 17-8-2018
E/SQLiteLog: (1) table books has no column named date
E/SQLiteDatabase: Error inserting date=17-8-2018 title=cool things author=Jamse isbn=REISUEY
                  android.database.sqlite.SQLiteException: table books has no column named date (code 1): , while compiling: INSERT INTO books(date,title,author,isbn) 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.android.nsuklib.data.MySQLiteHelper.addBook(MySQLiteHelper.java:116)
                      at com.android.nsuklib.data.AddBooks.onClick(AddBooks.java:99)
                      at android.view.View.performClick(View.java:6256)
                      at android.view.View$PerformClick.run(View.java:24697)
                      at android.os.Handler.handleCallback(Handler.java:789)
                      at android.os.Handler.dispatchMessage(Handler.java:98)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
E/EGL_emulation: tid 10741: eglSurfaceAttrib(1210): error 0x3009 (EGL_BAD_MATCH)

1 个答案:

答案 0 :(得分:0)

  

表格簿没有名为日期的列

因此,请检查表方案或更改列名,也许不允许date作为列名。