1

I have used the strategy suggested in this previous thread to create a custom vibrator in a non-activity class.

import android.content.Context;
import android.os.Vibrator;
public class IntensityVibrator {
    private static IntensityVibrator iv;
    private Vibrator vib= null;
    private Context context;
    private Vibrator getVibrator(){
        if(vib == null){
            vib = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        }
        return vib;
    }

    
    public static IntensityVibrator getManager(<an_activity> context) {
        if(iv == null){
            iv = new IntensityVibrator();
        }
        iv.setContext(context);
        return iv;
    }
    
    
    private void setContext(Context context){
        this.context = context;
    }

    public void regularVibrate(long millis){
    vib.vibrate(millis);
    }
    }

I'm using it in the other class this way:

vib = (IntensityVibrator) IntensityVibrator.getManager(<an_activity>);

The class in which I create the vib object is also a non-activity class. Therefore I pass the context via an_activity context.

The app crashes the times when the last method is called. Debugging shows that the code works fine up until the vib.vibrate(millis) is called. Can you guess what could be the problem here?

Community
  • 1
  • 1

1 Answers1

2

It seems to me you never initialize your vib class variable, as a result it is null and you get a NullPointerException when calling regularVibrate Your private getVibrator method, which initialize vib, is never called : you should call it in getManager, just after calling setContext.

Pierre Rust
  • 2,474
  • 18
  • 15