在Listview上显示数据库

时间:2016-04-21 14:58:15

标签: android listview

我正在尝试创建一个ListView,它在Android应用程序的活动中显示我的数据库的内容。我尝试过的方法在应用程序运行之前崩溃了。下面是我的主要活动和sqlhelper类的代码。如果有人能告诉我为什么那将是非常感谢。

主要活动     包com.mcclure.hannah.books;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.List;
import com.mcclure.hannah.books.MySQLiteHelper;
import com.mcclure.hannah.books.Book;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
private ListView lv ;
private String TAG="Hannah";

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

    /**
     * CRUD Operations
     * */
    // add 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"));

    // get all books
    List<Book> list = db.getAllBooks();

    // delete one book
    db.deleteBook(list.get(0));

    // get all books
    db.getAllBooks();

    String[] array = list.toArray(new String[list.size()]);


    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
             this,
             android.R.layout.simple_list_item_1, array );
    Log.d(TAG,"**************************");
     lv.setAdapter(arrayAdapter);



}

}

MySQLiteHelper类

package com.mcclure.hannah.books;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.mcclure.hannah.books.Book;
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){
    Log.d("addBook", book.toString());
    // 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));

    Log.d("getBook("+id+")", book.toString());

    // 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());
    }

    Log.d("getAllBooks()", books.toString());

    // 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();

    Log.d("deleteBook", book.toString());

}

diplayed的错误消息(stacktrace)是:

04-21 16:12:09.364 6896-6896/com.mcclure.hannah.books E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mcclure.hannah.books, PID: 6896
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mcclure.hannah.books/com.mcclure.hannah.books.MainActivity}: java.lang.ArrayStoreException: com.mcclure.hannah.books.Book cannot be stored in an array of type java.lang.String[]
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2808)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
        at android.app.ActivityThread.access$900(ActivityThread.java:181)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:6145)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
     Caused by: java.lang.ArrayStoreException: com.mcclure.hannah.books.Book cannot be stored in an array of type java.lang.String[]
        at java.util.LinkedList.toArray(LinkedList.java:958)
        at com.mcclure.hannah.books.MainActivity.onCreate(MainActivity.java:43)
        at android.app.Activity.performCreate(Activity.java:6374)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2752)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873) 
        at android.app.ActivityThread.access$900(ActivityThread.java:181) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:145) 
        at android.app.ActivityThread.main(ActivityThread.java:6145) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 

1 个答案:

答案 0 :(得分:0)

您正尝试在字符串列表中添加图书:

 String[] array = list.toArray(new String[list.size()]);