我已经在SQLite中存储了书籍的详细信息。但是当我点击MainActivity中的按钮时,我不知道如何检索它。有人可以帮忙吗?还有如何在列表视图中显示它? 这是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 title){
this.title = title;
}
// getting author
public String getAuthor(){
return this.author;
}
// setting author
public void setAuthor(String author){
this.author = author;
}
}
这是MySQLiteHelper.java
package com.hmkcode.android.sqlite;
import java.util.LinkedList;
import java.util.List;
import com.hmkcode.android.model.Book;
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 java.util.ArrayList;
import java.util.List;
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());
}
}
这是MainActivity.java
package com.hmkcode.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.List;
import com.hmkcode.android.model.Book;
import com.hmkcode.android.sqlite.MySQLiteHelper;
import android.os.Bundle;
import android.util.Log;
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(0));
}
}
}
答案 0 :(得分:0)
你可以使用cursorAdapter在listview中显示它们,这里有一个很好的教程http://www.vogella.com/articles/AndroidSQLite/article.html
答案 1 :(得分:0)
当您从SQLite读取数据时,一旦操作完成,关闭Cursor非常重要。
添加列表视图的步骤。
您缺少在oncreate方法中使用适配器。
其他一切,我认为你是对的。
将res / layout文件夹中的main.xml布局文件更改为以下内容。布局有一个ListView,用于显示现有的书籍。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
修改活动类。 (扩展列表活动而不是活动)
public class MainActivity extends ListActivity {
@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();
ArrayAdapter<Book> adapter = new ArrayAdapter<Book>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
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(0));
}
} }