0

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);
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Jim Ng
  • 91
  • 1
  • 4
  • 15

1 Answers1

0

In your Fragment you call startService() and immediate after that you read the SharedPreferences. This won't work. The call to startService() is asynchronous. It basically just requests that Android start the Service. This will happen at some time in the future, but definitely NOT immediately.

It will take some time for the Service to be started and for the SharedPreferences to be updated.

You could have your Service send a broadcast Intent when it updates the SharedPreferences and your Fragment or Activity could register to be notified of this broadcast Intent and use that as a trigger to update the View.

Or you could simply wait some time before checking the SharedPreferences.

David Wasser
  • 93,459
  • 16
  • 209
  • 274