从 Android 中的 Set<Locale> 获取对象数组的问题

你看到这段代码有什么问题吗?函数执行时出现以下错误:java.lang.NullPointerException: Attempt to invoke interface method java.lang.Object[] java.util.Set.toArray()on a null object reference。我在 Android 7.0 中运行它。


import android.speech.tts.TextToSpeech;

import android.speech.tts.TextToSpeech.OnInitListener;

import java.util.Locale;

import java.util.Set;

import java.util.Arrays;

import android.content.Context;



public static String GetLanguages(Object objcon) {

    Context context = (Context) objcon;

    TextToSpeech tts;


    tts = new TextToSpeech(context, new OnInitListener(){

        @Override

        public void onInit(int status) {


        };

    });


    Set<Locale> loc = tts.getAvailableLanguages();

    Object[] objloc = loc.toArray();

    return Arrays.toString(objloc);


};


茅侃侃
浏览 130回答 2
2回答

POPMUISE

你得到空值,因为TextToSpeech需要时间来初始化。这就是为什么你必须OnInitListener在初始化期间提供实现。tts = new TextToSpeech(context, new TextToSpeech.OnInitListener(){&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onInit(int status) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Now you can use tts&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Set<Locale> loc = tts.getAvailableLanguages();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object[] objloc = loc.toArray();&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; });该方法需要使用 TextToSpeech 作为类变量,因此您需要某种回调,以从GetLanguages方法中获取结果。

Helenr

改用这个:Locale[] locales = Locale.getAvailableLocales();List<Locale> localeList = new ArrayList<Locale>();for (Locale locale : locales) {&nbsp; &nbsp; int res = tts.isLanguageAvailable(locale);&nbsp; &nbsp; if (res == TextToSpeech.LANG_COUNTRY_AVAILABLE) {&nbsp; &nbsp; &nbsp; &nbsp; localeList.add(locale);&nbsp; &nbsp; }}return Arrays.toString(localeList);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java