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

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.

Related

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.
}

Using methods from another Java class

How can I use method speakOut from (Detail java) in (NoteEdit java)
so I use it after menu_search instead of viewDetails(mDateText).
This is Detail class
public class Detail extends Activity implements TextToSpeech.OnInitListener{
private Button prsstospeak;
public String data;
private int result=0;
private TextToSpeech tts;
private TextView passedView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.disp);
tts = new TextToSpeech(this, this);
prsstospeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
//It will called before TTS started
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
//check status for TTS is initialized or not
if (status == TextToSpeech.SUCCESS) {
//if TTS initialized than set language
result = tts.setLanguage(Locale.US);
// tts.setPitch(5); // you can set pitch level
// tts.setSpeechRate(2); //you can set speech speed rate
//check language is supported or not
//check language data is available or not
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "Missing data", Toast.LENGTH_LONG).show();
//disable button
prsstospeak.setEnabled(false);
} else {
prsstospeak.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
if(result!=tts.setLanguage(Locale.US))
{
Toast.makeText(getApplicationContext(), "Enter right Words...... ", Toast.LENGTH_LONG).show();
}else
{
//speak given text
tts.speak(data, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
This is NoteEdie:
public class NoteEdit extends Activity {
public static int numTitle = 1;
public static String curDate = "";
public static String curText = "";
private EditText mTitleText;
private EditText mBodyText;
private TextView mDateText;
private Long mRowId;
private Cursor note;
private NotesDbAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
setTitle(R.string.app_name);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateText = (TextView) findViewById(R.id.notelist_date);
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("d'/'M'/'y");
curDate = formatter.format(curDateTime);
mDateText.setText(""+curDate);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
}
public static class LineEditText extends EditText{
public LineEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(Color.BLUE);
}
private Rect mRect;
private Paint mPaint;
#Override
protected void onDraw(Canvas canvas) {
int height = getHeight();
int line_height = getLineHeight();
int count = height / line_height;
if (getLineCount() > count)
count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
int baseline = getLineBounds(0, r);
for (int i = 0; i < count; i++) {
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
baseline += getLineHeight();
super.onDraw(canvas);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.noteedit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_about:
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
return true;
case R.id.menu_delete:
if(note != null){
note.close();
note = null;
}
if(mRowId != null){
mDbHelper.deleteNote(mRowId);
}
finish();
return true;
//speech button
case R.id.menu_search:
viewDetails(mDateText);
finish();
return true;
case R.id.menu_save:
saveState();
finish();
return true;
/* case android.R.id.home:
finish(); */
default:
return super.onOptionsItemSelected(item);
}
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if(mRowId == null){
long id = mDbHelper.createNote(title, body, curDate);
if(id > 0){
mRowId = id;
}else{
Log.e("saveState","failed to create note");
}
}else{
if(!mDbHelper.updateNote(mRowId, title, body, curDate)){
Log.e("saveState","failed to update note");
}
}
}
private void populateFields() {
if (mRowId != null) {
note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
curText = note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
}
}
public void viewDetails(View view){
String data= mDbHelper.getALLData();
}
}
How can I use method speakOut from (Detail java) in (NoteEdit java)
so I use it after menu_search instead of viewDetails(mDateText).
Its not a good way to call a method in activity from another activity !
You have 2 solution :
the easiest way (I think) : if you have a method (or methods) that
you use alot and in different classes (such as activity or
fragment), put them in a class and import this class to your
activity and use this method.
call the activity that contain this method with
startActivityForResult and intent and return the result your
activity. For more info about how is this way:
How to manage `startActivityForResult` on Android?

How to change the onclick button become onclick and longclick together?

This is the main activity. How can i edit the code so that the button can become onclick and long click? I would like to make the button perform a task when clicked while it performs another task while I long click it.
public class AndroidRemoteActivity extends Activity implements OnClickListener {
private TextView logview;
private Button connect, deconnect;
private ImageView forwardArrow, backArrow, rightArrow, leftArrow, stop;
private BluetoothAdapter mBluetoothAdapter = null;
private String[] logArray = null;
private BtInterface bt = null;
static final String TAG = "Chihuahua";
static final int REQUEST_ENABLE_BT = 3;
//This handler listens to messages from the bluetooth interface and adds them to the log
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String data = msg.getData().getString("receivedData");
addToLog(data);
}
};
//this handler is dedicated to the status of the bluetooth connection
final Handler handlerStatus = new Handler() {
public void handleMessage(Message msg) {
int status = msg.arg1;
if(status == BtInterface.CONNECTED) {
addToLog("Connected");
} else if(status == BtInterface.DISCONNECTED) {
addToLog("Disconnected");
}
}
};
//handles the log view modification
//only the most recent messages are shown
private void addToLog(String message){
for (int i = 1; i < logArray.length; i++){
logArray[i-1] = logArray[i];
}
logArray[logArray.length - 1] = message;
logview.setText("");
for (int i = 0; i < logArray.length; i++){
if (logArray[i] != null){
logview.append(logArray[i] + "\n");
}
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_remote);
//first, inflate all layout objects, and set click listeners
logview = (TextView)findViewById(R.id.logview);
//I chose to display only the last 3 messages
logArray = new String[3];
connect = (Button)findViewById(R.id.connect);
connect.setOnClickListener(this);
deconnect = (Button)findViewById(R.id.deconnect);
deconnect.setOnClickListener(this);
forwardArrow = (ImageView)findViewById(R.id.forward_arrow);
forwardArrow.setOnClickListener(this);
backArrow = (ImageView)findViewById(R.id.back_arrow);
backArrow.setOnClickListener(this);
rightArrow = (ImageView)findViewById(R.id.right_arrow);
rightArrow.setOnClickListener(this);
leftArrow = (ImageView)findViewById(R.id.left_arrow);
leftArrow.setOnClickListener(this);
stop = (ImageView)findViewById(R.id.stop);
stop.setOnClickListener(this);
}
//it is better to handle bluetooth connection in onResume (ie able to reset when changing screens)
#Override
public void onResume() {
super.onResume();
//first of all, we check if there is bluetooth on the phone
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Log.v(TAG, "Device does not support Bluetooth");
}
else{
//Device supports BT
if (!mBluetoothAdapter.isEnabled()){
//if Bluetooth not activated, then request it
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else{
//BT activated, then initiate the BtInterface object to handle all BT communication
bt = new BtInterface(handlerStatus, handler);
}
}
}
//called only if the BT is not already activated, in order to activate it
protected void onActivityResult(int requestCode, int resultCode, Intent moreData){
if (requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
//BT activated, then initiate the BtInterface object to handle all BT communication
bt = new BtInterface(handlerStatus, handler);
}
else if (resultCode == Activity.RESULT_CANCELED)
Log.v(TAG, "BT not activated");
else
Log.v(TAG, "result code not known");
}
else{
Log.v(TAG, "request code not known");
}
}
//handles the clicks on various parts of the screen
//all buttons launch a function from the BtInterface object
#Override
public void onClick(View v) {
if(v == connect) {
addToLog("Trying to connect");
bt.connect();
}
else if(v == deconnect) {
addToLog("closing connection");
bt.close();
}
else if(v == forwardArrow) {
//addToLog("Move Forward");
bt.sendData("F");
}
else if(v == backArrow) {
//addToLog("Move back");
bt.sendData("B");
}
else if(v == rightArrow) {
//addToLog("Turn Right");
bt.sendData("R");
}
else if(v == leftArrow) {
//addToLog("Turn left");
bt.sendData("L");
}
else if(v == stop) {
//addToLog("Stopping");
bt.sendData("S");
}
}
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_android_remote);
final Button button = (Button) findViewById(R.id.forward_arrow);
button.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
if (v==forwardArrow){
bt.sendData("f");
}
return true;
}
});
}
}
}
use on click listner and on long click listner
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
})

Handler call to notifyDataSetChanged() not executing

I have an Handler registered in an Activity. handleMessage() calls notifyDataSetChanged on an Adapter. Things work while the Activity has initial focus. However, when I navigate out of the Activity and back in, notifyDataSetChanged() does not work.
FileAdapter is an ArrayAdapter. MergeAdapter is a custom class by CommonsWare. _mergeAdapter contains _fileAdapter.
Activity code:
public void setUpDownloadHandler() {
// Define the Handler that receives messages from the thread and update the progress
_downloadHandler = new Handler() {
public void handleMessage(Message message) {
super.handleMessage(message);
String fileId = (String) message.obj;
int progress = message.arg1;
FileInfo tempFile = null;
for (FileInfo file: _files) {
if (file.getFileId().equals(fileId)) {
file.setDownloadProgress(progress);
tempFile = file;
}
}
if (tempFile != null) {
_files.remove(tempFile);
_files.add(tempFile);
}
_fileAdapter.notifyDataSetChanged();
_mergeAdapter.notifyDataSetChanged();
}
};
}
Passing the handler:
RunnableTask task = new DownloadFileRunnableImpl(application, the_workspace_url, the_file_info, the_workspace_info.getTitle(), the_internal_storage_directory,
_downloadHandler);
Background thread code:
if(temp > previous) {
Message message = new Message();
message.arg1 = _currentProgress.intValue();
message.obj = _fileId;
_progressHandler.sendMessage(message);
previous = temp;
}
The other piece of information is that I'm passing the handler through a Binder and then into the runnable. I do this to run the background thread in a Service. I don't think this is the problem.
EDIT:
It seems like the handler is not associated with the activity the second time it is navigated to (perhaps because onCreate creates a new handler). Is there a way to re-associate or retain the old handler?
Update
The activity is being destroyed when it loses focus to another activity.
I would try putting a log message in your activity's onDestroy method to see if it is getting destroyed, when you navigate away from your activity. So your task may have the handler from the old activity.
Here is my answer, I relied heavily on http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentRetainInstance.html
Really just took their code and changed it so that I have to remake the fragment everytime I want to start the thread (work) again. And it communicates with the Activity through a handler.
public class Main extends Activity implements WorkProgressListener {
private static final String TAG = "tag";
private Handler handler;
private Button startWorkBtn;
private ProgressDialog progressDialog;
private boolean onSaveInstanceFlag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG,"Main onCreate " + Utils.getThreadId());
setContentView(R.layout.main);
handler = new ProgressHandler();
startWorkBtn = (Button)this.findViewById(R.id.start_work_btn);
startWorkBtn.setEnabled(false);
startWorkBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v) {
Log.i("tag","Main: startWorkBtn onClick ");
startWorkBtn.setEnabled(false);
FragmentManager fm = getFragmentManager();
Fragment workF = (Fragment)fm.findFragmentByTag("work");
if (null == workF) {
workF = new WorkFragment();
Log.i(TAG,"Main new WorkF" + Utils.getThreadId());
startProgressDialog(true);
startWorkBtn.setEnabled(false);
fm.beginTransaction().add(workF, "work").commit();
Log.i(TAG,"Main add(workF) " + Utils.getThreadId());
}
else {
// should never be able to get here.
}
}
});
FragmentManager fm = getFragmentManager();
Fragment loadingFragment = fm.findFragmentByTag("work");
Log.i(TAG,"Main findFragment " + Utils.getThreadId());
if (null == loadingFragment) {
this.startWorkBtn.setEnabled(true);
}
else {
// could also decide to show progress dialog based on savedInstanceState
this.startProgressDialog(true);
}
} // end onCreate
#Override
public void onRestart() {
Log.i(TAG,"Main onRestart " + Utils.getThreadId() );
super.onRestart();
this.onSaveInstanceFlag = false;
}
#Override
public void onResume () {
Log.i(TAG,"Main onResume " + Utils.getThreadId());
super.onResume();
this.onSaveInstanceFlag = false;
}
#Override
public void onSaveInstanceState (Bundle savedInstanceState) {
Log.i(TAG,"Main onSaveInstanceState "+ Utils.getThreadId());
this.onSaveInstanceFlag = true;
super.onSaveInstanceState(savedInstanceState);
if (null != this.progressDialog) {
savedInstanceState.putBoolean("progressDialog", true);
}
else {
savedInstanceState.putBoolean("progressDialog", false);
}
}
#Override
public void onStop () {
Log.i(TAG,"Main onStop " + Utils.getThreadId());
super.onStop();
}
#Override
public void onDestroy () {
Log.i(TAG,"Main onDestroy " + Utils.getThreadId());
super.onDestroy();
this.closeProgressDialog();
this.handler.removeCallbacksAndMessages(null);
}
public class ProgressHandler extends Handler {
#Override
public void handleMessage (Message msg) {
Log.i(TAG,"Main ProgressDialogHandler handleMessage");
Bundle b = msg.getData();
boolean isDone = b.getBoolean("isDone");
String tag = b.getString("tag");
if (isDone && !onSaveInstanceFlag) {
FragmentManager fm = getFragmentManager();
Fragment loader = (Fragment)fm.findFragmentByTag(tag);
fm.beginTransaction().remove(loader).commit();
closeProgressDialog();
Main.this.startWorkBtn.setEnabled(true);
}
}
}
#Override
public void sendProgress(String tag, int progress, int max) {
if ( progress == max) {
Log.i(TAG,"Main sendProgress " + Utils.getThreadId());
Message message = handler.obtainMessage();
Bundle b = new Bundle();
b.putBoolean("isDone", true);
b.putString("tag",tag);
message.setData(b);
this.handler.sendMessage(message);
}
}
private void startProgressDialog(boolean show) {
this.progressDialog = new ProgressDialog(this);
this.progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
this.progressDialog.setMessage("loading");
this.progressDialog.setCancelable(false);
this.progressDialog.show();
}
private void closeProgressDialog() {
if (null != this.progressDialog) {
progressDialog.cancel();
this.progressDialog = null;
}
}
} // end Main
public class WorkFragment extends Fragment {
private static final String TAG = "tag";
private boolean mReady = false;
private boolean mQuiting = false;
private boolean done = false;
public WorkFragment () {}
final Thread mThread = new Thread() {
#Override
public void run () {
synchronized(this) {
while (!mReady) {
Log.i(TAG,"WorkF notReady"+ Utils.getThreadId());
if (mQuiting) {
return;
}
try {
wait();
} catch (InterruptedException e) {
}
}
} // end synchronized
Log.i(TAG,"WorkF starting work "+ Utils.getThreadId());
try {
Log.i(TAG,"WorkF about to sleep"+ Utils.getThreadId());
Thread.currentThread().sleep(10000l);
Log.i(TAG,"WorkF almost finished "+ Utils.getThreadId());
done = true;
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized(this) {
while (!mReady) {
Log.i(TAG,"Activity notReady"+ Utils.getThreadId());
if (mQuiting) {
return;
}
try {
wait();
} catch (InterruptedException e) {
}
}
((WorkProgressListener)getActivity()).sendProgress(WorkFragment.this.getTag(), 100, 100);
} // end synchronized 2
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.i(TAG,"WorkF, onAttach: "+ Utils.getThreadId());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG,"WorkF, onCreate: "+ Utils.getThreadId());
setRetainInstance(true);
mThread.start();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG,"WorkF, onActivityCreated: "+ Utils.getThreadId());
if (done) {
((WorkProgressListener)getActivity()).sendProgress(WorkFragment.this.getTag(), 100, 100);
}
synchronized (mThread) {
mReady = true;
mThread.notify();
}
}
#Override
public void onStart()
{
super.onStart();
Log.i(TAG,"WorkF, onStart: "+ Utils.getThreadId() );
}
#Override
public void onDestroy() {
synchronized (mThread) {
mReady = false;
mQuiting = true;
mThread.notify();
}
super.onDestroy();
}
#Override
public void onDetach() {
synchronized (mThread) {
mReady = false;
mThread.notify();
}
super.onDetach();
}
public void restart() {
synchronized (mThread) {
mThread.notify();
}
}
}// end WorkFragment
public interface WorkProgressListener {
public void sendProgress (String tag, int progress, int max);
}

How can i get lock unlock screen on emulator in android?

Recently I am doing one project in emulator lock and unlock screen. I put one button. I want to do that if i press that button I want to lock the phone.
my problem is when i press the button nothing is happening.
please give me any idea about this.
how i get lock unlock perform using this code.
public class Test extends Activity implements OnClickListener{
/** Called when the activity is first created. */
Button btn1;
private KeyguardManager mKeyguardManager;
private KeyguardManager.KeyguardLock mKeyguardLock;
private static final String TAG = "ALERTLock";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(this);
int flags = getFlagsForVersion();
getWindow().addFlags(flags);
mKeyguardManager = (KeyguardManager)
getSystemService(Context.KEYGUARD_SERVICE);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==btn1)
{
disableKeyguard();
}
else
{
enableKeyguard();
}
}
private int getFlagsForVersion() {
final String possibleFlags[] = new String[] {
"FLAG_SHOW_WHEN_LOCKED",
"FLAG_DISMISS_KEYGUARD",
"FLAG_TURN_SCREEN_ON"
};
int flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
for(String flag:possibleFlags) {
try {
Field field = WindowManager.LayoutParams.class.getField(flag);
int value = field.getInt(null);
flags |= value;
}
catch(NoSuchFieldException e) { }
catch(IllegalAccessException e) { }
}
return flags;
}
private synchronized void enableKeyguard() {
if (mKeyguardLock != null) {
mKeyguardLock.reenableKeyguard();
mKeyguardLock = null;
}
}
private synchronized void disableKeyguard() {
if (mKeyguardLock == null) {
mKeyguardLock = mKeyguardManager.newKeyguardLock(TAG);
mKeyguardLock.disableKeyguard();
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
disableKeyguard();
}
#Override
public void onResume() {
super.onResume();
disableKeyguard();
}
}
//try this once
and check the logcat is printing the line enable
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
//do this
Log.d("clicked enable","-----");
enableKeyguard();
break;
}

Categories

Resources