I want to get username from my app user in setting page with EditTextPreference
and use it in Notification
. But it shows an error:
xml file:
<EditTextPreference
android:key="editpref_id"
android:title="@string/pref_edittext_id"
android:summary="@string/pref_edittext_id_summery"
android:dialogTitle="@string/pref_edittext_id_summery" />
and my class:
public class TimerService extends Service {
public SharedPreferences sharedPreferences;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
return super.onStartCommand(intent, flags, startId);
}
private void setupNotification() {
notification = new NotificationCompat.Builder(this)
.setContentText("Dear" + sharedPreferences.getString("editpref_id"," "));
// ...
}
and error:
java.lang.RuntimeException: Unable to start service with Intent { java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference
also I want to use it as summery of EditTextPreference
.
So how can I solve them? please answer me.Thanks
sharedPreferences
is undefined whensetupNotification()
is calledInitialize your
sharedPreferences
inonCreate()
: