Android Question What is wrong with this code?

hatzisn

Well-Known Member
Licensed User
Longtime User
Hi everybody,

I am trying to add to the TTSFunctions codemodule the following code to get the available languages of the TTS. The code compiles ok but I get the following error when it runs...

Code:

B4X:
Sub GetListOfAvailableLanguages() As String
    'Requires API 21 and greater
    Dim r As Reflector
    Dim jo As JavaObject
    jo.InitializeStatic(Application.PackageName & ".ttsfunctions")
    Return jo.RunMethod("GetLanguages", Array As Object(r.GetContext))
End Sub


#IF JAVA
    
    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);

    };
    
#End If

Error:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Set.toArray()' on a null object reference

Doesn't it get
the available languages? My android is 7.0.

Thanks in advance...
 

hatzisn

Well-Known Member
Licensed User
Longtime User
Hi,

Thanks for your response. I got it to work with a totally clumsy way... Here is the code:

B4X:
'Get all available languages of the TTS
'Uses Reflection Lib, JavaObject Lib
Sub GetListOfAvailableLanguages() As ResumableSub
    'Requires API 21 (Android 5.0) and above
    'It is called like this:
    'wait for (TTSFunctions.GetListOfAvailableLanguages) Complete (sLangs As String)
    'manipulate the sLangs variable
    Dim r As Reflector
    Dim jo As JavaObject
    jo.InitializeStatic(Application.PackageName & ".ttsfunctions")
    jo.RunMethod("InitTTS", Array As Object(r.GetContext))
    Sleep(4000)
    Return jo.RunMethod("GetLanguages", Null)
End Sub


#IF JAVA
    
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 sLangs;
public static TextToSpeech tts;


public static void InitTTS(Object objcon) {
    Context context = (Context) objcon;
    

    tts = new TextToSpeech(context, new OnInitListener(){
        @Override
        public void onInit(int status) {

        };
    });
};


public static String GetLanguages() {
    Set<Locale> loc = tts.getAvailableLanguages();
    Object[] objloc = loc.toArray();
    sLangs = Arrays.toString(objloc);
    return sLangs;
};
    
#End If
 
Upvote 0
Top