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.
}
Related
Hello I want to thank you in advance for your answers. My problem is I am using Zxing to scan qr codes. And I want to paste the scan value on the my edit text at Login Activity.
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.Result;
import com.logizard.logizard_go.R;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class ScanResult extends AppCompatActivity implements ZXingScannerView.ResultHandler{
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
// Log.v("tag", rawResult.getText()); // Prints scan results
// Log.v("tag", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
Login.editTextUser.setText(rawResult.getText());
onBackPressed();
// If you would like to resume scanning, call this method below:
//mScannerView.resumeCameraPreview(this);
}
}
This is the sample code that I use but every time I use the button for scan nothing happens.
It looks like that you have a Login(Activity) that open the ScanResult(Activity) and you want to return the value of the scanned to Login
I suggest to you to look this doc, but also maybe you could move the handlingscan part of your code to Login activity
... implements ZXingScannerView.ResultHandler{
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
editTextUser.setText(rawResult.getText());
}
}
BETTER do like that
in Login
static final int GET_SCANNED = 1;
...
private void openScanResult(){
Intent i = new Intent(this, ScanResult.class);
startActivityForResult(i, GET_SCANNED);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GET_SCANNED) {
if(resultCode == Activity.RESULT_OK){
String result = data.getStringExtra("scanned");
editTextUser.setText(result)
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
in ScanResult
#Override
public void handleResult(Result rawResult) {
Intent returnIntent = new Intent();
returnIntent.putExtra("scanned",rawResult.getText());
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
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.
I am new at Android and working on a speech to text app. I am using Google API. I want to allow users can only speak 2 seconds. After 2 seconds pop-up window should close. Can anyone give me some tips?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
public void promptSpeechInput()
{
//This intent recognize the speech
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say Something");
try {
startActivityForResult(i, 100);
}
catch (ActivityNotFoundException a)
{
Toast.makeText(MainActivity.this,"Your device does not support",Toast.LENGTH_LONG).show();
}
}
//For receiving speech input
public void onActivityResult(int request_code, int result_code, Intent i)
{
super.onActivityResult(request_code, result_code, i);
switch (request_code)
{
case 100: if(result_code == RESULT_OK && i != null)
{
ArrayList<String> result = i.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
resultTEXT.setText(result.get(0));
}
break;
}
}
You can add this code where you want to start the timer and in method run you have to write the code for closing the pop up
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
5000
);
Here it is 5 seconds (5000 milliseconds) you can change it to whatever time period you required in milliseconds.
Try Handler inside UIThread this lets you delay when the pop-up window closes..add the code to close the pop-up in run():
runOnUiThread(new Runnable() {
#Override
public void run() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//close the window pop-up here
}
}, 2000);
}
});
hope it helps
My Activity is named BlacklistAddActivity.
UI element: EditText editText, Button btn1. When I click btn1, it will launch contact list activity and I can pick a contact from the contact list. Then send the contact info back to BlacklistAddActivity, and set the contact's name to the text1 by editText.setText(contact.name).
The problem is, sometimes, in contact list, if I do some operations: enter dialer from recent applicaton window(long press home key), and make a call etc... As we know, the android will check memory to decide destroying the activity stack or not. If memory is low, it will destroy the background activities, including BlacklistActivity.
Now, resume to contact list and pick a contact, resume to BlacklistActivity, it will be recreated. I can get contact's info correctly at onActivityResult(). Then, editText.setText(contact.name). Strange thing is: the editText shown on UI is still empty.
The following is my code: (not completely)
public class BlacklistAddActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
static final boolean DBG = true;
private static final String TAG = "BlacklistAddActivity";
private static final String KEY_MATCH_CRITERIA = "match_criteria";
private SharedPreferences mSharedPreferences;
private ListPreference mCriteria;
private static final int CONTACT_ITEM = 0;
private static final int LOGS_ITEM = 1;
private static final String NUM_PROJECTION[] = { Phone.DISPLAY_NAME, Phone.NUMBER };
protected static final Intent CONTACT_IMPORT_INTENT;
static {
CONTACT_IMPORT_INTENT = new Intent(Intent.ACTION_GET_CONTENT);
CONTACT_IMPORT_INTENT.setType(Phone.CONTENT_ITEM_TYPE);
}
private Context mContext;
private EditText editText;
private ImageButton searchButton;
private TwSoftkeyItem mLeftSoftkey, mRightSoftkey;
private AlertDialog mSearchDialog = null;
private InputMethodManager imm;
private boolean updateMode;
private String mNumber;
private int mMatchCriteria;
#Override
protected void onCreate(Bundle savedInstanceState) {
initTitle();
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate()");
setContentView(R.layout.blacklist_number_layout);
addPreferencesFromResource(R.xml.blacklist_add_num_prefs);
mSharedPreferences = getPreferenceScreen().getSharedPreferences();
mContext = getBaseContext();
mCriteria = (ListPreference) findPreference(KEY_MATCH_CRITERIA);
editText = (EditText) findViewById(R.id.edit_text);
editText.requestFocus();
searchButton = (ImageButton) findViewById(R.id.search_button);
mLeftSoftkey = (TwSoftkeyItem) findViewById(R.id.skleft);
mRightSoftkey = (TwSoftkeyItem) findViewById(R.id.skright);
initValue();
initEvent();
imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
}
private void initTitle() {
String str = getIntent().getStringExtra("FROM");
if (str != null) {
if (DBG) Log.i(TAG, "initTitle() => from: " + str);
if (str.equals("msg")) {
setTitle(R.string.list_msg_block_num);
} else {
setTitle(R.string.list_call_block_num);
}
}
}
private void initValue() {
updateMode = getIntent().getBooleanExtra("UPDATE_MODE", false);
Log.i(TAG, "the updatemode is: "+ updateMode);
if (updateMode == true) { //from Edit
mNumber = getIntent().getStringExtra("NUMBER");
mMatchCriteria = getIntent().getIntExtra("CRITERIA", 0);
editText.setText(mNumber);
editText.setSelection(mNumber.length());
mCriteria.setValueIndex(mMatchCriteria);
mCriteria.setSummary(mCriteria.getEntry());
} else { // from Add
mCriteria.setValueIndex(0);
mCriteria.setSummary(mCriteria.getEntry());
}
}
private void initEvent() {
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDialogSearch();
}
});
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean focused) {
if (focused == true) {
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
} else {
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
});
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getAction() == KeyEvent.ACTION_UP) {
editText.requestFocus();
return true;
}
return false;
}
});
mLeftSoftkey.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NUMBER", editText.getText().toString());
intent.putExtra("CRITERIA", mCriteria.findIndexOfValue(mCriteria.getValue()));
setResult(RESULT_OK, intent);
finish();
}
});
mRightSoftkey.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_CANCELED, null);
finish();
}
});
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
if(DBG){
if(null != editText)
Log.d(TAG, "onRestoreInstanceState: Edit Text is: "+editText.getText().toString());
}
super.onRestoreInstanceState(savedInstanceState);
if(DBG){
if(null != editText)
Log.d(TAG, "onRestoreInstanceState: Edit Text is: "+editText.getText().toString());
}
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
if(null != editText)
if (DBG) Log.d(TAG, "onResume() Edit Text is: "+editText.getText().toString());
mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
mCriteria.setSummary(mCriteria.getEntry());
}
#Override
protected void onPause() {
super.onPause();
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
if (mSearchDialog != null) {
mSearchDialog.dismiss();
mSearchDialog = null;
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (DBG) Log.v(TAG, "onSharedPreferenceChanged(), key: " + key);
if (KEY_MATCH_CRITERIA.equals(key)) {
if (mCriteria.getEntry() == null) {
mCriteria.setValueIndex(0);
}
mCriteria.setValue(sharedPreferences.getString(key, mCriteria.getEntry().toString()));
mCriteria.setSummary(mCriteria.getEntry());
if (DBG) Log.v(TAG, "setValue: " + mCriteria.getEntry().toString());
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
System.out.println("DONE");
break;
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String output = "";
switch (requestCode) {
case CONTACT_ITEM:
if (resultCode != RESULT_OK) {
Log.e(TAG, "onActivityResult() => canceled");
} else {
Cursor cursor = getContentResolver().query(data.getData(), NUM_PROJECTION, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
output = cursor.getString(1);
if (DBG) Log.d(TAG, "onActivityResult() => contact output: " + output);
if (Utils.isValidNum(mContext, output)) {
editText.setText(output);
if (DBG) Log.d(TAG, "onActivityResult() Edit Text is: "+editText.getText().toString());
}
}
cursor.close();
}
}
break;
case LOGS_ITEM:
if (resultCode == RESULT_OK) {
output = data.getStringExtra("NUMBER");
if (DBG) Log.d(TAG, "onActivityResult() => logs output: " + output);
if (Utils.isValidNum(mContext, output)) {
editText.setText(output);
} else {
output = null;
Utils.displayToast(mContext, getString(R.string.vip_msg_wrong_number));
}
}
break;
}
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
if (output != null && output.length() > 0) {
editText.requestFocus();
editText.setSelection(output.length());
}
}
private void alertDialogSearch() {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle(R.string.title_search).setItems(R.array.dialog_search, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case CONTACT_ITEM:
startActivityForResult(CONTACT_IMPORT_INTENT, CONTACT_ITEM);
break;
case LOGS_ITEM:
intent = new Intent("contacts.com.sec.android.app.dialertab.calllog.LogsListActivity");
intent.putExtra("OPTION", 1);
startActivityForResult(intent, LOGS_ITEM);
break;
}
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
mSearchDialog = ad.show();
}
}
Android does not automatically backup any data on your Activity when it gets destroyed. You have to manually back your data up before it gets destroyed and restore it when your Activity is recreated.
To backup your data, you must override this method. (It will be called before your activity gets destroyed.)
#Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("key", value); //save your data in key-value pair
}
To restore your data, you must override this method. (It will be called before your activity resumes.)
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
value = savedInstanceState.getString("key"); //retrieve your data using its corresponding key
}
if your text is not set/displayed correctly you should take a close look at your onCreate(), onResume() and onRestoreInstanceState() implementation.
so the answer from arci is what i would also answer in this case.
you say it is working the first time and also working if the Activity will not get killed. But when the Activity got killed and recreated it is not working. This sounds like you work on the wrong reference at some point.Especially when you use Listeners this can happen easily
You should go into debug mode and check your Activity and EditText instance (via memory adress) are the same/correct every time you access it.
I don't realy see the problem with your code but it has to be something like this.
Note: everytime you use startActivity(), go into landscape/portrait mode or something other calling onCreate() you may get a new Activity instance.
Note II: everytime onCreate() is called you get most likely call setContentView() what ends up in getting a newly inflated/created view. this means your EditText and other Views will be a new instance.
I'm getting reports that, on some (not all) HTC Desire HD (FRF91, 2.2) and HTC EVO 4G ( PC36100|3.29.651.5, 2.2), the TextToSpeech.OnInitListener.onInit(int) is being called repeatedly (over 1500 times in the space of a few seconds) on the same object. This behaviour does not occur for any of my other users (or with other Desire HD users) AFAICT.
The code is:
TextToSpeech tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
private int mCallCount = 0; // trying to investigate potential infinite loops
#Override
public void onInit(int status) {
if ((mCallCount % 100) == 1) {
// report this
}
mCallCount++;
}
});
Anyone any ideas?
EDIT: I have also tried calling the shutdown() method (the first time multiple listener calls are detected) but this doesn't seem to help.
Maybe you should get around it with your own intermediary method, for example:
private long lastCall = 0;
private long deepBreath = 5*1000; //5 seconds
private boolean hasRested;
TextToSpeech tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
long thisCall = Calendar.getInstance().getTimeInMillis();
intermediaryMethod(status, thisCall);
}
});
//new method
public void intermediaryMethod(int status, long thisCall) {
hasRested = (thisCall-lastCall)>=deepBreath;
if (hasRested) {
lastCall = thisCall;
//do something about 'status'
}
}
This may or may not help, but I had a similar problem when call tts from a service, luckily for me I was better off doing my tts from an activity which solved the problem.
If you do this, and it is appropriate, make sure your manifest for the activity has:
android:finishOnTaskLaunch="true"
Try to create object of the Textospeech before on create ie. globally .try this code and check is it still calling many times????
public class TtsActivity extends Activity implements OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputText = (EditText) findViewById(R.id.input_text);
speakButton = (Button) findViewById(R.id.speak_button);
speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(TtsActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(TtsActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(TtsActivity.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}