我正在尝试在非 Activity 类(class)中使用 Toast。为此,我正在尝试以下操作:
//Method to get all books from database
public List<Book> getAllBooks() {
List<Book> books = new LinkedList<Book>();
Context context = null;
// 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());
} else {
Toast.makeText(context, "No books in database", Toast.LENGTH_LONG).show();
}
....
但是 context
上有一个黄色警告标记,表示Argument 'context' might be null
这是预期的,因为它被初始化为 null。在这种情况下如何使用上下文而不导致程序崩溃?该方法是从 Activity 的 onCreate()
方法调用的。我需要显示此消息。
最佳答案
如果您从 Activity 的 onCreate
调用 getAllBooks
,则只需传递 Activity 实例即可作为上下文。
public List<Book> getAllBooks(Context context) {
....
}
在 Activity 类中:
public void onCreate(Bundle savedInstanceState)
{
... getAllBooks(this); ....
}
关于java - 如何摆脱 Toast 警告中的 "Argument ' context' might be null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27646235/