How to call function of one Activity from other Activity or service?

Go To StackoverFlow.com

0

I need to call some functions from one activity. But when I do that, it gives null pointer... error. I am using this as my example, http://www.javacodegeeks.com/2010/09/android-text-to-speech-application.html

Please see line 38, says tts.speak(text, TextToSpeech.QUEUE_ADD, null);

So, if I have changed the code like this...

public class TTA extends Activity implements OnInitListener {

... ... ... ...

 public void MYCall()
 {
 tts.speak(text, TextToSpeech.QUEUE_ADD, null);
 }

... ... ...
}

and then call this my call from another activity, like this,

TTA tta = new TTA();
tta.MYCall();

Shouldn't it work? It doesnt, however when MYCall() is called from within the TTA class it works.

Thank you for your help.

2012-04-05 16:29
by Droid-Bird


2

It's hard to tell what's going on, as you haven't provided much code to examine.

Are you doing set-up for the text-to-speech object in Activity lifecycle methods? Those will not get called if you simply instantiate the Activity using new TTA(), so most likely your Text-To-Speech object isn't yet correctly initialized.

However: I would suggest re-arranging your code so that Text-To-Speech related methods are not coupled with a particular Activity, since you'll be using it in multiple places.

2012-04-05 21:50
by Jason LeBrun


0

You cannot call speak() or tta.MYCall() until onInit() is called.

Therefore, running your two lines of code is not likely to work all the time.

You need something like this or re-arrange your code:

TTA tta = new TTA();
while (!tta.isInitialized())
{
  try
  {
  Thread.sleep(100);
  }
  catch (InterruptedException e)
  {}
}
tta.MYCall();
2012-04-06 08:23
by gregm
Ads