android - Logcat 将数据库条目显示为空值

标签 android eclipse sqlite

我从一个网站得到了以下代码,我也做了一些修改。当我在日志猫中打印数据库时,我得到了 ID,但我得到的作者和标题为空。有人能告诉我可能是什么错误吗?

这是 Book.java

package com.hmkcode.android.model;
public class Book {
private int id;
private String title;
private String author;

public Book(){}

public Book(String title, String author) {
    super();
    this.title = title;
    this.author = author;
}

//getters & setters
// getting ID
public int getId(){
    return this.id;
}

// setting id
public void setId(int id){
    this.id = id;
}
// getting title
public String getTitle(){
    return this.title;
}

// setting title
public void setTitle(String name){
    this.title = title;
}

// getting authorname
public String getAuthor(){
    return this.author;
}

// setting authorname
public void setAuthor(String phone_number){
    this.author = author;
}
}

这是 MySQLiteHelper.java

 public class MySQLiteHelper extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "BookDB";

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

@Override
public void onCreate(SQLiteDatabase db) {
    // SQL statement to create book table
    String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
            "title TEXT, "+
            "author TEXT )";

    // create books table
    db.execSQL(CREATE_BOOK_TABLE);
}

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

    // create fresh books table
    this.onCreate(db);
}
//---------------------------------------------------------------------

/**
 * CRUD operations (create "add", read "get", update, delete) book + get all books + delete all books
 */

// Books table name
private static final String TABLE_BOOKS = "books";

// Books Table Columns names
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[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};

public void addBook(Book book){
    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

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

    // 3. insert
    db.insert(TABLE_BOOKS, // table
            null, //nullColumnHack
            values); // key/value -> keys = column names/ values = column values

    // 4. close
    db.close(); 
}

public Book getBook(int id){

    // 1. get reference to readable DB
    SQLiteDatabase db = this.getReadableDatabase();

    // 2. build query
    Cursor cursor = 
            db.query(TABLE_BOOKS, // a. table
            COLUMNS, // b. column names
            " id = ?", // c. selections 
            new String[] { String.valueOf(id) }, // d. selections args
            null, // e. group by
            null, // f. having
            null, // g. order by
            null); // h. limit

    // 3. if we got results get the first one
    if (cursor != null)
        cursor.moveToFirst();

    // 4. build book object
    Book book = new Book();
    book.setId(Integer.parseInt(cursor.getString(0)));
    book.setTitle(cursor.getString(1));
    book.setAuthor(cursor.getString(2));
    // 5. return book
    return book;
}

// Get All Books
public List<Book> getAllBooks() {
    List<Book> books = new LinkedList<Book>();

    // 1. build the query
    String query = "SELECT  * FROM " + TABLE_BOOKS;

    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. go over each row, build book and add it to list
    Book book = null;
    if (cursor.moveToFirst()) {
        do {
            book = new Book();
            book.setId(Integer.parseInt(cursor.getString(0)));
            book.setTitle(cursor.getString(1));
            book.setAuthor(cursor.getString(2));

            // Add book to books
            books.add(book);
        } while (cursor.moveToNext());
    }
    // return books
    return books;
}

 // Updating single book
public int updateBook(Book book) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put("title", book.getTitle()); // get title 
    values.put("author", book.getAuthor()); // get author

    // 3. updating row
    int i = db.update(TABLE_BOOKS, //table
            values, // column/value
            KEY_ID+" = ?", // selections
            new String[] { String.valueOf(book.getId()) }); //selection args

    // 4. close
    db.close();

    return i;

}

// Deleting single book
public void deleteBook(Book book) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. delete
    db.delete(TABLE_BOOKS,
            KEY_ID+" = ?",
            new String[] { String.valueOf(book.getId()) });

    // 3. close
    db.close();
}
}

这是MainActivity.java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MySQLiteHelper db = new MySQLiteHelper(this);

    /**
     * CRUD Operations
     * */
    // add Books
    /*Log.d("Inserting: ", "Inserting all Books..");
    db.addBook(new Book("Android Application Development Cookbook", "Wei Meng Lee"));   
    db.addBook(new Book("Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));       
    db.addBook(new Book("Learn Android App Development", "Wallace Jackson"));*/
   //Reading and getting all books
    Log.d("Reading: ", "Reading all Books.."); 
    List<Book> list = db.getAllBooks();
    for (Book cn:list) {
        String log = "Id: "+cn.getId()+" ,Title: " + cn.getTitle() + " ,Author: " + cn.getAuthor();
            // Writing Contacts to log
    Log.d("Name: ", log);
   // delete one book
    //db.deleteBook(list.get(3));
}
}
}

这就是我在 Logcat 中得到的

12-17 12:18:01.498: D/Name:(506): Id: 29 ,Title: null ,Author: null
12-17 12:18:01.498: D/Name:(506): Id: 33 ,Title: null ,Author: null
12-17 12:18:01.498: D/Name:(506): Id: 36 ,Title: null ,Author: null
12-17 12:18:01.498: D/Name:(506): Id: 41 ,Title: null ,Author: null
12-17 12:18:01.498: D/Name:(506): Id: 42 ,Title: null ,Author: null
12-17 12:18:01.498: D/Name:(506): Id: 43 ,Title: null ,Author: null
12-17 12:18:01.498: D/Name:(506): Id: 44 ,Title: null ,Author: null
12-17 12:18:01.508: D/Name:(506): Id: 45 ,Title: null ,Author: null
12-17 12:18:01.508: D/Name:(506): Id: 46 ,Title: null ,Author: null

忽略id不对,因为我删除和添加了很多条目。

最佳答案

Book.java 错误,

// setting title
public void setTitle(String name){ ---> change argument as title you are using name
    this.title = title; 
}


// setting authorname
public void setAuthor(String phone_number){ ---> change argument as author
    this.author = author;
}
}

对于更新:

 // Updating single book
public int updateBook(Book book, String newTitle, String newAuthor) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put("title", newTitle); // get title 
    values.put("author", newAuthor()); // get author

    // 3. updating row
    int i = db.update(TABLE_BOOKS, //table
            values, // column/value
            KEY_ID+" = ?", // selections
            new String[] { String.valueOf(book.getId()) }); //selection args

     // Based on your condition

    // 4. close
    db.close();

    return i;

}

关于android - Logcat 将数据库条目显示为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20627901/

相关文章:

Android : java. lang.NoSuchMethodError : org. apache.commons.codec.binary.Base64.encodeBase64String in android

java - gcm_defaultSenderId 无法解析

java - 用于 Eclipse 和运行 Glassfish 的 GlassFish 工具包问题

sqlite - 新的 SQLite3 PHP 类中是否有事务支持?

jdbc - 在sqlite上调用createArrayOf方法时出现java.lang.AbstractMethodError : org. sqlite.Conn.createArrayOf错误

Android:可从库项目绘制到应用程序

java - android 2.3.6版本中的NoClassDefFoundError(HttpResponseCahe)

android - 如何在运行时将参数从 Activity 或 Fragment 传递到 Dagger 模块

android - BitmapFactory.decodeResource() 忽略 jpg 图像的 inPreferredConfig 选项

node.js - 我收到 SQLITE_Error : no such column, 但它存在为什么?