0

I have tried to make a service to recognize the user's current activity. But this code crashes everytime.

It throws exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.location.DetectedActivity com.google.android.gms.location.ActivityRecognitionResult.getMostProbableActivity()' on a null object reference at com.always_in_beta.ecodrive.service.UserTrackService.detectActivity(UserTrackService.java:51) at com.always_in_beta.ecodrive.service.UserTrackService$1.run(UserTrackService.java:27)

The code is:

public class UserTrackService extends Service {

    public Handler handler = null;
    public Runnable runnable = null;
    int count = 0;
    public Context context = this;
    public Intent intentt;

    @Override
    public void onCreate() {
        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                detectActivity();
            }
        };
        handler.postDelayed(runnable, 4000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(context, "Service stopped", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        intentt = intent;
        return null;
    }

    public void detectActivity() {
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intentt);
        DetectedActivity activity = result.getMostProbableActivity();
        Toast.makeText(context, activity.toString(), Toast.LENGTH_SHORT).show();
        Log.d("tag_tag_tag", activity.toString());
    }
}

1 Answers1

0

ActivityRecognitionResult#extractResult(android.content.Intent)

Returns an ActivityRecognitionResult, or null if the intent doesn't contain an ActivityRecognitionResult.

So, according to your null pointer stacktrace, that's expected because you can't run getMostProbableActivity() on a null.

TWL
  • 6,228
  • 29
  • 65
  • 1
    I want to detect the activity of the user on a regular interval, but am unable to implement. Can you please tell me where to start? –  Feb 02 '19 at 17:11
  • @user10445346 did you find a solution? – Arjun Oct 19 '21 at 10:44