java - 如何摆脱 Toast 警告中的 "Argument ' context' might be null"

标签 java android

我正在尝试在非 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/

相关文章:

java - struts2 token 错误struts.token和struts.token.name

java - 如何访问另一个对象中的 Android Activity?

java - getTime()(Date 中的一个方法)在 joda.time.LocalDate 中的等效项是什么?

android - 在移动应用程序中使用分析有哪些道德问题?

c# - 如何将 ServiceStack 客户端与 Xamarin.Android 独立许可证一起使用

java - 如何限制传输速度?

java - 使用 Maven 时,Derby 给出 ClassNotFoundException : org. apache.derby.jdbc.EmbeddedDriver

java - 如何在 Play Framework 的表单助手中隐藏标签?

java - 在自定义 View 中绘制描边形状

android - 如何在android中存储具有可变数量属性的数据