我尝试将某些值从活动传递到非活动接收器类以创建通知。我无法理解为什么我会在这个问题上收到错误。我的意思是,我通过上下文,检索它,并相应地使用它。我读了一些关于这个问题的线索,并尽力解决它,但这就是我能走多远。我在这条线上感到恐惧:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
DailyForecastActivity.java
public class DailyForecastActivity extends AppCompatActivity {
private Daily[] mDays;
public static Context contextOfApplication;
@Bind(android.R.id.list)
ListView mListView;
@Bind(android.R.id.empty)
TextView mEmptyTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
ButterKnife.bind(this);
contextOfApplication = getApplicationContext();
GPSTracker gpsTracker = new GPSTracker(this);
TextView mLocationLabel = (TextView) findViewById(R.id.locationLabel);
Intent intent = getIntent();
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
mDays = Arrays.copyOf(parcelables, parcelables.length, Daily[].class);
DayAdapter adapter = new DayAdapter(this, mDays);
mListView.setAdapter(adapter);
mListView.setEmptyView(mEmptyTextView);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String dayOfTheWeek = mDays[position].getDayOfTheWeek();
String condition = mDays[position].getSummary();
String tempMin = mDays[position].getTempMin() + "";
String tempMax = mDays[position].getTempMax() + "";
int icon = mDays[position].getIconId();
String message = String.format("%s Summary: %s", dayOfTheWeek, condition);
Toast.makeText(DailyForecastActivity.this, message, Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("summary", condition);
editor.putString("tempMin", tempMin);
editor.putString("tempMax", tempMax);
editor.putString("dayOfTheWeek", dayOfTheWeek);
editor.putInt("icon", icon);
editor.apply();
}
});
String area = gpsTracker.getSubLocality(this);
String city = gpsTracker.getAdminArea(this);
String country = gpsTracker.getCountryName(this);
mLocationLabel.setText(area + ", " + city + ", " + country);
}
public static Context getContextOfApplication(){
return contextOfApplication;
}
}
Receiver.java
public class Receiver extends BroadcastReceiver{
Context applicationContext = DailyForecastActivity.getContextOfApplication();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
String summary = preferences.getString("summary", null);
String tempMin = preferences.getString("tempMin", null);
String tempMax = preferences.getString("tempMax", null);
String dayOfTheWeek = preferences.getString("dayOfTheWeek", null);
int icon = preferences.getInt("icon", 0);
@Override
public void onReceive(Context context, Intent intent) {
this.applicationContext = context;
PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(icon)
.setContentTitle(dayOfTheWeek + " Weather")
.setContentText(summary + "Temperature: " + tempMax + "/" + tempMin)
.setTicker("Daily Weather");
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
logcat的
java.lang.RuntimeException: Unable to instantiate receiver com.theoc.stormy.Receiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2565)
at android.app.ActivityThread.access$1700(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
at com.theoc.stormy.Receiver.<init>(Receiver.java:42)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2560)
at android.app.ActivityThread.access$1700(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
修改
我解决了NPE错误,但现在我得到了&#34; null&#34;对于我的SharedPreferences值。我在DailyForecastActivity中运行了一个调试,我在那里放置了值,并且那里似乎没有问题。我能够提供我想要的所有价值。看起来我无法检索Receive.java中的SharedPreferences。另外作为旁注,我因某种原因收到通知声音,但根本没有收到任何通知。
答案 0 :(得分:0)
在SharedPreference
onReceive
preferences = PreferenceManager.getDefaultSharedPreferences(context);
当您的BroadcastReceiver
被调用时,您的活动可能为空
答案 1 :(得分:0)
尝试这样做:
首先,通过链接到类
来在清单中实现应用程序<application
android:name = ".App"
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name" >
然后在您的应用程序类中实现以下方法
public class App extends Application {
private static final String TAG = ".App";
private static Context context = null;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
@SuppressWarnings("unused")
public static Context getContext() {
if (context != null) {
return context;
} else {
Log.e(TAG, "App was not successfully created");
throw new Error("App was not successfully created");
}
}
}
答案 2 :(得分:0)
我总是使用以下方式获取我的共享首选项:
context.getSharedPreferences(PREFERENCE_FILENAME, Context.MODE_PRIVATE);
您还可以验证是否在应用程序数据/目录中创建了首选项文件。 请仔细阅读共享首选项在android中的工作原理。
答案 3 :(得分:0)
致电DailyForecastActivity.java
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
并在Receiver.java
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
您要求SharedPreferences
的两个不同的实例。你保存在一个,然后你试图从第二个,你没有保存任何东西,所以你得到null
所有值。你必须联合它并在第一和第二种情况下使用它,例如:
SharedPreferences sharedPref = getPreferences("MyPref", Context.MODE_PRIVATE);
<{1>}和中的
DailyForecastActivity
<{1>}中的,这将导致获得相同的实例。
您也可以尝试使用相同的SharedPreferences sharedPref = context.getPreferences("MyPref", Context.MODE_PRIVATE);
。来自Receiver
的{{1}}来自Context
的{{1}}来自Context
。因此,请在两种情况下使用getActivity()
,或者通过活动中的构造函数中的参数传递Context
。