【问题标题】:"null object reference error" when trying to use TTS尝试使用 TTS 时出现“空对象引用错误”
【发布时间】:2020-07-26 21:32:03
【问题描述】:

我正在尝试使用 Text-To-Speech 但收到以下错误:

2020-07-26 22:58:51.876 15964-15964/ch.yourclick.kitt E/AndroidRuntime: 致命异常: main 进程:ch.yourclick.kitt,PID:15964 java.lang.NullPointerException: 尝试调用虚拟方法'int android.speech.tts.TextToSpeech.speak(java.lang.String, int, java.util.HashMap)' 在空对象引用上 在 ch.yourclick.kitt.​​MainActivity.speak(MainActivity.java:61) 在 ch.yourclick.kitt.​​fragments.GeneralFragment$1.onClick(GeneralFragment.java:59)

MainActivity.java

package ch.yourclick.kitt;

import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import java.util.Locale;
import ch.yourclick.kitt.ui.main.SectionsPagerAdapter;

public class MainActivity extends AppCompatActivity {
    public TextToSpeech tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        FloatingActionButton fab = findViewById(R.id.fab);

        // Text to speech
        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) { // <-- I never get into that if statement
                    int result = tts.setLanguage(Locale.getDefault());
                    // Language is not supported
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.e("TTS", "Language not supported");
                    }
                }
                else {
                    Log.e("TTS", "" + status); // Returns -1
                    Log.e("TTS", "" + TextToSpeech.SUCCESS); // Returns 0
                }
            }
        });

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    /**
     * Speak
     */
    public void speak() {
        String text = "Hello";
        tts.speak(text, TextToSpeech.QUEUE_ADD, null);
    }

    /**
     * Turn off
     */
    @Override
    public void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

}

GeneralFragment.java

package ch.yourclick.kitt.fragments;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import ch.yourclick.kitt.MainActivity;
import ch.yourclick.kitt.R;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link GeneralFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GeneralFragment extends Fragment {

    public GeneralFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment General.
     */
    // TODO: Rename and change types and number of parameters
    public static GeneralFragment newInstance() {
        GeneralFragment fragment = new GeneralFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_general, container, false);
        Button hello = view.findViewById(R.id.hello);
        
        hello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity mainActivity = new MainActivity();
                mainActivity.speak();
            }
        });
        return view;
    }


}

tts 似乎返回 null 但为什么呢?

【问题讨论】:

    标签: java android


    【解决方案1】:

    考虑您帖子中的以下两个 sn-ps:

    // Code found in onCreate(...) in MainActivity.java
    tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        // A bunch of code here
    }
    

    和

    // Code found in an OnClickListener in GeneralFragment.java
    MainActivity mainActivity = new MainActivity();
    mainActivity.speak();
    

    您可能得到一个NullPointerException,因为当您调用mainActivity.speak() 时tts 为空。

    虽然您的意图是好的,但未按计划工作的原因是您实际上正在创建一个尚未经过适当生命周期步骤的 MainActivity 的新实例,这意味着从未调用过 onCreate(...)因此tts 从未被分配...在那个特定的活动实例中。值得一提的是,您的片段正在运行的“真实”活动实例应该正确设置它。

    那么,让它工作的最快方法是什么?好吧,我会说获取当前活动,如果可能,将其转换为 MainActivity,然后尝试在该实例上调用 speak():

    hello.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final Activity activity = getActivity();
            if (activity instanceof MainActivity) {
                ((MainActivity) activity).speak();
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多