Android Speech Recogntion won't work in a separate class - java

I'm a beginner in Android development. What I'm trying to create is an app the speaks to you then waits for your answer so its kind of text to speech works ,then it activates speech recognition and with my code the text to speech works then it calls speech recognition.Then an erro msg is shown ,the catch block is executed.
The problem is that I have to add Speech Recognition in a separate class, then add an Object of it in the Adapter not Main Activity. Speech Recognition won't work and since all tutorials for speech recognition for Android are adding the code in Main Activity and I'm doing it as class called in the adapter is the problem ?
UPDATE startActivityForResult() method is not working
Here is the code for SpeechRecogntion class
public class SpeechRecog extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
String textResult ;
public void Start (Intent i , Context c){
i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
i.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Are You Done , yet? ");
try{
startActivityForResult(i,VOICE_RECOGNITION_REQUEST_CODE);
} catch(Exception e) {
Toast.makeText(c, "SpeechRecogntion is not avalible on your device ", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == VOICE_RECOGNITION_REQUEST_CODE)&& (resultCode== RESULT_OK)) {
textResult= data.getStringExtra(RecognizerIntent.EXTRA_RESULTS);
if (checkResult())
Toast.makeText(getApplicationContext(), "You are done ", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "You are not done ", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
private boolean checkResult() {
if (textResult.equals("done")||(textResult.equals("yes")))
return true ;
return false;
}
}
And Here is the object of it in the Adapter class
private SpeechRecog mySP;
private Intent mySpIntetn ;
public ListAdapterClass(Context context) {
mytts = new TxtToSpeechClass(context);
mySP = new SpeechRecog();
}
And Here is where my problem relies ,the on clicklistener inside the Adapter class
Lh.btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if (Lh.btn.getText().equals("Play"))
{
Lh.btn.setText("Pause"); //change the btn status so user know how to stop it
List<Items> hResults=db.getAllItems(Lh.idList + 1);
for (int i = 0; i < hResults.size(); i++)
{
Items item = hResults.get(i);
String s = item.getItemname();
mytts.Talk(s,1);
mySP.Start(mySpIntetn , context ); //the code in here wont work is there something I'm missing here
Toast.makeText(context,s, Toast.LENGTH_SHORT).show();
}
mytts.Talk("Congrats ",1);// 1 means Queue_add
} else {
Lh.btn.setText("Play");
mytts.Talk("See you later", 0); // 0 means Queue_Flush
}
}
);

mySpIntetn is private. Try to change it to public in the Adapter class.

Related

Activity intent child doesn't return data to parent, toast is not shown

Greetings fellow programmers,
I have been having some issues with understanding why my child's intent doesn't return the proper value to my parent's intent properly.
private static final int REQUEST_CODE_CHEAT = 0;
Now here is how I call my explicit intent
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isTrue = mStatements[mStatementIndex].isAnswerTrue();
Intent intent = SubActivity.newIntent(MainActivity.this, isTrue);
startActivityForResult(intent, REQUEST_CODE_CHEAT);
}
});
This is the code for the SubActivity that creates the interfacing Intent
public static Intent newIntent(Context packageContext, boolean answerIsTrue){
Intent intent = new Intent(packageContext, SubActivity.class);
intent.putExtra(EXTRA_ANSWER_SHOWN, answerIsTrue);
return intent;
}
Also, have the following keys to keep track of what goes where
private static final String EXTRA_ANSWER_IS_TRUE = "com.tsourtzis.android.test.answer_is_true";
private static final String EXTRA_ANSWER_SHOWN = "com.tsourtzis.android.test.answer_shown";
Finally some methods to be certain what values are passed
private void setAnswerShownResult(boolean isAnswerShown){
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_IS_TRUE, isAnswerShown);
setResult(RESULT_OK, data);
}
Here I'm sending back the intent to the MainActivity with setResult();
public static boolean wasAnswerShown(Intent result){
return result.getBooleanExtra(EXTRA_ANSWER_SHOWN, false);
}
Moreover, I have this method here to evaluate the result, but checking first if the user has created it.
public void evaluateStatement(boolean userChoice){
boolean statementValue = mStatements[mStatementIndex].isAnswerTrue();
int textResId = 0;
if(mBoolResult){
textResId = R.string.judgment_toast;
}else{
if(userChoice == statementValue){
textResId = R.string.correct_toast;
}else{
textResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, textResId, Toast.LENGTH_SHORT).show();
}
Notice, I have stated the following my MainActivity after using setResult(...) and a field value for keeping the boolean result from the Sub activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode != Activity.RESULT_OK){
return;
}
if(requestCode == REQUEST_CODE_CHEAT){
if(data == null){
return;
}
mBoolResult = SubActivity.wasAnswerShown(data);
}
}
Finally just to be clear, here is the field that I have in MainActivity.
private boolean mBoolResult;
I'm not looking for any code answer, I just want to understand why it doesn't work. Thank you!
Do you finish() your SubActivity ?
Seeing that the Toast should be shown any time the method evaluateStatement is called, I guess onActivityResult doesn't dispatch the call to it.
Can you explicit where is the onActivityResult you show last? It's unclear since it's calling CheatActivity#wasAnswerShown() as if it is not in CheatActivity (MainActivity?)

Android - Get result from change default SMS app dialog

I am working on restoring SMS on KITKAT. Referring to this article I have added the things which are required to set my app as default app for SMS. After adding all required things in manifest file I have write the following code:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
mDefaultSmsApp = Telephony.Sms.getDefaultSmsPackage(mContext);
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, mContext.getPackageName());
mContext.startActivity(intent);
}
The above code shows this dialog but I am unable to get the result from this activity/dialog either user clicked on Yes or No because I want to add listener or get any code which should represent that the user clicked on these buttons.
Thanks.
One way to do this is to fire the Intent with startActivityForResult(), and then check the resultCode in the onActivityResult() method. Please note that I've changed the code in the example to run in an Activity's Context.
private static final int DEF_SMS_REQ = 0;
private String mDefaultSmsApp;
...
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
mDefaultSmsApp = Telephony.Sms.getDefaultSmsPackage(this);
if (!getPackageName().equals(mDefaultSmsApp))
{
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivityForResult(intent, DEF_SMS_REQ);
}
}
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case DEF_SMS_REQ:
boolean isDefault = resultCode == Activity.RESULT_OK;
...
}
}
As mentioned in a comment below, apparently checking the result code is not 100% reliable. A safer check is to simply compare your app's package name to the current default in onActivityResult(). There's no need to check the result code at all, like the answer linked in the comment shows.
String currentDefault = Sms.getDefaultSmsPackage(this);
boolean isDefault = getPackageName().equals(currentDefault);
The way you can react on "yes" button click:
private String mDefSmsPackage;
#Override
public void onCreate(#Nullable Bundle state) {
//...
mDefSmsPackage = Telephony.Sms.getDefaultSmsPackage(getActivity())
}
#Override
public void onResume() {
super.onResume();
String newDefSmsPkg = Telephony.Sms.getDefaultSmsPackage(getActivity());
if (!TextUtils.equals(mDefSmsPackage, newDefSmsPkg)) {
mDefSmsPackage = newDefSmsPkg;
//ON DEF SMS APP CAHNGE...
}
}

TextView's Text is not updated in UI Thread

I've got a problem. I want to change the text of a textview after selecting an item (ringtone). I got the selected ringtone title and wanted to write it on the text attribute of textview, but it doesn't work (I am in the UI Thread not in a seperate thread).
Here's the code, where i want to update the text:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(resultCode) {
case RESULT_OK:
String ringtoneTitle = null;
ringtoneUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if(ringtoneUri != null) {
ringtoneValue = ringtoneUri.toString(); //diesen Wert später in Datenbank abspeichern !!
ringtoneTitle = RingtoneManager.getRingtone(this, ringtoneUri).getTitle(this); //Titel getten
}
textViewRingtone.append(": " + ringtoneTitle); //Titel zu TextView setzen
break;
}
}
Can somebody help ?
Use the post(Runnable) method of the View class :
textViewRingtone.post(new Runnable() {
#Override
public void run() {
textViewRingtone.append(": " + ringtoneTitle);
}
};
Try setting textview inside a handler:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(resultCode) {
case RESULT_OK:
String ringtoneTitle = null;
ringtoneUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if(ringtoneUri != null) {
ringtoneValue = ringtoneUri.toString(); //diesen Wert später in Datenbank abspeichern !!
ringtoneTitle = RingtoneManager.getRingtone(this, ringtoneUri).getTitle(this); //Titel getten
}
new Handler().post(new Runnable() {
#Override
public void run() {
textViewRingtone.append(": " + ringtoneTitle); //Titel zu TextView setzen
}
});
break;
}
}
OK,
i've found the solution, it was a really, really silly mistake of mine, that you couldnt know, because i didnt show that code to you.
In the onClick Method, in which i start the intent of showing the ringtone picker i accidentally called startActivity(intent) instead of startActivityForResult(intent, requestCode) so onActivityResult couldn't get called.
Thanks to #codeMagic, who made me realize this mistake.

onActivityResult() Does not get called?

I have an MainActivity which has two TextView. User has an option to start another activity and choose data from ListView to fill those TextView. My main activity has an OnClickListener which starts an Activty from which user can select data and come back to main activity.My OnClickListener code looks likes this:
private static final int PICK_START = 0;
private static final int PICK_END = 1;
#Override
public void onClick(View v) {
Log.i(MainActivity, "view clicked");
int id = v.getId();
if (id == R.id.searchR) {
//do nothing
} else if (id == R.id.startSearch) {
Intent startIntent = new Intent(this, SList.class);
startActivityForResult(startIntent, PICK_START);
} else if (id == R.id.endSearch) {
Intent startIntent = new Intent(this, SList.class);
startActivityForResult(startIntent, PICK_END);
}
}
When the above onClick method gets called and after that its starts another activity SList.class.In that I have a listview from which user can select the value and upon selecting value the result will be set and activity will finish itself.Code for this is:
sListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Station selectedS = sArray.get(position);
Intent returnIntent = new Intent();
returnIntent.putExtra("_id", selectedS.getId());
returnIntent.putExtra("name", selectedS.getName());
setResult(RESULT_OK, returnIntent);
finish();
}
});
In above code activity sets the result and finishes itself.Till here everything is working accordingly.But after that when the previous activity is started, the onActivityResult() method nevers gets called.The code for onActivityResult() is :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(MainActivity, "" + requestCode);
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Check which request we're responding to
if (requestCode == PICK_START) {
//data.getStringExtra("_id");
Log.i(MainActivity, data.getStringExtra("name"));
} else if (requestCode == PICK_END) {
Log.i(MainActivity, data.getStringExtra("name"));
}
}
}
I dont know why onActivityResult is never triggered .Someone even
wrote on his blog that There is bug in android API. In
startActivityForResult(intent, requestCode); This function does work
as long as requestCode = 0. However, if you change the request code to
anything other than zero, the ApiDemos will fail (and onActivityResult()
won't be called).
I found the solution to my problem.I just needed to restart my eclipse and my code started working.

Android Facebook-Connect button needs to be clicked two times

since hours I am trying to figure out why my facebook-connect is not working properly. I always have to click it two times.. the first time I click it I see that the facbeook dialog is opening but its not calling any kind of callback so my Login-Activity is just "resuming".
public void onClick_fbIcon(View v) {
if(!buttonsEnabled)
return;
buttonsEnabled = false;
tryFacebookConnect();
}
#SuppressWarnings("deprecation")
private void tryFacebookConnect() {
Log.d("debug", "start fbc");
doingFacebooklogin = true;
facebook.authorize(this, new DialogListener() {
public void onComplete(Bundle values) {
end();
toast("Complete");
Log.d("debug", "#0");
// .. continue with main code
}
public void onFacebookError(FacebookError error) {
end();
Log.d("debug", "#1");
}
public void onError(DialogError e) {
end();
Log.d("debug", "#2");
}
public void onCancel() {
end();
Log.d("debug", "#3");
}
private void end() {
Log.d("debug", "fbc complete");
doingFacebooklogin = false;
}
});
}
The first click I only get "start fbc" but nothing after that, so I guess that no callback method is called.
I found out that when the facebook-connect is not working the first time, "onResume is called". The next time onActivityResult is called.
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("debug", "Main: onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
My login activity is an intent started by my main activity that is specifing if a login is needed at all:
Intent intent = new Intent(this, Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Sometimes I can see the following error:
11-22 10:23:39.684: D/Facebook-publish(7317): Can NOT get FbInjector instance! Probably because this method was called in ContentProvider's onCreate.
Please take a look at this Tutorial. I just Follow this and I make it all works perfectly.
Hope that it will help you too.
http://www.youtube.com/watch?v=xndi6s9Tn_U
I don't know why but the problem is obviously part of the facebook-sdk. I found out that this problem does not occur if I have no facebook-app installed on my device. So I changed my code like this:
facebook.authorize(a, new String[] { }, **Facebook.FORCE_DIALOG_AUTH**, new DialogListener() {
...

Categories