How to make text green if chinese words are equals? - android

I am learning Android Studio and I have a question: I wanna say something in chinese and there compare the word/phrase I said with the one that was displayed at the screen. And if these two words are equals - make text green. else - red. But it always red after I press the mic button.
Will appriciate any help
public class SpeakingActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SPEECH_INPUT = 1000;
TextView mTextView;
TextView input;
ImageButton mImageButton;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speakingfromhome);
button = findViewById(R.id.nextSpeaking);
mTextView = findViewById(R.id.output);
mImageButton = findViewById(R.id.image);
input = findViewById(R.id.input);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeQuestions();
mTextView.setTextColor(Color.BLACK);
}
});
mImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
checkIfCorrect();
}
});
}
private void checkIfCorrect() {
if (input.toString().equals(mTextView.toString()))
mTextView.setTextColor(Color.GREEN);
else
mTextView.setTextColor(Color.RED);
}
private void changeQuestions() {
input.setText("基辅");
}
private void speak() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.CHINA.toString());
try {
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
} catch (Exception ex) {
Toast.makeText(this, "" + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mTextView.setText(result.get(0));
}
break;
}
}
}
}

The function checkIfCorrect() is the problem
Change it to:
input.toString() -> input.getText()
mTextView.toString() -> mTextView.getText()
Like:
input.getText().equals(mTextView.getText())
with getText() get the text of the TextView, doint input.toString() convert the object TextView to String
your checkIfCorrect function must look like:
private void checkIfCorrect() {
if (input.getText().equals(mTextView.getText()))
mTextView.setTextColor(Color.GREEN);
else
mTextView.setTextColor(Color.RED);
}
A better way:
private void checkIfCorrect() {
mTextView.setTextColor((input.getText().equals(mTextView.getText())) ? Color.GREEN : Color.RED )
}

Related

Button transition on Android

I make speech recognition application. But i have a problem. How can i make an transition from letter category menu to speech recognition menu, but don' add new class or new layout. Example. When i click A button, it will get A menu with speech recognition menu and so on. Sorry, i'm new in Android studio.
Here is the code for Speech Recognition
public class MainGame extends AppCompatActivity {
private TextView jawabanTxt;
private String textA;
TextView textView;
SpeechRecognizer mSpeechRecognizer;
Intent mSpeechRecognizerIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_game_act);
jawabanTxt = (TextView) findViewById(R.id.jawabanTxt);
textView = (TextView) findViewById(R.id.textView);
}
public void getSpeechInput(View view){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,Locale.getDefault());
if(intent.resolveActivity(getPackageManager())!=null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Perangkat anda tidak mendukung", Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode,int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode,data);
switch (requestCode){
case 10:
if ((resultCode == RESULT_OK &&data != null)) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
jawabanTxt.setText(result.get(0));
}
break;
}
}
}
And here is the code for the category
public class HurufActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final TextView ATxt;
ImageButton aBtn;
super.onCreate(savedInstanceState);
setContentView(R.layout.huruf_activity);
ATxt = (TextView) findViewById(R.id.aTxt);
aBtn = (ImageButton) findViewById(R.id.aBtn);
aBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
TextView textA = (TextView) ATxt.getText();
if (textA == ATxt) {
Intent intent = new Intent(HurufActivity.this, MainGame.class);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
From this:
To This:
Thank You
Something wrong is here:
try {
TextView textA = (TextView) ATxt.getText();
if (textA == ATxt) {
Intent intent = new Intent(HurufActivity.this, MainGame.class);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
I think, that this try - catch block is unnecessary and this (TextView) ATxt.getText(); will not work.
Just do something like this:
aBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HurufActivity.this, MainGame.class);
startActivity(intent);
}
});

Speech recognition result does not update EditText

I tried using a "speech to text" feature in my app.
it opens up the recording window/ dialog or whatever but the text doesn't show.
this is the code:
public void onTalk(View v){
promptSpeechInput();
}
public void promptSpeechInput()
{
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, 50);
}
catch(ActivityNotFoundException e){
Toast.makeText(this,"sorry your device doesnt support speech language",Toast.LENGTH_LONG).show();
}
}
then there's the onResult part:
public void onActivityResult(int request_code, int result_code, Intent i){
super.onActivityResult(request_code,result_code,i);
if (request_code==RESULT_OK)
if(i!=null) {
EditText locationTS = (EditText) findViewById (R.id.locationET);
ArrayList<String> result = i.getStringArrayListExtra((RecognizerIntent.EXTRA_RESULTS));
locationTS.setText(result.get(0));
}
}
locationTS is an EditText, and it does not show any text after i talk.
This worked in my case:
I had a separate Helper class as:
public class SpeechRecognitionHelper {
private static final int VOICE_RECOGNITION_REQUEST_CODE=101;
public static void run(Activity activity){
if(isSpeechRecognitionActivityPresent(activity)){
startRecognition(activity);
}
else {
Toast.makeText(activity,"You must install Google Voice Search",Toast.LENGTH_LONG).show();
installGoogleVoiceSearch(activity);
}
}
private static boolean isSpeechRecognitionActivityPresent(Activity activity){
try {
PackageManager packageManager = activity.getPackageManager();
List activities = packageManager.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH),0);
if (activities.size()!=0){
return true;
}
}
catch (Exception e){
}
return false;
}
public static void startRecognition(Activity activity){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Say Something");
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
activity.startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);
}
private static void installGoogleVoiceSearch(final Activity activity){
Dialog dialog = new AlertDialog.Builder(activity)
.setMessage("For recognition Install Google Voice Search")
.setTitle("Install voice search?")
.setPositiveButton("Install", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.voicesearch"));
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
}
Then in the MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final int VOICE_RECOGNITION_REQUEST_CODE=101;
private static final int CAMERA_REQUEST=201;
private Button buttonVoiceCommand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonVoiceCommand = (Button)findViewById(R.id.buttonVoiceCommand);
buttonVoiceCommand.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.buttonVoiceCommand){
run(MainActivity.this);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(matches.size()>0){
if(matches.get(0).indexOf("camera")>0){
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
}
else {
Toast.makeText(this,matches.get(0),Toast.LENGTH_LONG).show();
}
}
}
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
//Perform whatever you want to do (-.-)
Toast.makeText(this,"Camera Working",Toast.LENGTH_LONG).show();
}
}
}
I Toast the content of matches.get(0) You just have to set it in an edit text

Customized Camera view in ZXING code reader to show detection

I am using the ZXING QR Code Reader. It is working fine. Detecting codes etc but it does not shows any detection progress(Like red line) while it is scanning the QR Code. Here is Screenshot
And my ScanActivity is,
ScanCode.Java
public class ScanCode extends Activity implements OnClickListener {
Button btnScan;
TextView scanResult;
String text;
Bitmap bmp;
ImageView ivPic;
#Override
public void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.scan_code);
initViews();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btnScanCode) {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 1);
}
}
private void initViews() {
scanResult = (TextView) findViewById(R.id.scanResult);
ivPic = (ImageView) findViewById(R.id.capturedImg);
btnScan = (Button) findViewById(R.id.btnScanCode);
btnScan.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
String format = data.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(getApplicationContext(), contents,
Toast.LENGTH_SHORT).show();
scanResult.setText(contents);
}// if result_ok
}// onActivityResult
}
I know this answer is bit late but I've just used Zxing barcode/QR-Code scanner recently in my app, if anyone has issue implementing it just follow the steps below (Using Android Studio Official IDE for android).
First add dependencies in app --> build.gradle file
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
compile 'com.google.zxing:core:3.2.1'
}
Activity Usage:
public class MainActivity extends AppCompatActivity {
Button btnScan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScan = (Button) findViewById(R.id.btnScan);
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBarcode();
}
});
}
private void scanBarcode()
{
new IntentIntegrator(this).initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
}
}
}
If you want to use custom callback and BarCodeView. Zxing provide this functionality simply make layout file
<com.journeyapps.barcodescanner.CompoundBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.journeyapps.barcodescanner.CompoundBarcodeView>
<TextView
android:id="#+id/tvScanResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan Results will be shown here"
android:textColor="#android:color/white"
android:textStyle="bold"/>
In Activity use the following code
public class MainActivity extends AppCompatActivity
{
CompoundBarcodeView barcodeView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barcodeView = (CompoundBarcodeView) findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
barcodeView.setStatusText("");
}
#Override
protected void onResume()
{
super.onResume();
barcodeView.resume();
isScanned = false;
}
#Override
protected void onPause()
{
super.onPause();
barcodeView.pause();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
private BarcodeCallback callback = new BarcodeCallback()
{
#Override
public void barcodeResult(BarcodeResult result)
{
if (result.getText() != null)
{
barcodeView.setStatusText(result.getText());
tvscanResult.setText("Data found: " + result.getText());
}
//you can also Add preview of scanned barcode
//ImageView imageView = (ImageView) findViewById(R.id.barcodePreview);
//imageView.setImageBitmap(result.getBitmapWithResultPoints(Color.YELLOW));
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints)
{
System.out.println("Possible Result points = " + resultPoints);
}
};
}
Source zxing-android-embedded. Hope someone get help from this solution

EditText displayed nothing when resuming. (activity destroyed by android system)

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.

Android Handler unable to access GUI elements

I feel kind of dumb asking this question because I have another app that this works for fine or at least I think it is the same. I definitely need another set of eyes on this because to me, it looks like it should work. My code is below:
public class InventorySystemActivity extends Activity {
private EditText barcode;
private EditText proddesc;
private EditText quantity;
public String scan_result;
public int which;
private InventorySystemDB db;
public Item singleItem;
public Item[] itemList;
private Thread t;
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
barcode.setText(scan_result);
proddesc.setText(singleItem.name);
quantity.setText(singleItem.quantity);
break;
case 3:
updateUI();
pd.dismiss();
}
}
};
public static Intent in = new Intent("com.google.zxing.client.android.SCAN");
private ProgressDialog pd;
private Thread dbt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.db = new InventorySystemDB(this);
try {
this.db.createDataBase();
this.db.openDataBase();
} catch (Exception e) {
e.printStackTrace();
}
this.dbt = new Thread(this.db);
setContentView(R.layout.main);
Button scan = (Button) findViewById(R.id.scan);
scan.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(in, 0);
}
});
Button search = (Button) findViewById(R.id.searchbutton);
search.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
pd.show();
which = 1;
scan_result = barcode.getText().toString();
dbt.start();
}
});
barcode = (EditText) findViewById(R.id.barcodenum);
proddesc = (EditText) findViewById(R.id.proddesc);
quantity = (EditText) findViewById(R.id.prodquantity);
pd = new ProgressDialog(this);
pd.setMessage("Loading data...");
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
scan_result = intent.getStringExtra("SCAN_RESULT");
barcode.setText(scan_result);
} else if (resultCode == RESULT_CANCELED) {
}
}
}
private void updateUI() {
barcode.setText(singleItem.upc);
proddesc.setText(singleItem.name);
quantity.setText("0");
}
}
All my thread does is it takes the UPC number and pulls up info from a couple websites. The code sends the message to the handler just fine and I've made a few apps like this using threads and handlers, not sure why I have this issue now. Anyway, I can dismiss the ProgressDialog, but I am unable to update any UI objects. It all looks fine to me, so I really need some more sets of eyes on this. Thanks guys.
You need to do UI changes in runOnUIThread()

Categories

Resources