UtteranceProgressListener won't call the functions - java

I am trying to make a speech powered app, however I have run into a major problem.
My UtteranceProgressListener Class will not call any of the given methods regardless of where I place the Speak method.
Here is my code:
This is my OnCreate Method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
voiceBtn = (Button) findViewById(R.id.startListeningBtn);
voiceBtn.setEnabled(false);
textToSpeech = new TextToSpeech(mContext,new botListener());
}
This is the OnInitListner Imeplementation
public class botListener implements TextToSpeech.OnInitListener{
#Override
public void onInit(int i) {
if(i == TextToSpeech.SUCCESS)
{
int s = textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
Toast.makeText(getApplicationContext(),"Done Speaking",Toast.LENGTH_SHORT).show();
}
#Override
public void onDone(String s) {
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
}
#Override
public void onError(String s) {
Toast.makeText(getApplicationContext(),"Done Speaking",Toast.LENGTH_SHORT).show();
}
});
Log.d(TAG,String.valueOf(s));
int result = textToSpeech.setLanguage(Locale.ENGLISH);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Log.e(TAG,"Language not supported");
Intent installLanguage = new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installLanguage);
}
Log.d(TAG,"Started Voice Speaker");
}
else{
Log.e(TAG,"initialization failed");
}
}
}
Now, when I press the button, the event that fires is:
public void initVoiceRecog(View v){
//Toast.makeText(mContext,"Clicked",Toast.LENGTH_SHORT).show();
Speak("hello","1");
// does some other things here after that
}
private void Speak(String text,String identifierID){
if(Build.VERSION.SDK_INT>21) {
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,identifierID);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, params, identifierID);
}
else{
// ttsMap is a HashMap
ttsMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,identifierID);
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,ttsMap );
}
}
My Question is, after saying hello, it does not fire the OnStart() or the OnError() or the OnDone() methods. Why is this happening?
I tried with the deprecated setOnUtteranceListner() as well, same result. It does not fire any of the methods, the Toasts don't show up.
Please tell a fix or a workaround for this.
The Devices I tried on are:
API 19 Micromax Canvas Nitro
API 21 Samsung S4
API 23(Marshmellow) ASUS Zenfone

I finally figured out why the callbacks were not working. Turns out, they were working and calling on a separate thread. So to execute the normal functionality, call the functions in the 'Activity.this.RunOnUiThread' and put this in the call back fuctions.

Related

UtteranceProgressListener not called

I'm trying to take some action after a TextToSpeech object in my Android app finishes speaking a sentence, but my UtteranceProgressListener.onDone() method is never called. I tried many things, including the suggestions from this post, but nothing has worked. Relevant code from my app is posted below. The TextToSpeech object correctly speaks the sentence I give it, but none of the callback functions in UtteranceProgressListener are called. Can someone please help me identify what's wrong? For example, should the utterance ID I provide to the TextToSpeech.speak() function need to be in some special format that I'm missing?
mtts = new TextToSpeech(myAct, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
mtts.setLanguage(Locale.US);
}
}
});
mtts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onDone(String utteranceId) {
Toast.makeText(myAct, "OnDone called", Toast.LENGTH_LONG).show();
}
#Override
public void onError(String utteranceId) {
Toast.makeText(myAct, "OnError called", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(String utteranceId) {
Toast.makeText(myAct, "OnStart called", Toast.LENGTH_LONG).show();
}
});
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
myAct.mtts.speak(myText, TextToSpeech.QUEUE_FLUSH, params, "MyID");
Look at logcat, your code has probably fired: android.view.ViewRootImpl$CalledFromWrongThreadException
If you want to do some GUI-thread stuff, use handler and runnable like this:
public void onDone(String utteranceId) {
Log.v(TAG, "Speaking done"); // this is OK
// This is GUI-thread part
final View v = findViewById(R.id.txtStatus);
v.getHandler().post(new Runnable() {
#Override
public void run() {
txtStatus.setText("Speaking done");
}
});
}
And to start TTS speaking:
tts.speak("bla bla bla", TextToSpeech.QUEUE_FLUSH, null, "1");
If you want to add the call back UtteranceProgressListener, you have to give TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID as the utteranceId
It would look like this:
myAct.mtts.speak(myText, TextToSpeech.QUEUE_FLUSH, null, TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID);
See this post:
UtteranceProgressListener does not return error message
and check the engine web site: TTS Engine

Android camera works for one time only after giving permission

I try to show the content of the built-in camera inside my android device using ArCore. I have handled a code for asking permission at the beginning of the application. If I provide the permission I can see the current image stream coming from the camera.
After relaunching the application the result is black. The only solution is to revoke the camera permission inside the setting. Then the application asks again for permission and shows the image stream on the screen.
Is anybody who face the same problem? Do I have to refresh the permission? If I do RequestCameraPermission(); without checking permission, the activity is paused and resumed in a cycle. But I can see the first frame.
In the console the following error appears:
D/ACameraDevice: Device error received, code 3, frame number 51, request ID 0, subseq ID 0
and android_camera.cc:1088 Camera capture failed! frame: 51 reason: 1.
Code 3 is ERROR_CAMERA_DISABLED depending on https://github.com/aosp-mirror/platform_development/blob/master/ndk/platforms/android-24/include/camera/NdkCameraDevice.h
After some time only
I/native: analytics_logger.cc:190 The AnalyticsClient.sendAnalyticsMessage() method returned false. Will retry...
E/native: analytics_logger.cc:198 Could not send event. Event will be dropped.
is called in a loop. There is no activity anymore.
My code:
public class GameActivity extends NativeActivity
{
static GameActivity s_Instance;
public static GameActivity GetInstance()
{
return s_Instance;
}
#Override
public void onCreate(Bundle _SavedInstanceState)
{
super.onCreate(_SavedInstanceState);
s_Instance = this;
nativeInitializeInterface(getApplicationContext());
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume()
{
super.onResume();
if (!HasCameraPermission())
{
RequestCameraPermission();
return;
}
RequestCameraPermission();
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int _RequestCode, String[] _Permissions, int[] _Results)
{
if (!HasCameraPermission())
{
Toast.makeText(this, "Camera permission is needed to run this application", Toast.LENGTH_LONG).show();
if (!ShouldShowRequestPermissionRationale())
{
// Permission denied with checking "Do not ask again".
LaunchPermissionSettings();
}
finish();
}
}
public int GetDeviceOrientation()
{
return getResources().getConfiguration().orientation;
}
public int GetDeviceRotation()
{
return getWindowManager().getDefaultDisplay().getRotation();
}
public int GetDeviceDimensionWidth()
{
Point Size = new Point();
getWindowManager().getDefaultDisplay().getSize(Size);
return Size.x;
}
public int GetDeviceDimensionHeight()
{
Point Size = new Point();
getWindowManager().getDefaultDisplay().getSize(Size);
return Size.y;
}
public boolean HasCameraPermission()
{
return this.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
public void RequestCameraPermission()
{
this.requestPermissions(new String[] {Manifest.permission.CAMERA}, 0);
}
public boolean ShouldShowRequestPermissionRationale()
{
return this.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA);
}
public void LaunchPermissionSettings()
{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package", this.getPackageName(), null));
this.startActivity(intent);
}
public native void nativeInitializeInterface(Context context);
static
{
System.loadLibrary("app_droid");
}
}
Where exactly do you have the logic for presenting the image on screen? Maybe you only have it inside the permission granted callback.
(I'd put this answer as a comment, but can't yet due to reputation)

How to instatiate dialogfragment in a project

I am done with a flag quiz app, it turns out however, that the app doesn't run smoothly. I have debugged several times. Presently, I am stuck. Initially the exception was fragment null must be public static in order to recreate Instance..or something like that. After several, several hours of surfing the net for solutions I created a new class, there is no error in this class but it is coloured red. Why is this?, also what do I need to use the complete or correct this code. eg Studio is saying void showDialog() is not used below is a portion of my MainActivity Fragment
guessButton = ((Button) v);
String guess = guessButton.getText().toString();
String answer = getCountryName(correctAnswer);
++totalGuesses;
if (guess.equals(answer)) {
++correctAnswers;
answerTextView.setText(answer + "!");
answerTextView.setTextColor(
getResources().getColor(R.color.correct_answer));
disableButtons();
if (correctAnswers == FLAGS_IN_QUIZ) {
resetQuiz();
void showDialog(){
DialogFragment newFragment = MyNewFragment.newInstance();
newFragment.show(getFragmentManager(), "QUIZ RESULTS");
newFragment.setCancelable(false);
}
public void doPositiveClick(){
Log.i(" fragmentdialog" , "positive click");
}
}
else {
handler.postDelayed(
new Runnable() {
#Override
public void run() {
animate(true);
}
}, 2000);
}
} else {
flagImageView.startAnimation(shakeAnimation);
answerTextView.setText((R.string.incorrect_answer));
answerTextView.setTextColor(ContextCompat.getColor(getContext(),
R.color.incorrect_answer));
guessButton.setEnabled(false);
}
}
;
private void disableButtons() {
for (int row = 0; row < guessRows; row++) {
LinearLayout guessRow = guessLinearLayouts[row];
for (int i = 0; i < guessRow.getChildCount(); i++)
guessRow.getChildAt(i).setEnabled(false);
}
}
};
}
Below is the new class that keeps on appearing red.
public class MyNewFragment extends DialogFragment {
public static MyNewFragment newInstance() {
MyNewFragment frag = new MyNewFragment();
Bundle args = new Bundle();
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(getActivity())
.setMessage("fff")
.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}
);
return builder.create();
}
};
I will appreciate a precise answer that helps solve these problems
Looks to me that you are somehow declaring methods within if-then-else clauses, hence Android Studio is saying the are unused. The snippet of code where you attempt to launch the DialogFragment should look more like this (i.e. without the surrounding void showDialog() {} method definition):
if (correctAnswers == FLAGS_IN_QUIZ) {
resetQuiz();
DialogFragment newFragment = MyNewFragment.newInstance();
newFragment.show(getFragmentManager(), "QUIZ RESULTS");
newFragment.setCancelable(false);
}
I can't see anything significantly wrong with your definition of MyNewFragment, although you have an empty OnClickListener.OnClick() definition and you are setting the fragment arguments to an empty Bundle. However neither of these issues would generate a Studio compiler error making it show red. Find where Studio is indicating the errors and it will tell you what's wrong with your code.

Native Android UI for using Within LibGdx

Hi there StackOverflow!
I had been loocking on a way to Use the native Android Dialogs and Confimation Boxes in Libgdx...
All that i did by now was a Title and an Image under it:
Dialog yourmsgbox = new Dialog("Title", jsons);
yourmsgbox.setBounds(0f,0f,100f,200f);
yourmsgbox.add(choiceImg);
mainClass.addActor(yourmsgbox);
I suck a little at this but all the codes that i find in Google to do that are Or for Desktop or very especific for that Type of game + Even after some tries to copy the code and adapt it to my .java Files im still getting errors....
So if you guys could guide through a step by step ((Or a list Number of online items that i could follow to get this done I WOULD BE VERYY GRATEFULL !!!))
[[My Json file is EXTREMELY BUGGY, so if I could not have to mess with that Stubborn uiskin.json, I would Thank you :]]
Sorry my bad english
Please i'd apreciate a little help!?
UPDATE:: Sorry i have
two MainClasses for this project and i pick the wrong Logcat :)
I just use showMessage(); in the beggining of the create(), it
crashes when i get into the app. Here is what i did:
I Created an Inferface in core Project:
public interface NativeDialogInterface {
void showMessage(final String title, final String message, final String okButtonText);
}
Created AndroidNativeDialog in -android Project folder:
public class AndroidNativeDialog implements NativeDialogInterface {
private Activity activity;
public void initialize(Activity activity) {
this.activity = activity;
}
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
this.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(okButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface arg0, final int arg1) {
alertDialog.cancel();
}
});
alertDialog.show();
}
});
}
}
*Strange that it says as warning "Method setButton(...) is deprecated"
Then i added new (dialogInterface) in the AndroidLaucher.java:
public class AndroidLauncher extends AndroidApplication {
private AndroidNativeDialog dialogInteface;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
dialogInterface = new AndroidNativeDialog();
initialize(new IndexMain(dialogInteface), config);
}
}
Then in the MainClass what i did was:
btnWindow.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
mainScreen.addActor(andWindow);
dialogInteface.showMessage("TITLE", "ThE MeSsaGe", "Okayy");
Timer.schedule(new Timer.Task() {
#Override
public void run() {
andWindow.setBounds(Gdx.graphics.getWidth(), 0f, 1f, 1f);
}
}, 17);
}
});
I head to that link that "Fuat Coçkun" provided and i learn a lot about these type of structures but it seems i still have something wrongg
Its WORKS perfectly until i click that /\ Button, the button is ok if i delete the showMessage(...);
new LogCat: http://pastebin.com/NbgnyrAJ
Sorry for my bad english.
I can give you example usage of native android AlertDialog with libgdx. Firstly you need an interface in your core Project as follows :
public interface NativeDialogInterface {
void showMessage(final String title, final String message, final String okButtonText);
}
You need different implementations for each of platform you support in your project. Android project implementation will use Dialog, AlertDialog or whatever you want to use as native android component. This example shows AlertDialog implementation:
public class AndroidNativeDialog implements NativeDialogInterface {
private Activity activity;
public void initialize(Activity activity) {
this.activity = activity;
}
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
this.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(okButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
alertDialog.cancel();
}
});
alertDialog.show();
}
});
}
}
You need to call "initialize" method of your instance in your activity(onCreate is proper.) for setting activity field.
You can use any dummy implementation for the Desktop module of your libgdx project. Following implementation only logs the data you passed.
public class DesktopNativeDialog implements NativeDialogInterface {
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
System.out.println("Title : " + title);
System.out.println("Message : " + message);
System.out.println("OkButtonText : " + okButtonText);
}
}
That's all. You should have a field typed NativeDialogInterface in your Core module and call "showMessage" method with your parameter. You will see a console log if you run your application on desktop. You will see native Android alert dialog on your glSurfaceView when you run your application on device/emulator.
I did this and created an expansion for libGDX. You can use it or check the source: https://github.com/TomGrill/gdx-dialogs

Parse.com Android API and Android Dialog

I have placed the parse method inside onCreate method. But my problem is how to show the Android Loading... Dialog??
Parse.initialize(this, "a", "b");
ParseQuery query = new ParseQuery("Category");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> catObjects, ParseException arg1) {
Log.d("Catlength", String.valueOf(catObjects.size()));
for(int i =0; i<catObjects.size(); i++){
Log.d("lengthName"+String.valueOf(i), String.valueOf(catObjects.get(i).getInt("Id")));
Category category = new Category();
category.Name= catObjects.get(i).getString("CatName");
category.id= catObjects.get(i).getInt("Id");
categories.add(category);
}
if(categories.size()>0){
setListAdapter(new CategoryArrayAdapter(CategoryListActivity.this, R.layout.row_category, categories));
}
else{
Toast.makeText(CategoryListActivity.this, "Our servers are busy. Hit refresh..", 3000).show();
}
}
});
Everything works fine in the above code but I couldn't figure out how to show the Dialog.
I'm unable to use AsycTask also as parse sdk invokes its own thread in the background and before the findInBackground execution finishes, the doInBackground completes the Asyc thread. That's why I invoked it in the main thread.
As the result I always get no results in my ArrayList.
Can someone please enlighten me.
I was in the same situation regarding the progress dialog, tried a few tricks and finally just declared a ProgressDialog class member:
protected ProgressDialog proDialog;
then created two methods:
protected void startLoading() {
proDialog = new ProgressDialog(this);
proDialog.setMessage("loading...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
proDialog.setCancelable(false);
proDialog.show();
}
protected void stopLoading() {
proDialog.dismiss();
proDialog = null;
}
and called startLoading() before the background operation and stopLoading()
inside the background operation after I got the the results.
startLoading();
ParseUser.logInInBackground(userName.getText().toString(), hashedPass, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
Log.d(Constants.TAG, "User Loged in.");
ParseManager.sCurrentUser = user;
stopLoading();
finish();
} else {
stopLoading();
invalidCreds();
}
}
});
if you want to use AsyncTask don't call findInBackground() you can use find().
you can check it out in the api https://parse.com/docs/android/api/com/parse/ParseQuery.html#find()
hope this helps.
It's easy to get the progress of both uploads and downloads using ParseFile by passing a ProgressCallback to saveInBackground and getDataInBackground. For example:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
file.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// Handle success or failure here ...
}
}, new ProgressCallback() {
public void done(Integer percentDone) {
// Update your progress spinner here. percentDone will be between 0 and 100.
}
});

Categories