Android:MainActivity中的方法工作正常,通过BroadcastReceiver类在MainActivity中运行相同的方法会给出空指针

时间:2018-12-01 01:16:34

标签: android broadcastreceiver alarmmanager

所以我的MainActivity中有此方法,它可以正常工作。

public void DailyQuoteDatabaseAccess(){

SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase SqlDb = sqLiteOpenHelper.getReadableDatabase();
String rawQuery = "SELECT * FROM dailyQuoteTable ORDER BY RANDOM() LIMIT 1";
Cursor cursor = SqlDb.rawQuery(rawQuery, null);
DailyQuoteCursorAdapter DQCursorAdapter = new DailyQuoteCursorAdapter(this, cursor);
this.mDailyQuoteListView.setAdapter(DQCursorAdapter);
}

但是,当我尝试从BroadcastReceiver类运行它时,可以访问它,但应用程序崩溃,并且在 log cat 中出现以下错误:

Process: com.myapps.dailyquotes, PID: 15024
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.myapps.dailyquotes.TodaysQuoteAlarmReceiver@d63089d
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_52497(LoadedApk.java:1323)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.$m$7(Unknown Source:4)
at android.app.-$Lambda$aS31cHIhRx41653CMnd4gZqshIQ.run(Unknown Source:39)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:109)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:129)
at com.myapps.dailyquotes.MainActivity.DailyQuoteDatabaseAccess(MainActivity.java:403)

这是我的BroadcastReceiver班:

package com.myapps.dailyquotes;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class TodaysQuoteAlarmReceiver  extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity mainActivity = new MainActivity();
mainActivity.DailyQuoteDatabaseAccess();

}
}

DailyQuoteDatabaseAccess的{​​{1}}方法中突出显示的行是这一行:

MainActivity

我从MainActivity onCreate调用它...它链接到TodaysQuoteAlarmReceiver:

SQLiteOpenHelper sqLiteOpenHelper = new SQLiteAssetHelper(this, DATABASE_NAME, null, DATABASE_VERSION);

1 个答案:

答案 0 :(得分:2)

从未使用new运算符创建Android中的活动类。它们是在实现目标时由系统创建的。如果按照活动方式创建活动,则该活动将没有正确的上下文设置。这就是为什么在创建SQLiteAssetHelper时会得到一个空指针。