0

After updating to Android Studio 3.0, I'm getting this warning every time I try to use vibrate():

Method invocation 'vibrate' may produce 'java.lang.NullPointerException'

Here's my code:

package com.gavinsappcreations.vibratortest;

import android.content.Context;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(100);

    }
}

I've included the permission:

<uses-permission android:name="android.permission.VIBRATE"/>

Also, the code works on my device.

Gavin Wright
  • 3,124
  • 3
  • 14
  • 35

1 Answers1

5

You can just remove the warning doing.

if(vibrator != null) {
   vibrator.vibrate(100);
}

Check Nikolas's comment.

Djory Krache
  • 347
  • 4
  • 9
  • Thanks! I was just confused because I don't recall this warning ever showing up in prior Android Studio versions. – Gavin Wright Oct 26 '17 at 15:05
  • 2
    While the not null check fixes the warning, the assumption about "doesn't have a VIBRATOR_SERVICE" is plain wrong. Your IDE just performs static code analysis, and does so more restrictive then your former IDE might have. – Nikolas Oct 26 '17 at 15:11
  • Effectively, you're right. After reading the documentation of this object, there is a method hasVibrator() which implies that this object is never null. – Djory Krache Oct 26 '17 at 15:19
  • 1
    Although, I have a developer console error log that says NullPointerException when using vibrate, on a Galaxy S8+, which definitely has a vibrator. Maybe there's a setting to restrict vibration access? – behelit Mar 26 '18 at 22:26
  • I got such a crash from Samsung Galaxy Tab A (2016) on Android 8.1 (SDK 27), so I've set null check there. – djdance Jun 17 '21 at 09:35