Text to speech in fragment

假装没事ソ 提交于 2021-01-28 21:28:36

问题


Getting errors on, sorry only beginner. All help would be great.

  05-31 21:49:16.077: E/AndroidRuntime(655): FATAL EXCEPTION: main
  05-31 21:49:16.077: E/AndroidRuntime(655): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appal.song/com.appal.song.MainActivity}: java.lang.NullPointerException
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.os.Handler.dispatchMessage(Handler.java:99)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.os.Looper.loop(Looper.java:137)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.app.ActivityThread.main(ActivityThread.java:4424)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at java.lang.reflect.Method.invokeNative(Native Method)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at java.lang.reflect.Method.invoke(Method.java:511)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at dalvik.system.NativeStart.main(Native Method)
  05-31 21:49:16.077: E/AndroidRuntime(655): Caused by: java.lang.NullPointerException
  05-31 21:49:16.077: E/AndroidRuntime(655):    at com.appal.song.Fragment_1.onCreateView(Fragment_1.java:33)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1133)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.app.Activity.performStart(Activity.java:4475)
  05-31 21:49:16.077: E/AndroidRuntime(655):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1929)
  05-31 21:49:16.077: E/AndroidRuntime(655):    ... 11 more

Here's full code, any help would be great, thanks, only beginner sorry. Trying to make text then next to it make a button that will repeat the text in speech.

 public class Fragment_1 extends Fragment implements OnClickListener, OnInitListener{
private TextToSpeech txts;
private static final String TAG = "TextToSpeechDemo";
private static final int MY_DATA_CHECK_CODE = 1234;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_1,
            container, false);


        Button btnAdd = (Button) getView().findViewById(R.id.button1);
        btnAdd.setOnClickListener(this);
        btnAdd.setEnabled(false);

        TextView txt = (TextView) getView().findViewById(R.id.textView1);
        txt.setText("OnCreate");

        // Fire off an intent to check if a TTS engine is installed
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        TextView txt = (TextView) getView().findViewById(R.id.textView1);
        if (requestCode == MY_DATA_CHECK_CODE)
        {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
            {
                // success, create the TTS instance
                txt.setText("Done result");
                txts = new TextToSpeech(this, this);
                txts.setLanguage(Locale.US);
                Button btnAdd = (Button) getView().findViewById(R.id.button1);
                btnAdd.setEnabled(true);

            }
            else
            {
                txt.setText("Missing");
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(
                        TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }

    @Override
    public void onDestroy()
    {
        // Don't forget to shutdown!
        if (txts != null)
        {
            txts.stop();
            txts.shutdown();
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {

        TextView txt = (TextView) getView().findViewById(R.id.textView1);
                txt.setText("Click");

        String myText1 = "hello";
        String myText2 = "bye";
        txts.speak(myText1, TextToSpeech.QUEUE_FLUSH, null);
        txts.speak(myText2, TextToSpeech.QUEUE_ADD, null);
    }
    @Override
    public void onInit(int status) {
        TextView txt = (TextView) getView().findViewById(R.id.textView1);
        txt.setText("status 0");
        if (status == TextToSpeech.SUCCESS) {
                txt.setText("status 1");
            int result = txts.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA ||
                result == TextToSpeech.LANG_NOT_SUPPORTED) {
                txt.setText("status 2");
            } else {
                Button btnAdd = (Button) getView().findViewById(R.id.button1);
                btnAdd.setEnabled(true);
                txt.setText("status 3");
            }
            } else {
            txt.setText("status 4");
            Log.e(TAG, "Could not initialize TextToSpeech.");
        }
        return view;
    }
}

回答1:


As I said in my comment: using this while in a Fragment refers to that Fragment's instance. Fragments aren't Contexts, hence the compile time error.

To make a new TextToSpeech Object, you should use:

txts = new TextToSpeech(getActivity(), this);

Activities extend Context, so that should fix this compile-time error.

Another potential problem: for the Buttons, TextViews, etc that you are setting up onCreateView() you should be using view.findViewById() instead of getView().findViewById() (but only for the Views you're setting up in onCreateView(). The rest of the getView() calls should be fine).

It's one less method call, and getView() probably returns null until onCreateView() returns the inflated View.

Lastly, onCreateView() needs to return a View, so just before its closing brace, add:

return view;

The method with appropriate changes:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_1,
            container, false);


        Button btnAdd = (Button) view.findViewById(R.id.button1);
        btnAdd.setOnClickListener(this);
        btnAdd.setEnabled(false);

        TextView txt = (TextView) view.findViewById(R.id.textView1);
        txt.setText("OnCreate");

        // Fire off an intent to check if a TTS engine is installed
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

        return view;
    }



回答2:


You can initialize the class inside of TextToSpeech.OnInitListener() method.

// variable declaration
TextToSpeech tts;

// TextToSpeech initialization, must go within the onCreateView method
tts = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() {
 @Override
 public void onInit(int i) {
  if (i == TextToSpeech.SUCCESS) {
   int result = tts.setLanguage(Locale.US);
   if (result == TextToSpeech.LANG_MISSING_DATA ||
    result == TextToSpeech.LANG_NOT_SUPPORTED) {
    Log.e("TTS", "Lenguage not supported");
   }
  } else {
   Log.e("TTS", "Initialization failed");
  }
 }
});

// method call
@Override
public void onClick(View v) {
  speak();
}

private void speak() {
 tts.speak("Text to Speech Test", TextToSpeech.QUEUE_ADD, null);
}

@Override
public void onDestroyView() {
 if (tts != null) {
  tts.stop();
  tts.shutdown();
 }
 super.onDestroyView();
}

taken from: Text to Speech Youtube Tutorial



来源:https://stackoverflow.com/questions/16866173/text-to-speech-in-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!