Automatically click Button if EditText is correct - android

I am creating a simple app, I require a button called 'bVoice' to be automatically pressed after 500ms if the EditText field contains the correct information.
How do I write the handler to do this in the following code:
//Assign button clicks to got to a new activity:
public void onButtonClick_1(View v){
if (v.getId() == R.id.bVoice){
String str_1 = a.getText().toString();
//Go to the relevant page if any part of the phrase or word entered in the 'EditText' field contains 'next' which is not case sensitive
if (str_1.toLowerCase().contains("command")) {
Intent userintent = new Intent(PocketSphinxActivity.this, Display_1.class);
startActivity(userintent);
} else {
Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
}
}
}
Below is the full code I have got thus far (Updated):
public class PocketSphinxActivity extends Activity implements RecognitionListener
{
private static final String KWS_SEARCH = "wakeup";
/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "open voice command"; //adjust this keyphrase!
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
ListView lv;
TextView tv;
EditText a;
Button b;
Button c;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Prepare the data for UI
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
lv = (ListView) findViewById(R.id.lvVoiceReturn);
tv = (TextView) findViewById(R.id.result_text);
a = (EditText) findViewById(R.id.TFusername);
b = (Button) findViewById(R.id.bVoice);
c = (Button)findViewById(R.id.Blogin);
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
a.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().equalsIgnoreCase("open voice command")) {
//
//Do your stuff here OR button.performClick()
//
//DELAY
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
b.performClick();
}
}, 500);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
recognizer.cancel();
recognizer.shutdown();
}
/**
* In partial result we get quick updates about current hypothesis. In
* keyword spotting mode we can react here, in other modes we need to wait
* for final result in onResult.
*/
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
//((TextView) findViewById(R.id.result_text)).setText(text);
((EditText) findViewById(R.id.TFusername)).setText(text);
}
/**
* This callback is called when we stop the recognizer.
*/
#Override
public void onResult(Hypothesis hypothesis) {
//((TextView) findViewById(R.id.result_text)).setText("");
((EditText) findViewById(R.id.TFusername)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
//a.setText((String) tv.getText());
//tv = TextView.getText().toString();
}
}
#Override
public void onBeginningOfSpeech() {
}
/**
* We stop recognizer here to get a final result
*/
#Override
public void onEndOfSpeech() {
if (!recognizer.getSearchName().equals(KWS_SEARCH))
switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
recognizer.stop();
// If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
if (searchName.equals(KWS_SEARCH))
recognizer.startListening(searchName);
else
recognizer.startListening(searchName, 10000);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
recognizer = defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
// To disable logging of raw audio comment out this call (takes a lot of space on the device)
.setRawLogDir(assetsDir)
// Threshold to tune for keyphrase to balance between false alarms and misses
.setKeywordThreshold(1e-45f)
// Use context-independent phonetic search, context-dependent is too slow for mobile
.setBoolean("-allphone_ci", true)
.getRecognizer();
recognizer.addListener(this);
/** In your application you might not need to add all those searches.
* They are added here for demonstration. You can leave just one.
*/
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
}
#Override
public void onError(Exception error) {
((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
}
#Override
public void onTimeout() {
switchSearch(KWS_SEARCH);
}
//Assign button clicks to go to a new activity:
public void onButtonClick_1(View v){
if (v.getId() == R.id.bVoice){
String str_1 = a.getText().toString();
}
UPDATED text with onResume at the bottom of code:
#Override
public void onResume(){
super.onResume();
isDone = false;
a.setText("");
}

If you want to do something based on the input in the edittext, then you could use a TextWatcher.
UPDATE
Create a global boolean variable:
Boolean isDone=false;
Then inside your Handler code update the code like this :
a.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().equalsIgnoreCase("open voice command"))
{
//
//Do your stuff here OR button.performClick()
//
//DELAY
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (!isDone){
b.performClick();
isDone=true;
} }
}, 500);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Just Add this code after your AsyncTask. i.e after
}.execute();
To import the Editable class, click on it and press alt+Enter.
Do the same for TextWatcher, click on it and then press alt+Enter.
Whatever code you type inside onTextChanged will get executed whenever the text in the EditText changes. SOLVES your automatic problem.

Related

Cancel Task in Place AutoComplete for Android

Im using Places autocomplete for Android Library below is my code:
private void callGoogleAutoComplete(String newText) {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setCountry("PK")
.build();
Task<AutocompletePredictionBufferResponse> results=mGeoDataClient.getAutocompletePredictions(newText,myBounds,typeFilter);
results.addOnCompleteListener(new OnCompleteListener<AutocompletePredictionBufferResponse>() {
#Override
public void onComplete(#NonNull Task<AutocompletePredictionBufferResponse> task) {
try {
String response="";
} catch (Exception e) {
e.printStackTrace();
}
}
});
results.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
results.addOnSuccessListener(new OnSuccessListener<AutocompletePredictionBufferResponse>() {
#Override
public void onSuccess(AutocompletePredictionBufferResponse autocompletePredictions) {
}
});
}
Above method is called every time when text change in EditText, I want to cancel pervious call (Task) as on every character task is being generated. But Im unable to cancel Task.
Note
I only posted necessary code for Listeners only.
I think it's a better way to delay user input. Wait for user finished typing then call your method it helps you. Like this way
editText.addTextChangedListener(
new TextWatcher() {
#Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
private Timer timer=new Timer();
private final long DELAY = 1000; // milliseconds
#Override
public void afterTextChanged(final Editable s) {
timer.cancel();
timer = new Timer();
timer.schedule(
new TimerTask() {
#Override
public void run() {
// TODO: do what you need here (refresh list)
// you will probably need to use runOnUiThread(Runnable action) for some specific actions
}
},
DELAY
);
}
}
);

ZXingScannerView scan bulk mode in handleresult

I'm trying to implement Bulk Scan mode in me.dm7.barcodescanner:zxing:1.9 library. This is my snippet codes. Im trying to do multiple scan which from the codes for now i just trying to display each of the scan result in messagedialogue. however, after the first scan resulthandler, the second time scan automatically kill the activity.
private ZXingScannerView mScannerView;
private boolean mFlash;
private boolean mAutoFocus;
private int mCameraId = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
setupFormats();
contentFrame.addView(mScannerView);
}
//i want to make my scanner able to keep scanning getting the result.
//however after the first scan, the second scan will automatically close the activity
#Override
public void handleResult(Result result) {
try {
if(!result.getText().equals("")){
//In message dialogue will have 1 button handle on onDialogPositiveClick
showMessageDialog("Contents = " + result.getText() + ", Format =
" + result.getBarcodeFormat().toString());
}
} catch (Exception e) {
} finally {
}
}
public void showMessageDialog(String message) {
DialogFragment fragment = MessageDialogFragment.newInstance("Scan
Results", message, this);
fragment.show(getSupportFragmentManager(), "scan_results");
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
mScannerView.resumeCameraPreview(this);
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
closeMessageDialog();
closeFormatsDialog();
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera(mCameraId);
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
}
Try it with onActivityResult
/*Here is where we come back after the Barcode Scanner is done*/
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// contents contains whatever the code was
String contents = intent.getStringExtra("SCAN_RESULT");
// Format contains the type of code i.e. UPC, EAN, QRCode etc...
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_FORMATS", "PRODUCT_MODE,CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF");
startActivityForResult(intent, 0); // start the next scan
} else if (resultCode == RESULT_CANCELED) {
//do whatever else you want.
}
}
}
you have to add handler or TimerTask for secondTime Scan.after get first scan result in handleResult you have to start scanning again after some delay, whatever delay you want add to handler.
#Override
public void handleResult(final Result rawResult) {
runOnUiThread(new Runnable() {
#Override
public void run() {
handleDecode(rawResult);
}
});
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mScannerView.resumeCameraPreview(CaptureActivity.this);
}
}, 4000);// 4 sec delay to restart scan again.
}

Clear the contents of an EditText Field once button is pressed

I am creating a simple app which automatically triggers a button b once the contents of an EditText field called a contains a key phrase. I am wanting to clear the contents of the edit text field automatically say after 2 seconds. Is there a easy way to implement this into my code below?
public class PocketSphinxActivity extends Activity implements RecognitionListener
{
private static final String KWS_SEARCH = "wakeup";
/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "open voice command"; //adjust this keyphrase!
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
ListView lv;
TextView tv;
EditText a;
Button b;
Button c;
Boolean isDone = false;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Prepare the data for UI
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
lv = (ListView) findViewById(R.id.lvVoiceReturn);
tv = (TextView) findViewById(R.id.result_text);
a = (EditText) findViewById(R.id.TFusername);
b = (Button) findViewById(R.id.bVoice);
c = (Button)findViewById(R.id.Blogin);
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
//line added.../////////////////////////
a.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().equalsIgnoreCase("open voice command")) {
//
//Do your stuff here OR button.performClick()
//
//DELAY
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (!isDone) {
b.performClick();
isDone = true;
}
}
}, 500);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
////////////////////////////////////////
}
#Override
public void onDestroy() {
super.onDestroy();
recognizer.cancel();
recognizer.shutdown();
}
/**
* In partial result we get quick updates about current hypothesis. In
* keyword spotting mode we can react here, in other modes we need to wait
* for final result in onResult.
*/
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
//((TextView) findViewById(R.id.result_text)).setText(text);
((EditText) findViewById(R.id.TFusername)).setText(text);
}
/**
* This callback is called when we stop the recognizer.
*/
#Override
public void onResult(Hypothesis hypothesis) {
//((TextView) findViewById(R.id.result_text)).setText("");
((EditText) findViewById(R.id.TFusername)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
//a.setText((String) tv.getText());
//tv = TextView.getText().toString();
}
}
#Override
public void onBeginningOfSpeech() {
}
/**
* We stop recognizer here to get a final result
*/
#Override
public void onEndOfSpeech() {
if (!recognizer.getSearchName().equals(KWS_SEARCH))
switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
recognizer.stop();
// If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
if (searchName.equals(KWS_SEARCH))
recognizer.startListening(searchName);
else
recognizer.startListening(searchName, 10000);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
recognizer = defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
// To disable logging of raw audio comment out this call (takes a lot of space on the device)
.setRawLogDir(assetsDir)
// Threshold to tune for keyphrase to balance between false alarms and misses
.setKeywordThreshold(1e-45f)
// Use context-independent phonetic search, context-dependent is too slow for mobile
.setBoolean("-allphone_ci", true)
.getRecognizer();
recognizer.addListener(this);
/** In your application you might not need to add all those searches.
* They are added here for demonstration. You can leave just one.
*/
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
}
#Override
public void onError(Exception error) {
((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
}
#Override
public void onTimeout() {
switchSearch(KWS_SEARCH);
}
//Assign button clicks to go to a new activity:
public void onButtonClick_1(View v){
if (v.getId() == R.id.bVoice){
String str_1 = a.getText().toString();
//Go to the relevant page if any part of the phrase or word entered in the 'EditText' field contains 'command' which is not case sensitive
if (str_1.toLowerCase().contains("command")) {
Intent userintent = new Intent(PocketSphinxActivity.this, Gvoice.class);
startActivity(userintent);
} else {
Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
}
}
}
//Added this to clear the 'open voice command' text when pressing back from a activity window
//This at the moment seems to only work when typing the command, If I use speech to text to say'open voice command
#Override
public void onResume(){
super.onResume();
isDone = false;
a.setText("");
}
}
Additionally, due to using a boolean method, if I go back to this activity using the back button etc in my app, it does not seem to trigger the option again. Is there a way to cause it to trigger b again if I return back to the same window/activity?
I'll really appreciate some useful help in modifying part of my code shown above.
For the first part, you're actually doing it already on your code. The only thing that I don't understand is as to why do you have the boolean isDone? Have you tried removing it? Since if you already cleared the EditText, even if it does go through onTextChanged again, it wont pass the first condition again (Here I'm presuming that bs action is to clear the text of a).
For the text checking, I think you can use androids TextUtils.equals() :
TextUtils.equals(s, "open voice command");
EDIT
Okay. So I re-analyzed your post and your comments and ended up with this flow of behavior.
The First time the activity runs, when you type in "open voice command" in EditText a, Button b will be automatically clicked and will proceed to starting an activity and MUST clear EditText a. Pressing back to the activity that contains both EditText a and Button b, you want the EditText a onTextChangeListener to still function.
With those in mind, I ended up modifying your code as below:
public class MainActivity extends AppCompatActivity {
EditText a;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize Views
a = (EditText) findViewById(R.id.a);
b = (Button) findViewById(R.id.b);
// Initialize listeners
a.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (TextUtils.equals(s, "open voice command")) {
Log.d("SAMPLE", ">>>>>>> Running handler!....");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
a.setText(null);
b.performClick();
}
}, 500);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SampleActivity.class);
startActivity(intent);
}
});
}
}
When I type in "open voice command" in EditText a, is automatically gets cleared and calls the performClick() for Button b. After I get back to the activity. Nothing happens, the handler doesn't run since the text value of EditText a is empty. The handler will only trigger again if you type in "open voice command".
EDIT 2
Here is the code I am running. I just commented out most of the codes that are not related to the concern on your post. I'm getting the correct behavior you are aiming for.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognitionListener;
import android.speech.SpeechRecognizer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
public class PocketSphinxActivity extends Activity implements RecognitionListener {
private static final String KWS_SEARCH = "wakeup";
/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "open voice command"; //adjust this keyphrase!
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
ListView lv;
TextView tv;
EditText a;
Button b;
Button c;
Boolean isDone = false;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_main);
// Prepare the data for UI
// captions = new HashMap<String, Integer>();
// captions.put(KWS_SEARCH, R.string.kws_caption);
// ((TextView) findViewById(R.id.caption_text))
// .setText("Preparing the recognizer");
// lv = (ListView) findViewById(R.id.lvVoiceReturn);
// tv = (TextView) findViewById(R.id.result_text);
a = (EditText) findViewById(R.id.a);
b = (Button) findViewById(R.id.b);
// c = (Button) findViewById(R.id.Blogin);
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
// new AsyncTask<Void, Void, Exception>() {
// #Override
// protected Exception doInBackground(Void... params) {
// try {
// Assets assets = new Assets(PocketSphinxActivity.this);
// File assetDir = assets.syncAssets();
// setupRecognizer(assetDir);
// } catch (IOException e) {
// return e;
// }
// return null;
// }
//
// #Override
// protected void onPostExecute(Exception result) {
// if (result != null) {
// ((TextView) findViewById(R.id.caption_text))
// .setText("Failed to init recognizer " + result);
// } else {
// switchSearch(KWS_SEARCH);
// }
// }
// }.execute();
//line added.../////////////////////////
a.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().equalsIgnoreCase("open voice command")) {
//
//Do your stuff here OR button.performClick()
//
//DELAY
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (!isDone) {
b.performClick();
isDone = true;
}
}
}, 500);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
////////////////////////////////////////
}
#Override
public void onDestroy() {
super.onDestroy();
// recognizer.cancel();
// recognizer.shutdown();
}
/**
* In partial result we get quick updates about current hypothesis. In
* keyword spotting mode we can react here, in other modes we need to wait
* for final result in onResult.
*/
// #Override
// public void onPartialResult(Hypothesis hypothesis) {
// if (hypothesis == null)
// return;
//
// String text = hypothesis.getHypstr();
// //((TextView) findViewById(R.id.result_text)).setText(text);
// ((EditText) findViewById(R.id.TFusername)).setText(text);
// }
/**
* This callback is called when we stop the recognizer.
*/
// #Override
// public void onResult(Hypothesis hypothesis) {
// //((TextView) findViewById(R.id.result_text)).setText("");
// ((EditText) findViewById(R.id.TFusername)).setText("");
// if (hypothesis != null) {
// String text = hypothesis.getHypstr();
// makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
//
//
// //a.setText((String) tv.getText());
// //tv = TextView.getText().toString();
// }
// }
/**
* We stop recognizer here to get a final result
*/
#Override
public void onEndOfSpeech() {
// if (!recognizer.getSearchName().equals(KWS_SEARCH))
// switchSearch(KWS_SEARCH);
}
private void switchSearch(String searchName) {
// recognizer.stop();
//
// // If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
// if (searchName.equals(KWS_SEARCH))
// recognizer.startListening(searchName);
// else
// recognizer.startListening(searchName, 10000);
//
// String caption = getResources().getString(captions.get(searchName));
// ((TextView) findViewById(R.id.caption_text)).setText(caption);
}
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
// recognizer = defaultSetup()
// .setAcousticModel(new File(assetsDir, "en-us-ptm"))
// .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
//
// // To disable logging of raw audio comment out this call (takes a lot of space on the device)
// .setRawLogDir(assetsDir)
//
// // Threshold to tune for keyphrase to balance between false alarms and misses
// .setKeywordThreshold(1e-45f)
//
// // Use context-independent phonetic search, context-dependent is too slow for mobile
// .setBoolean("-allphone_ci", true)
//
// .getRecognizer();
// recognizer.addListener(this);
/** In your application you might not need to add all those searches.
* They are added here for demonstration. You can leave just one.
*/
// Create keyword-activation search.
// recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
}
// #Override
// public void onError(Exception error) {
// ((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
// }
// #Override
// public void onTimeout() {
// switchSearch(KWS_SEARCH);
// }
//Assign button clicks to go to a new activity:
public void onButtonClick_1(View v) {
if (v.getId() == R.id.b) {
String str_1 = a.getText().toString();
//Go to the relevant page if any part of the phrase or word entered in the 'EditText' field contains 'command' which is not case sensitive
if (str_1.toLowerCase().contains("command")) {
Intent userintent = new Intent(PocketSphinxActivity.this, Gvoice.class);
startActivity(userintent);
} else {
Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
}
}
}
//Added this to clear the 'open voice command' text when pressing back from a activity window
//This at the moment seems to only work when typing the command, If I use speech to text to say'open voice command
#Override
public void onResume() {
super.onResume();
isDone = false;
a.setText("");
}
}

Managing Delays in an android app

Hey guys, i would like to know how to manage delays in an android application, for example, I have an overridden method onTextChanged(). In relation to that I want to set a delay like .5 seconds in order to finalized what the user is typing in my autocomplete textbox. If the user hangs/stop typing in .5 sec, i wanted a certain method or implementation to execute in my code(i.e. my own filtering scheme/logic in my autocomplete textbox, just to lessen resource usage within my app, thanks).
Here's my sample code:
protected AutoCompleteTextView autoCompleteView;
protected AutoCompleteAdapter suggsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countries = getResources().getStringArray(R.array.countries_array);
autoCompleteView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
TextWatcher textChecker = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//here inside this overridden method, I wanted to create a delay in order to lessen the
//use of resources.
String enteredText = autoCompleteView.getText().toString();
refreshList(enteredText);
}
};
autoCompleteView.addTextChangedListener(textChecker);
}
and for example, the user typed "Lond"(for String like "London") with each letter typed less than .5 sec, I want all the previous onTextChanged() method called(method call in typing "L", "o" and "n") to be disregarded and only the onTextChanged() when the last letter was typed would be granted for execution.
How would I do that, please help me:(.
You can create a Handler subclass and call Handler.sendEmptyMessageDelayed() or Handler.sendMessageDelayed() method when onTextChanged() is triggered. And you can remove messages from the message queue using Handler.removeMessages(). You should process messages in Handler.handleMessage() method. So your onTextChanged() method will be something like:
mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
mHandler.sendEmptyMessage(MESSAGE_TEXT_CHANGED, 500);
EDIT: Here's an example of code. I haven't tested it yet, so I'm not sure it works.
private static final int AUTOCOMPLETE_DELAY = 500;
private static final int MESSAGE_TEXT_CHANGED = 0;
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_TEXT_CHANGED) {
String enteredText = (String)msg.obj;
refreshList(enteredText);
}
}
};
// ... your code here
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String enteredText = autoCompleteView.getText().toString();
mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
final Message msg = Message.obtain(mHandler, MESSAGE_TEXT_CHANGED, enteredText);
mHandler.sendMessageDelayed(msg, AUTOCOMPLETE_DELAY);
}
I am writing Running code for autocomplete.
First onTextChanged will be called.
public void onTextChanged(CharSequence s, int start, int before, int count) {
String newText = s.toString();
if(!newText.trim().equals(""))
Autocompletes_Timer(newText);
}
now we need a Handler.
Hander handler = new Handler();
private void Autocompletes_Timer(final String newText) {
// new text will be here. so if you type fast within 1 sec.
// handler will be remover each time so that handler post delay also be remove.
if(handler!= null)
handler.removeCallbacksAndMessages(null);
// new text will be in runnable with 1 sec delay.
handler.postDelayed(runnable(newText), 1000);
}
// it will be start work after 1 sec.
// if you stop the typing then it will complete work like as sending data at server.
// if you continue typing , it will not complete work and each type will be removeCallbackAndMessage.
private Runnable runnable(final String newText) {
Runnable runnable = new Runnable() {
#Override
public void run() {
Log.d("Autocompleted", newText);
// call AysncTask here
}
};
return runnable;
}
just copy and paste my code. It should be fix your problem . Enjoy.
use a CountDownTimer
protected AutoCompleteTextView autoCompleteView;
protected AutoCompleteAdapter suggsAdapter;
String TAG = "Timer";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countries = getResources().getStringArray(R.array.countries_array);
autoCompleteView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
TextWatcher textChecker = new TextWatcher() {
CountDownTimer countDownTimer = new CountDownTimer(500,100) {
#Override
public void onTick(long millisUntilFinished) {
Log.d(TAG, "addressTextWatcher.countDownTimer.onTick() -> Tick: " + millisUntilFinished);
}
#Override
public void onFinish() {
Log.d(TAG, "addressTextWatcher.countDownTimer.onTick() -> Finish");
String enteredText = autoCompleteView.getText().toString();
refreshList(enteredText);
}
};
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
countDownTimer.cancel();
countDownTimer.start();
}
};
autoCompleteView.addTextChangedListener(textChecker);
}

Android: waiting until tts speak is finished, then continue

I'm really struggling with something... I have a couple of sentences that I want to read, both verbally through tts speek function, and via text on screen, one sentence at a time.
I have the textview area ready, but putting it together is what I'm not getting. Either it will read all the sentences and only show the last one, or it will show and read only the first sentence.
Anyone know i how I can accomplish this goal?
I just ran into this issue, according to the speak method, use an UtteranceProgressListener. I found out this is not executed on the UI thread, so I had to use runOnUiThread() to get back to update the activity.
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
LettersActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// Do something on UI thread
}
});
}
#Override
public void onError(String utteranceId) {
Log.e(TAG, "error on " + utteranceId);
}
});
boolean speakingEnd = tts.isSpeaking();
do{
speakingEnd = tts.isSpeaking();
} while (speakingEnd);
//Continue with code
public void speak(String message){
tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
while (tts.isSpeaking()){
System.Out.Println("Do something or nothing while speaking..")
}
}
Try this
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{
private boolean initialized;
private String queuedText;
private String TAG = "TTS";
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this /* context */, this /* listener */);
tts.setOnUtteranceProgressListener(mProgressListener);
speak("hello world");
}
public void speak(String text) {
if (!initialized) {
queuedText = text;
return;
}
queuedText = null;
setTtsListener(); // no longer creates a new UtteranceProgressListener each time
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
tts.speak(text, TextToSpeech.QUEUE_ADD, map);
}
private void setTtsListener() {
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
initialized = true;
tts.setLanguage(Locale.ENGLISH);
if (queuedText != null) {
speak(queuedText);
}
}
}
private abstract class runnable implements Runnable {
}
private UtteranceProgressListener mProgressListener = new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
} // Do nothing
#Override
public void onError(String utteranceId) {
} // Do nothing.
#Override
public void onDone(String utteranceId) {
new Thread()
{
public void run()
{
MainActivity.this.runOnUiThread(new runnable()
{
public void run()
{
Toast.makeText(getBaseContext(), "TTS Completed", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
};
}

Categories

Resources