我是Android工作室的初学者。我手头有一个任务,我应该使用包含选项的微调控件来从books.db中获取数据库记录,例如具有最高和最低值的记录,记录计数等。 下面是列出详细信息的Main类和SQLHelper类。 每次我尝试运行代码时,我都会收到这个Null指针异常。我确实尝试了一切,但似乎没有任何效果!
有人可以帮忙吗?
主要类
package com.example.amrapali.bookreviews;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements OnClickListener, OnItemSelectedListener {
SqlHelper db;
boolean blnFlag=false;
private String tag = "My Name Is:";
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(tag, "Amrapali");
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
SqlHelper db = new SqlHelper(this);
/** CRUD Operations **/
// add Books
//db.addBook(new Book("Professional Android 4 Application Development", "Reto Meier"));
//db.addBook(new Book("Beginning Android 4 Application Development", "Wei-Meng Lee"));
//db.addBook(new Book("Programming Android", "Wallace Jackson"));
//db.addBook(new Book("Hello, Android", "Wallace Jackson"));
// get all books
List<Book> list = db.getAllBooks();
ListView listContent = (ListView) findViewById(R.id.list);
List<Book> books = new ArrayList<Book>();
books=db.getAllBooks();
//get data from the table by the ListAdapter
//ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, books);
//listContent.setAdapter(customAdapter);
//Book updateBook = list.get(3);
// Spinner element
Spinner spinner;
// Spinner element
spinner = (Spinner) findViewById(R.id.spinner1);
// Spinner Drop down element items (some list you build)
List<String> blist = new ArrayList<String>();
blist.add(0,"Select Analytics...");
blist.add(1,"Get Highest Rated Title(s)");
blist.add(2,"Get Lowest Rated Title(s)");
blist.add(3,"Get Record Count");
blist.add(4,"Retrieve Title(s) with Android 4");
// Creating adapter for spinner, pass your list into the constructor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, blist);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(R.layout.myspinner);
// attaching data adapter to spinner
spinner.setAdapter(adapter);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
} //end onCreate() method
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// TODO Auto-generated method stub
if(blnFlag) //spoof message from displaying initially
{
if(position==1)
{
String condition = parentView.getItemAtPosition(position).toString();
Toast.makeText(this,"Highest Rating = " + db.getHighestRating(condition), Toast.LENGTH_LONG).show();
}
//get query result for Highest rated title(s)
//display query result(s) in a Toast message
if(position==2) {
String condition = parentView.getItemAtPosition(position).toString();
Toast.makeText(this,"Lowest Rating = " + db.getLowestRating(condition), Toast.LENGTH_LONG).show();
//get query result for Lowest rated title(s)
//display query result(s) in a Toast message
}
if(position==3)
{
String condition = parentView.getItemAtPosition(position).toString();
Toast.makeText(this,"Total Number of Records = " + db.getCount(condition),
Toast.LENGTH_LONG).show();
}
}
blnFlag=true;
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// TODO Auto-generated method stub
}
@Override
public void onClick(View v) {
}
// update one book
//int j = db.updateBook(updateBook,"Hello, Android","Ben Jackson");
// delete one book
//db.deleteBook(list.get(0));
// get all books
//db.getAllBooks();
//Log.d("The book count is ", Integer.toString(db.getIds(updateBook)));
}
SQLHelper类:
package com.example.amrapali.bookreviews; /**
* Created by Amrapali on 4/3/2016.
*/
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
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.example.amrapali.bookreviews.Book;
public class SqlHelper extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 4;
// Database Name
private static final String DATABASE_NAME = "BookDB";
// 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";
public SqlHelper(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);
String upgradeQuery = "ALTER TABLE books ADD COLUMN rating TEXT";
String upgradeQuery2 = "ALTER TABLE books ADD COLUMN imagename TEXT";
if (oldVersion == 3 && newVersion == 4){
db.execSQL(upgradeQuery);
db.execSQL(upgradeQuery2);
}
}
/*CRUD operations (create "add", read "get", update, delete) */
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
// 4. Close dbase
db.close();
}
// 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));
book.setRating(cursor.getString(3));
book.setImageName(cursor.getString(4));
// 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, 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", 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 dbase
db.close();
Log.d("UpdateBook", book.toString());
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());
}
public int getIds(Book book){
String selectQuery = "Select id from books";
SQLiteDatabase database = this.getReadableDatabase();
Cursor c = database.rawQuery(selectQuery, null);
c.moveToFirst();
int total = c.getCount();
return total;
}
public Set<String> getTitle()
{
Set<String> set = new HashSet<String>();
String selectQuery= "select * from " + TABLE_BOOKS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
if
(cursor.moveToFirst())
{
do
{
set.add(cursor.getString(1));
//get title column's value
}
while
(cursor.moveToNext());
}
cursor.close();
db.close();
return
set;
}
public int getCount(String condition) {
int total=0;
if (condition=="Get Record Count")
{
String selectQuery = "Select Count(*) from" + TABLE_BOOKS;
SQLiteDatabase database = this.getReadableDatabase();
Cursor c = database.rawQuery(selectQuery, null);
c.moveToFirst();
total= c.getCount();
}
return total;
}
public StringBuilder getHighestRating(String condition) {
StringBuilder s = null;
if (condition == "Get Highest Rated Title(s)") {
s = new StringBuilder();
String selectQuery = "select max(rating) from " + TABLE_BOOKS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
s.append(cursor.getString(3)); //get rating's value
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
}
return s;
}
public StringBuilder getLowestRating(String condition) {
StringBuilder s = null;
if (condition == "Get Highest Rated Title(s)") {
s = new StringBuilder();
String selectQuery = "select min(rating) from " + TABLE_BOOKS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
s.append(cursor.getString(3)); //get rating's value
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
}
return s;
}
}
答案 0 :(得分:1)
您尚未初始化全局的SqlHelper数据库。这就是为什么你得到这个错误。
更改此
SqlHelper db = new SqlHelper(this);
到
db = new SqlHelper(this);