how to get string of EditTextPreference and use it in notification.setContent and use it as summery in android?

144 views Asked by At

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

1

There are 1 answers

1
Bertrand Martel On

sharedPreferences is undefined when setupNotification() is called

Initialize your sharedPreferences in onCreate() :

@Override
public void onCreate() {
    super.onCreate();
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}