简体   繁体   中英

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

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.

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM