Question

I'm having a class that implements RecognitionListener like this:

public class listener implements RecognitionListener

I wanted to show a alertdialog and use the vibrator but this isn't possible because I need to provide a context what I don't have.

My alertdialog code was like this:

    new AlertDialog.Builder(this)
        .setTitle("dd")
        .setMessage("aa")
        .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 

            }
         })
         .show();

But the AlertDialog.Builder(this) wants a context, the same problem with my vibrator code:

v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

The getSystemService method isn't available.

My code that starts the class:

sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);        
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");

intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5); 
sr.startListening(intent);

Whats the best way to solve this?

Was it helpful?

Solution

A constructor that takes a context object would work well here.

Declare a context variable

private Context mContext;

Then declare a constructor that takes a context

public listener(Context context){
    super();
    mContext = context
}

When you need a context use mContext instead of this.

When you create the listener pass the current context

sr.setRecognitionListener(new listener(this));

Also as an aside in Java class names should always start with a capital so your class should be Listener not listener

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top