Alert Dialog dismissing on ScreenLock - android

My Alert Dialog is dismissing when screen is locked and Unlocked.In my case,
1)Starting connection in asynctask (which is inner class),here progress dialog starts saying "please wait...".
2)After completion of connection ProgressDilog is dismissed and Alert Message is shown.
So,In this process when i lock the screen when Connection is started, Alert Message is not shown and the same Activity in previous state is shown.
alertBuilder = new AlertDialog.Builder(Registration.this);
alertBuilder.setMessage(Constants.TEXT_REGISTERED_SUCCESSFULLY);
alertBuilder.setCancelable(false);
alertBuilder.setPositiveButton(Constants.TEXT_OK, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Util.saveData(Registration.this);
Intent thanksYouIntent = new Intent(Registration.this,ThankYouActivity.class);
Registration.this.finish();
} });
alertBuilder.create().show();
This is my Code for raising the dialog.I heard to bind the dialog to activity so i tried like alertBuilder.create().setOwnerActivity(RegistrationActivity.this).This is also not showing any results.
One thing I have no clarity is what happens to inner asyncTask which is running Connection when the parent activity is paused.Any body plz help me out.
Thanks in advance,
Sha.

Correct me if am wrong.Form my observation when an activity is in paused state,the corresponding AsyncTask is stopped.
So,In my case when screen is locked connection which is in doInBackground of asynctask already starts execution.But due to the screen lock reasons asyncTask is stopped and onPostExecute is not Completing successfully.My alertDialog which is in onpostexecute is not displaying.So,I'm saving the response state of the connection and displaying it when oncreate is called on screen Unlock using a boolean check.
The below is the code.This is huge but couldn't cut more than that to explain my case.
private static boolean alertDialogDismissedUnExpectedly;
private static String _alertMessage; //alert Message is for saving the previous alert message displaying when screen is locked
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//coding part
_registerImageView.setOnClickListener(new OnClickListener() {//here the asynctask starts running on click
private String _response;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
_alertMessage = "";
//post data for response
String postcontent="Sucess";
if(Constants.LOG)Log.d("Content to post is :", ""+postcontent);
ResgiserAsyncTask asyncTask = new ResgiserAsyncTask(postcontent);
asyncTask.execute(null);
}
if(alertDialogDismissedUnExpectedly && savedInstanceState != null){ // check for Alert Message dismissed unexpectedly
if(_alertMessage == null ? true : _alertMessage.equalsIgnoreCase("")){ //intialise the last state of alert message if no alert message is set
_alertMessage = _Engine.get_returnMessage();//this is my engine where parsing is done,So i'll get the previous response of connection
}
if(_alertMessage != null){
if(_alertMessage.equalsIgnoreCase(Constants.TEXT_REGISTERED_SUCCESSFULLY) || _alertMessage.equalsIgnoreCase(Constants.TEXT_SUCCESS)){//my success case
raiseSuccessDialog();//this is internal method
}else{//failure case
raiseDialog(_alertMessage);//this is internal method
}
}
}else{
alertDialogDismissedUnExpectedly = false;
_alertMessage = "";
}
}
private class ResgiserAsyncTask extends AsyncTask{
private String _postContent;
private Document _document;
public ResgiserAsyncTask(String postContent) {
// TODO Auto-generated constructor stub
alertDialogDismissedUnExpectedly = true;//set the coolean to true and make it false Clicklistener of alertDialog
_postContent= postContent;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
_document = Util.postPage(Constants.URL_REGISTRATION, _postContent, true);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(_document != null){
String _response = _Engine.parseRegistration(_document);
if(!Constants.TEXT_SUCCESS.equalsIgnoreCase(_response)){
raiseDialog(_response);
}else{
raiseSuccessDialog();
}
}
}
}
private void raiseSuccessDialog(){
_alertMessage = Constants.TEXT_REGISTERED_SUCCESSFULLY;
alertBuilder = new AlertDialog.Builder(Registration.this);
alertBuilder.setMessage(Constants.TEXT_REGISTERED_SUCCESSFULLY);
alertBuilder.setCancelable(false);
alertBuilder.setPositiveButton(Constants.TEXT_OK, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
alertDialogDismissedUnExpectedly = false;
Intent thanksYouIntent = new Intent(Registration.this,ThankYouActivity.class);
startActivity(thanksYouIntent);
}
});
alertBuilder.create().show();
}
private void raiseDialog(String message) {
// TODO Auto-generated method stub
_alertMessage = message; // intialise the message to the raised dialog so that when screen is locked the alert can be displayed once again
AlertDialog.Builder alertBuilder = new Builder(Registration.this);
alertBuilder.setMessage(message);
alertBuilder.setCancelable(false);
alertBuilder.setPositiveButton(Constants.TEXT_OK, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
alertDialogDismissedUnExpectedly = false;
}
});
alertBuilder.create().show();
}
Hope it helps for those who faced the same problem.Any better ideas invited.

Override onCreateDialog() for showing dialogs. It can helps.

#sha
there are some events raised during screen off and on you need to control that too.... the link http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/ shoes some examples regarding this

Related

Dismiss Custom Alert Dialog on Back button pressed of hardware in android

I am having problem on back button of hardware. In my main Activity, I have one List view(say 1). When I click on item of this List view(1), one Alert Dialog appears, in this alert dialog, there is one List view(say 2). Data of this List view(2) are being repeated when I press back button of hardware. I have also put cancel image on this alert dialog to dismiss, when I press this cancel image, data are not being repeated. I tried different methods onResume(), onPause(), onDestroy(), onRestart() to clear the array for List view(2), but nothing works. Here is my code...
case LIST_DIALOG :
LayoutInflater inflater2 = LayoutInflater.from(this);
View dialogview1 = inflater2.inflate(R.layout.listdialog, null);
AlertDialog.Builder dialogbuilder2 = new AlertDialog.Builder(this);
dialogbuilder2.setView(dialogview1);
dialogDetails = dialogbuilder2.create();
case LIST_DIALOG:
AlertDialog alertDialog1 = (AlertDialog) dialog;
// Cancel Alert Dialog
ImageView ivCancel = (ImageView) alertDialog1.findViewById(R.id.imgCancel);
ivCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dismissDialog(LIST_DIALOG);
arr2.clear();
}
});
// Friend List
showFriendList();
break;
// List view data are inserted with this function call
private void showFriendList() {
// TODO Auto-generated method stub
Request.executeMyFriendsRequestAsync(friendSession, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
// TODO Auto-generated method stub
// arr2 = new ArrayList<String>();
for(GraphUser user : users)
{
arr2.add(user.getName());
}
adapter2 = new ArrayAdapter<String>(getBaseContext(), R.layout.single_row, R.id.txt,arr2);
lvDialog.setAdapter(adapter2);
lvDialog.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
adapter2.notifyDataSetChanged();
itemCount = lvDialog.getCount();
Toast.makeText(getBaseContext(), "" + itemCount, 1000).show();
}
});
}
// I tried these methods, but nothing works...
#Override
public void onResume()
{
super.onResume();
ShowSavedFiles();
arr2.clear();
}
#Override
public void onPause()
{
super.onPause();
arr1.clear();
arr2.clear();
}
#Override
public void onBackPressed() {
//super.onBackPressed();
// finish your Activity
arr2.clear();
return;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
arr2.clear();
dismissDialog(LIST_DIALOG);
}
return false;
}
I'm not sure but might be adding the following code to your onKeyDown method might help out :
return super.onKeyDown(keyCode, event);

Code after ProgressDialog (Android) gets executed before the ProgressDialog's timer runs out

When I click a button BUTTON, I'm showing a ProgressDialog popup, which shows the round circling progress meter thing. Now that's supposed to run for N seconds, and after that, there's some code which executes only after the temporarily created ProgressDialog instance vanishes (when N seconds are up). The code shows some text in a TextView, and the text changes on every click of BUTTON, and an image which should change too. But the change is to be visible only after the ProgressDialog has ended
But the problem is, as soon as I click BUTTON, the text already changes, and the ProgressDialog circling dialog plays on for N seconds, which is not supposed to happen - the text should change only after the ProgressDialog finished circling for its N seconds, and the app View is back in focus, and the text gets changed then.
Here's the code:
BUTTON.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
imageView.setVisibility(ImageView.INVISIBLE);
//Choosing MESXs type to show =================================
if(mTSFlag==1)
mTS=holA;
else
mTS=holB;
// ProgressDialog =================================
final ProgressDialog progressRing=ProgressDialog.show(MainActivity.this, "Please wait..", "This takes time..", true);
progressRing.setCancelable(false);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try
{
Thread.sleep(3000);
}catch(Exception e){}
progressRing.dismiss();
}
}).start();
//Image choosing logic =================================
imageView.setVisibility(ImageView.VISIBLE);
if(pTOGGLE)
imageView.setImageResource(R.drawable.IMG_XXT);
else
imageView.setImageResource(R.drawable.IMG_XYT);
wIHM_result.setText(mTS);
}
});
The problem is, that it's as if the Image Logic part (marked by a header comment), is run before the ProgressDialgo part of the code. The appropriate image shows up, the text is changed, I can see all that in the dimmed app screen while the ProgressDialog is making it's progress to the end of N seconds.
I want it to show the changed image and text (objects here in code - imageView and wIHM respectively) after the Progress Dialog circling thing has finished circling and the focus is back on the app's view.
Use AsynTask class.
Write the button click in it and use progress Dialog in AsynTask..
AsynTask have method like initBackground() , preExecute() , postExecute() ..
Start the progress Dialog in preExecute... write the logic in initBackground with ending the logic last line with ProgressDialog.dismiss(); and write the textchange code and imagechange logic in postExecute();
BUTTON.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ABC.Execute();
}
});
public class ABC extends AsyncTask<Void,Void,Void>
{
ProgressDialog downloadProgressDialog =new ProgressDialog(Accounts.this);
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
//Set your text and image object here....
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
downloadProgressDialog.setMessage("Message");
downloadProgressDialog.setCancelable(false);
downloadProgressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0)
{
//Write your code here......
downloadProgressDialog.dismiss();
}
}
You'd better use the AsyncTask to do. If you want to fix the issue based on your code, you should do like these:
BUTTON.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
imageView.setVisibility(ImageView.INVISIBLE);
//Choosing MESXs type to show =================================
if(mTSFlag==1)
mTS=holA;
else
mTS=holB;
// ProgressDialog =================================
final ProgressDialog progressRing=ProgressDialog.show(MainActivity.this, "Please wait..", "This takes time..", true);
progressRing.setCancelable(false);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try{
Thread.sleep(3000);
//Don't run your UI method in non-Ui thread.
//move progressRing.dismiss() to runOnUiThread();
yourActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressRing.dismiss();
//Image choosing logic =================================
imageView.setVisibility(ImageView.VISIBLE);
if(pTOGGLE)
imageView.setImageResource(R.drawable.IMG_XXT);
else
imageView.setImageResource(R.drawable.IMG_XYT);
wIHM_result.setText(mTS);
}
}catch(Exception e){
}
}
}).start();
}
});
progressRing.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
// Image choosing logic codes should be here for processing after dialog showed
}
});
setOnShowListener sets a listener to be invoked when the dialog is shown

User input alertdialog not opening after button click in BluetoothChat

Hi I'm an android newbie and I've been stuck for a week on this. Any help would be appreciated! I've done a lot of research and can't figure out what is wrong. I've successfully run the bluetoothchat sample code on two phones and successfully communicated via bluetooth. I've also successfully written and run a standalone app that, after a button click on the main activity, opens a custom alertdialog which accepts user input, and passes the input back to the main activity. But when I write the alertdialog code into the BluetoothChat code, nothing happens when I click the button. I've tried to step through the debugger with the phone but with no luck. It doesn't seem to step to the code containing the button click. There are no errors showing. Why won't the alertdialog pop up on button click? Here's the BluetoothChat.java code I've modified :
public class BluetoothChat extends Activity implements OnClickListener{
final Context context = this;
private Button rButton;
View rScreen;
private EditText mAlertDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//components from main.xml
//When button is clicked, the alert dialog is pulled up
rButton = (Button)findViewById(R.id.buttonr);
mAlertDialog = (EditText)findViewById(R.id.edittextresultm);
//add button listener
rButton.setOnClickListener(new OnClickListener() {
//#Override
public void onClick_register(View view) {
String title = "title";
String buttonOk = "OK";
String buttonCancel = "Cancel";
String madd, name;
//get review.xml view
LayoutInflater li = LayoutInflater.from(context);
View rView = li.inflate(R.layout.review, null);
//AlertDialog dialog;
AlertDialog.Builder adRegister = new AlertDialog.Builder(context);
//set review.xml to adRegister builder
adRegister.setView(rView);
//set title
adRegister.setTitle(title);
//Set EditText views to get user input
final EditText mField = (EditText)rView.findViewById(R.id.editTextm);
final EditText nField = (EditText)rView.findViewById(R.id.editTextn);
//set dialog message
adRegister.setMessage("Message")
.setCancelable(false)
.setPositiveButton(buttonOk, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String madd = mField.getText().toString();
String name = nField.getText().toString();
//get user input and set it to result on main activity
mAlertDialog.setText(mField.getText());
}
})
.setNegativeButton(buttonCancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//if this button is clicked, close current activity
dialog.cancel();
}
});
//Create alert dialog
AlertDialog alertDialog = adRegister.create();
//dialog= adRegister.create();
//show it
adRegister.show();
//dialog.show();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
Write your inputDialog code in OnClick Method.
Enjoy!!

getParcelableArrayListExtra issue. Program crashing

I'm trying to pass an arraylist of objects to a new activity, I followed a tutorial and it looks as if I've done everything right but my program kept crashing. I've commented out the majority of the code to isolate the line that seems to be causing the crash and its the getParcelableArrayListExtra bit that seems to be the problem. Can anyone help?
New Activity:
public class DatabaseSearch extends ListActivity{
DBAdapter db = new DBAdapter(this);
ArrayList<String> listrecipes = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databasesearch);
Intent i = getIntent();
if (i != null) {
ArrayList<mydata> data = i.getParcelableArrayListExtra ("com.example.MyPantry.array");
}
}
}
Bit of code from the old activity--
I don't know if it matters but the new activity is being called within a dialog box
#Override
protected Dialog onCreateDialog(int id)
{
switch(id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("List all recipes that match over:")
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
switch (item)
{
case 0:
percentageselected = 25;
break;
case 1:
percentageselected = 50;
break;
case 2:
percentageselected = 75;
break;
case 3:
percentageselected = 100;
break;
default:
break;
}
}
})
.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
if (percentageselected == 0)
{
Toast.makeText(getBaseContext(), "Please make a selection", Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(getBaseContext(), DatabaseSearch.class);
intent.putParcelableArrayListExtra("com.example.MyPantry.array", array);
startActivity(intent);
}
}
})
.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
dialog.dismiss();
}
})
.create();
}
return null;
}
My objects inside the array I want to pass--
public class mydata implements Parcelable {
private int recipeID;
private int ingredientID;
private String check = "unchecked";
private int percentage = 0;
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel data, int flags) {
// TODO Auto-generated method stub
data.writeInt(recipeID);
data.writeInt(ingredientID);
data.writeString(check);
data.writeInt(percentage);
}
//Other functions
}
Lastly I have this class that the tutorial instructed me to make...
public class MyCreator implements Parcelable.Creator<mydata> {
#Override
public mydata createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new mydata(source);
}
#Override
public mydata[] newArray(int arg0) {
// TODO Auto-generated method stub
return new mydata[arg0];
}
}
So I know it's quite a bit to look at but I'm just trying to be thorough. The problem starts to occur inside the if statement in the new activity.
When just passing data between intents, you can just mark your classes as Serializable (by implementing the Serializable marker interface) and add them directly to the intent as extras without having to do all this work with parcelable (parcelable is really only needed when binding to services).
It's hard to say why you're getting the error without seeing a stack trace or the constructor for mydata that populates the class using the Parcel.

BACK Button is not working ,while progressDialog is running

I have a little problem; I hope you can help me.
While progressDialog is running, the user presses the BACK Button. The current Activity progressDialog goes to Background, but progressDialog is running.
My problem is that when the user clicks on the BACK button, progressDialog should be foreground Activity, stop current progress and ask "Do you want to continue or exit?"
If the user presses Continue, progressDialog should continue the remaining work.
Otherwise, close the current activity.
CODE HERE:
public class SampleExample extends Activity {
static final int PROGRESS_DIALOG = 0;
Button button;
TextView download;
ProgressThread progressThread;
ProgressDialog progressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
download = (TextView) findViewById(R.id.download);
button = (Button) findViewById(R.id.progressDialog);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(PROGRESS_DIALOG);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Ask the user if they want to quit
new AlertDialog.Builder(this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to leave?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
SampleExample.this.finish();
}
}).show();
// Say that we've consumed the event
return true;
}
return super.onKeyDown(keyCode, event);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(SampleExample.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
download.setText("Now downloading.......");
progressThread = new ProgressThread(handler);
progressThread.start();
progressDialog.setCancelable(true);
return progressDialog;
default:
return null;
}
}
// Define the Handler that receives messages from the thread and update the
// progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int total = msg.getData().getInt("total");
progressDialog.setProgress(total);
if (total >= 100) {
download.setText(" download is completed.");
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
}
};
/** Nested class that performs progress calculations (counting) */
private class ProgressThread extends Thread {
Handler mHandler;
final static int STATE_DONE = 0;
final static int STATE_RUNNING = 1;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
public void run() {
mState = STATE_RUNNING;
total = 0;
while (mState == STATE_RUNNING) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e("ERROR", "Thread Interrupted");
}
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total++;
}
Log.d("SampleExample", "6666 run () 6666 End");
}
/*
* sets the current state for the thread, used to stop the thread
*/
public void setState(int state) {
mState = state;
}
}
}
You need to override back button event. You can do this as:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && progressDialog.isShowing()) {
Log.d(this.getClass().getName(), "back button pressed");//write your own logic here, Whatever you want to do
}
return super.onKeyDown(keyCode, event);
}
Well, I had the same issue. The simplest method that worked for me is using progressDialog.setCancelable(true).. This declares whether the dialog is cancelable by hitting the back key.. Try it and let me know if it works for you or not. Good luck
Similar issue , When progressDialog.setCancelable(true) is set then hitting back button does not execute code written in back button code but just cancels the progress dialog..Hitting the key again works.
i want to cancel the progress dialog and execute some piece of code together which is not working.
Clicking back button twice does not make sense to me.
You can use progressDialog.setCancelable(true) and then use progressDialog.setOnCancelListener() to provide the OnCancelListener to execute your code to be executed onCancel().
See the Android documentation on Dialogs.

Categories

Resources