I am trying to pass data through shared preferences from a Service class to a Fragment class.
I have encountered no syntax error, but there is a logic error as I do not get the text view updated with the updated step counter I want in StepsFragment.
I am running a step counter in StepsService.java
and I'm trying to pass the information to StepsFragment.java
.
I have tried these following solutions:
Access shared preference from a service
Can I get data from shared preferences inside a service?
This is my code in StepsService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true){
// ------- code for task to run
SharedPreferences.Editor editor = getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
editor.putString("DeviceToken",String.valueOf(stepsCounter));
editor.apply();
addNotification(String.valueOf(stepsCounter));
// ------- ends here
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
return START_NOT_STICKY;
}
This is my code in StepsFragment.java
public void startService(View view) {
Intent serviceIntent = new Intent(getActivity(),StepsService.class);
getActivity().startService(serviceIntent);
SharedPreferences prefs = this.getActivity().getSharedPreferences("DeviceToken", MODE_PRIVATE);
String deviceToken = prefs.getString("DeviceToken", null);
tv_steps.setText(deviceToken);
}