[英]How to return a Table row in Android SQLite
I want for the time being just to return a row of my SQLite Table in my Android app(In Logcat). 我暂时只想在我的Android应用程序中返回一行SQLite Table(在Logcat中)。
I inserted a sample code based on SQlite tutorials I have read as follows: 我插入了基于SQlite教程的示例代码,内容如下:
1)I inserted that code into my main activity: 1)我将该代码插入到我的主要活动中:
MySQLiteHelper db = new MySQLiteHelper(this);
// 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();
2)I created a new class named MySQLiteHelper.java and I pasted that code: 2)我创建了一个名为MySQLiteHelper.java的新类,并粘贴了该代码:
package com.qualcomm.QCARSamples.ImageTargets;
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;
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){
//for logging
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
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, //table name
KEY_ID+" = ?", // selections
new String[] { String.valueOf(book.getId())}); //selections args
// 3. close
db.close();
//log
Log.d("deleteBook", book.toString());
}
}
3)Finally I created a new class named Book.java including that code: 3)最后,我创建了一个名为Book.java的新类,其中包括该代码:
package com.qualcomm.QCARSamples.ImageTargets;
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;
}
// getting ID
public int getId(){
return this.id;
}
// getting name
public String getAuthor(){
return this.author;
}
// getting name
public String getTitle(){
return this.title;
}
// setting id
public void setId(int id){
this.id = id;
}
// setting name
public void setTitle(String title){
this.title = title;
}
// setting name
public void setAuthor(String author){
this.author = author;
}
//getters & setters
@Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", author=" + author
+ "]";
}
}
In my code so far I am able to view my three rows of my SQLite Table in Logcat. 到目前为止,在我的代码中,我可以在Logcat中查看我的SQLite表的三行。
How do I return for example the 1st or the 2nd row of my SQLite Table? 例如,如何返回我的SQLite表的第一行或第二行?
You can try http://developer.android.com/reference/android/database/Cursor.html#moveToPosition%28int%29 but without an order by in your query (and a very consistent order by), this might not give you the same row every time you ask for says move to 2nd position. 您可以尝试http://developer.android.com/reference/android/database/Cursor.html#moveToPosition%28int%29,但查询中没有排序依据(并且排序依据非常一致),这可能无法给您每当您要求说同一行时,移至第二位。 Even then, as the table gets updated, this keeps changing. 即使那样,随着表的更新,它也在不断变化。
You can just query through Your table like this: 您可以像这样通过您的表进行查询:
Cursor cursor =
db.query(TABLE_BOOKS, new String[] {KEY_ID,KEY_TITLE,KEY_AUTHOR },
null, null, null, null, null);
with this, You get the complete entries of Your table. 这样,您将获得表的完整条目。 And then, it depends on You what exactly You want. 然后,这取决于您的确切需求。 If You want just a certain line: 如果您只想要某一行:
String currentTitle="";
String currentAuthor="";
int rows = Cursor.getCount();
Cursor.moveToFirst();
for(int i=0;i<rows;i++){
int bookId = c.getInt(0);
if(bookId==id){
//now You got the entry and can get all informations You want
currentTitle = cursor.getString(1);
currentAuthor = cursor.getString(2);
c.moveToNext();
}
}
It is only an example to know how You have to do it. 这只是了解您必须执行的操作的一个示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.