Animation in Oncreate() not stopping in android - android

Want to Do : i want to have an Internet check on Start of An app and if it doesn't finds then on clicking Positive button it should go to setting of wifi & if User ON the wifi then on coming back to App i want the dialog box to be dismiss and Animation start else it again show how the Internet Dialog Box .
What i have done : I have placed the Internet Check Dialog in OnResume() and animation code in OnCreate .
Issue is : on start of my App, when it check Wifi connection ,But it also run all the animation code in Oncreate() in continuity instead of running it only after Internet Connection
OnCreate Code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.grow_from_middle, R.anim.shrink_to_middle);
setContentView(R.layout.activity_csplogin);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
mobileEdit = (EditText) findViewById(R.id.mobileText);
nameEdit = (EditText) findViewById(R.id.nameText);
employerEdit = (EditText) findViewById(R.id.employerText);
noEmployerCheckbox = (CheckBox) findViewById(R.id.noEmployercheckboxid);
employerSpinner = (Spinner) findViewById(R.id.employer_spinner_id);
noEmployerLayout = (LinearLayout) findViewById(R.id.linearlayoutCheckbox);
init();
if (myPrefs.getOrgValidated() == false) {
new OrganisationValidationTask(CSPLoginActivity.this).execute();
}
isdeviceValidated = myPrefs.getIsDeviceValidated();
isLoggedIn = myPrefs.getIsLogIn();
if (isdeviceValidated) {
startLoginActivity();
}
final RelativeLayout LoginBox = (RelativeLayout) findViewById(R.id.LoginBox);
LoginBox.setVisibility(View.GONE);
Animation animTranslate = AnimationUtils.loadAnimation(CSPLoginActivity.this, R.anim.translate);
animTranslate.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
LoginBox.setVisibility(View.VISIBLE);
Animation animFade = AnimationUtils.loadAnimation(CSPLoginActivity.this, R.anim.fade);
LoginBox.startAnimation(animFade);
showSingleChoice();
}
});
ImageView imgLogo = (ImageView) findViewById(R.id.imageView1);
imgLogo.startAnimation(animTranslate);
isdeviceValidated = myPrefs.getIsDeviceValidated();
isLoggedIn = myPrefs.getIsLogIn();
if (!isLoggedIn) {
// display login screen
if (Utils.isNetworkConnected(this)) {
if (isdeviceValidated) {
// to display user details
// displayUserDetails();
if (!isMyServiceRunning()) {
Utils.startLocationPollerAndWakeupService(this);
}
}
}
} else if (isLoggedIn && isdeviceValidated) {
// skip login screen
if (!isMyServiceRunning()) {
Utils.startLocationPollerAndWakeupService(this);
}
startLoginActivity();
}
}
OnResume
#Override
protected void onResume() {
super.onResume();
if(Utils.isNetworkConnected(this)) {
}else{
showWifiAlert();
}
}
Checking Internet Connection Dialog Box:
private void showWifiAlert(){
new MaterialDialog.Builder(CSPLoginActivity.this)
.content("Unable to validate device as Internet not available")
.title("Alert !")
.positiveText("OK")
.negativeText("Cancel")
.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onNegative(MaterialDialog dialog) {
finish();
}
#Override
public void onPositive(MaterialDialog dialog) {
dialog.dismiss();
startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
}
})
.cancelable(false)
.show();
}
Please Help , How to achieve what i want to do .

try replacing the onResume method code as following:
#Override
protected void onResume() {
super.onResume();
if(Utils.isNetworkConnected(this)) {
imgLogo.startAnimation(animTranslate);
}else{
showWifiAlert();
}
}
Let me know if this works for you.

Related

Showing results for a quiz app (Android Studio)

I have a quiz app that is working properly, but the thing is the user must answer all questions correctly in order to win the game(if the player gets it wrong the game will be over) .
What I wanted to do is have the questions answered and then at the end there will be an activity that will show how many the player has answered then there will be the options to retry and go back to menu
This is the code for the maingameactivity
public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
//Initializing variables
questionText = (TextView) findViewById(R.id.triviaQuestion);
buttonA = (FButton) findViewById(R.id.buttonA);
buttonB = (FButton) findViewById(R.id.buttonB);
buttonC = (FButton) findViewById(R.id.buttonC);
buttonD = (FButton) findViewById(R.id.buttonD);
triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
timeText = (TextView) findViewById(R.id.timeText);
resultText = (TextView) findViewById(R.id.resultText);
coinText = (TextView) findViewById(R.id.coinText);
//Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
triviaQuizText.setTypeface(sb);
questionText.setTypeface(tb);
buttonA.setTypeface(tb);
buttonB.setTypeface(tb);
buttonC.setTypeface(tb);
buttonD.setTypeface(tb);
timeText.setTypeface(tb);
resultText.setTypeface(sb);
coinText.setTypeface(tb);
//Our database helper class
triviaQuizHelper = new TriviaQuizHelper(this);
//Make db writable
triviaQuizHelper.getWritableDatabase();
//It will check if the ques,options are already added in table or not
//If they are not added then the getAllOfTheQuestions() will return a list of size zero
if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
//If not added then add the ques,options in table
triviaQuizHelper.allQuestion();
}
//This will return us a list of data type TriviaQuestion
list = triviaQuizHelper.getAllOfTheQuestions();
//Now we gonna shuffle the elements of the list so that we will get questions randomly
Collections.shuffle(list);
//currentQuestion will hold the que, 4 option and ans for particular id
currentQuestion = list.get(qid);
//countDownTimer
countDownTimer = new CountDownTimer(22000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to timeText
timeText.setText(String.valueOf(timeValue) + "\"");
//With each iteration decrement the time by 1 sec
timeValue -= 1;
//This means the user is out of time so onFinished will called after this iteration
if (timeValue == -1) {
//Since user is out of time setText as time up
resultText.setText(getString(R.string.timeup));
//Since user is out of time he won't be able to click any buttons
//therefore we will disable all four options buttons using this method
disableButton();
}
}
//Now user is out of time
public void onFinish() {
//We will navigate him to the time up activity using below method
timeUp();
}
}.start();
//This method will set the que and four options
updateQueAndOptions();
}
public void updateQueAndOptions() {
//This method will setText for que and options
questionText.setText(currentQuestion.getQuestion());
buttonA.setText(currentQuestion.getOptA());
buttonB.setText(currentQuestion.getOptB());
buttonC.setText(currentQuestion.getOptC());
buttonD.setText(currentQuestion.getOptD());
timeValue = 20;
//Now since the user has ans correct just reset timer back for another que- by cancel and start
countDownTimer.cancel();
countDownTimer.start();
//set the value of coin text
coinText.setText(String.valueOf(coinValue));
//Now since user has ans correct increment the coinvalue
coinValue++;
}
//Onclick listener for first button
public void buttonA(View view) {
//compare the option with the ans if yes then make button color green
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
//Check if user has not exceeds the que limit
if (qid < list.size() - 1) {
//Now disable all the option button since user ans is correct so
//user won't be able to press another option button after pressing one button
disableButton();
//Show the dialog that ans is correct
correctDialog();
}
//If user has exceeds the que limit just navigate him to GameWon activity
else {
gameWon();
}
}
//User ans is wrong then just navigate him to the PlayAgain activity
else {
gameLostPlayAgain();
}
}
//Onclick listener for sec button
public void buttonB(View view) {
if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) {
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for third button
public void buttonC(View view) {
if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) {
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for fourth button
public void buttonD(View view) {
if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) {
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//This method will navigate from current activity to GameWon
public void gameWon() {
Intent intent = new Intent(this, GameWon.class);
startActivity(intent);
finish();
}
//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
Intent intent = new Intent(this, PlayAgain.class);
startActivity(intent);
finish();
}
//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
Intent intent = new Intent(this, Time_Up.class);
startActivity(intent);
finish();
}
//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
#Override
protected void onRestart() {
super.onRestart();
countDownTimer.start();
}
//When activity is destroyed then this will cancel the timer
#Override
protected void onStop() {
super.onStop();
countDownTimer.cancel();
}
//This will pause the time
#Override
protected void onPause() {
super.onPause();
countDownTimer.cancel();
}
//On BackPressed
#Override
public void onBackPressed() {
Intent intent = new Intent(this, HomeScreen.class);
startActivity(intent);
finish();
}
//This dialog is show to the user after he ans correct
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
//Since the dialog is show to user just pause the timer in background
onPause();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);
//Setting type faces
correctText.setTypeface(sb);
buttonNext.setTypeface(sb);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//it will increment the question number
qid++;
//get the que and 4 option and store in the currentQuestion
currentQuestion = list.get(qid);
//Now this method will set the new que and 4 options
updateQueAndOptions();
//reset the color of buttons back to white
resetColor();
//Enable button - remember we had disable them when user ans was correct in there particular button methods
enableButton();
}
});
}
//This method will make button color white again since our one button color was turned green
public void resetColor() {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}
//This method will disable all the option button
public void disableButton() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
}
//This method will all enable the option buttons
public void enableButton() {
buttonA.setEnabled(true);
buttonB.setEnabled(true);
buttonC.setEnabled(true);
buttonD.setEnabled(true);
}
}
Edited
Just remove the wrapper if else inside all the buttons better to keep it as, don't repeat the code. I am assuming the screen that shows result is handled inside gameWon and you have implemented functionality for inCorrectDialog
public void buttonA(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonB(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonC(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonD(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonPressed(Button button) {
button.setButtonColor(ContextCompat.getColor(getApplicationContext(), R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
correctDialog();
} else {
inCorrectDialog();
}
} else {
gameWon();
}
}

Count Down Timer app has issue when I change orientation

The layout of my app contains a TextView and a toggle Button. When the toggle Button is turned ON an AlertDialog appears and the user is prompted to give the time for the countdown to start. It works fine if I dont change the orientation while it counts down. However when I change orientation while the countdown keeps running the Dialog Box reappears which shouldn't. I know that changing orientation destroys and recreates my activity so given the fact that toggle button was ON before the activty is destroyed when it is recreated it continuous to be ON as it should be. So my question is if there is a way for the AlertDialog not to appear after the orientation change.
I have tried adding the following but it didnt work
Declared as class variable
public static final String TOGGLE_BUTTON_STATE = "OFF";
Trying to set the toggle Button to true
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: created.............");
mTextTime = (TextView) findViewById(R.id.textView);
mToggleButton = (ToggleButton) findViewById(R.id.toggleButton);
if((savedInstanceState != null) && TOGGLE_BUTTON_STATE.equals("ON")) {
Log.d(TAG, "onCreate: created after changing orientation........");
mToggleButton.setChecked(true);
}
mToggleButton.setOnCheckedChangeListener(this);
saving the state before it is destroyed
#Override
public void onSaveInstanceState(Bundle outState) {
if(mToggleButton.isChecked()) {
Log.d(TAG, "onSaveInstanceState: toggleButton is checked...........****");
outState.putString(TOGGLE_BUTTON_STATE, "ON");
}else {
Log.d(TAG, "onSaveInstanceState: toggleButton is not checked...........*****");
outState.putString(TOGGLE_BUTTON_STATE, "OFF");
}
super.onSaveInstanceState(outState);
}
//Listener for the ToggleButton
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// Toast.makeText(this, "ON", Toast.LENGTH_SHORT).show();
// TOGGLE_BUTTON_ON = true;
//getting the xml user_input to java
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.user_input, null);
//search inside the view for the text_input
mTextUserInput = (EditText) view.findViewById(R.id.text_input);
//We create the builder and we use it to add functionality to the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Enter The Time");
//We create the user_input that has only the editext widget that we gonna use to get the
//time from the user
builder.setView(view);
builder.setPositiveButton("OK", this);
builder.setNegativeButton("Cancel", this);
builder.show();
} else {
// OFF selected and timer must stop
// TOGGLE_BUTTON_ON = false;
timer.stop();
}
}
ps The countdown timer keeps running properly even after orientation change
Your way of loading the previously stored state in onCreate is false. You are saving the state correctly (but i would prefer storing it as a boolean) - but you are not reading it correctly from the savedInstance.
The way i would do it:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("TOGGLE_BUTTON_STATE", mToggleButton.isChecked());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if(savedInstanceState != null) {
mToggleButton.setChecked(savedInstanceState.getBoolean("TOGGLE_BUTTON_STATE"));
}
mToggleButton.setOnCheckedChangeListener(this);
...
}
You can dismiss the alert dialog when the activity is going to be destroyed.
For example:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
...
// Save the dialog in an instance variable
mDialog = builder.show();
}
#Override
public void onStop() {
if (mDialog != null) {
mDialog.dismiss();
}
super.onStop();
}

Android Calculator Backspace button

Any idea how to illustrate backspace funtion in this code? I try to make some changes but it can't work the backspace function. So, i would like to help me, with the backspace button.
enter code here
public class MainActivity extends AppCompatActivity implements OnClickListener {
private TextView mCalculatorDisplay;
private Boolean userIsInTheMiddleOfTypingANumber = false;
private CalculatorBrain mCalculatorBrain;
private static final String DIGITS = "0123456789.";
DecimalFormat df = new DecimalFormat("############");
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide the status bar and other OS-level chrome
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCalculatorBrain = new CalculatorBrain();
mCalculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonBackspace).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
// The following buttons only exist in layout-land (Landscape mode) and require extra attention.
// The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
if (findViewById(R.id.buttonSquareRoot) != null) {
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
}
if (findViewById(R.id.buttonSquared) != null) {
findViewById(R.id.buttonSquared).setOnClickListener(this);
}
if (findViewById(R.id.buttonInvert) != null) {
findViewById(R.id.buttonInvert).setOnClickListener(this);
}
if (findViewById(R.id.buttonSine) != null) {
findViewById(R.id.buttonSine).setOnClickListener(this);
}
if (findViewById(R.id.buttonCosine) != null) {
findViewById(R.id.buttonCosine).setOnClickListener(this);
}
if (findViewById(R.id.buttonTangent) != null) {
findViewById(R.id.buttonTangent).setOnClickListener(this);
}
}
#Override
public void onClick (View v) {
String buttonPressed = ((Button) v).getText().toString();
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
mCalculatorDisplay.append(buttonPressed);
}
} else {
if (buttonPressed.equals(".")) {
// ERROR PREVENTION
// This will avoid error if only the decimal is hit before an operator, by placing a leading zero
// before the decimal
mCalculatorDisplay.setText(0 + buttonPressed);
} else {
mCalculatorDisplay.setText(buttonPressed);
}
}
userIsInTheMiddleOfTypingANumber = true;
}else{
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation(buttonPressed);
if (new Double(mCalculatorBrain.getResult()).equals(0.0)) {
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", mCalculatorBrain.getResult());
outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
if (new Double(mCalculatorBrain.getResult()).equals(0.0)){
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
In your layout you can add a onClick attribute to each button, say onClick="function", and in your activity you just need to implement a method like this:
public void function(View v) {
switch(v.getId()) {
case R.id.buttonBackspace:
// handle the backspace button
break;
case R.id.xxx:
// handle the button
break;
...
}
}
And for digits, I suggest assign a tag to each digit button in the layout, and do your logic in java based on the tag, instead of the text on the button. Because the text is just a UI, it might change in the future due to other possible requirements.

remove all listeners while performing some actions

I have a button (named button1) with an OnClickListener and after button is clicked, a task should be execute, and button should become unclickable until task is finished. This is my code:
#Override
public void onClick(View v) {
removeListeners();
executeMyTask();
addListeners();
}
private void disableListeners() {
button1.setOnTouchListener(null);
button2.setOnClickListener(null);
}
private void enableListeners() {
button1.setOnTouchListener(this);
button2.setOnClickListener(this);
}
Now it happen that, if I click button while executeMyTask is running (so when listener is disabled), when task finish, onClick is called again.
I would that all clicks performed while executeMyTask is running will be ignored.
how can I do ?
Why don't you just disable the whole button with:
button1.setEnabled(false);
button2.setEnabled(false);
And later just re-enable them:
button1.setEnabled(true);
button2.setEnabled(true);
It will be easier for the users to understand that the button is un-clickable at the moment.
There are 2 ways:
1) With disable all other buttons,
#Override
public void onClick(View v) {
setButtonEnabled(false);
executeMyTask();
setButtonEnabled(true);
}
private void setButtonEnabled(boolean enable) {
// TODO Auto-generated method stub
btn_1.setEnabled(enable);
btn_2.setEnabled(enable);
btn_3.setEnabled(enable);
}
2) Use a boolean to keep record of async task running or not:
Like:
#Override
public void onClick(View v) {
removeListeners();
executeMyTask();
addListeners();
}
// And in executeMyTask
onPreExecute(){
....
..
isAsyncRunning = true;
..
....
}
onPostExecute(){
....
..
isAsyncRunning = false;
..
....
}
//And in Button Click Listeners
{
if(!isAsyncRunning){
// Do something...
}
}

Android Dialog dismisses instead of cancel

I'm having the following issue developing in android 2.2 (API 8):
I have a customized Dialog class like this:
public AuthDialog(final Context context, OnDismissListener dismissListener, OnCancelListener cancelListener) {
super(context);
setOnDismissListener(dismissListener);
setOnCancelListener(cancelListener);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userpassdialog);
setTitle("Enter email and password");
setCancelable(true);
setCanceledOnTouchOutside(true);
authEmail = (EditText) findViewById(R.id.authEmail);
authPass = (EditText) findViewById(R.id.authPass);
alertMessage = (TextView) findViewById(R.id.auth_alert);
Button authButton = (Button) findViewById(R.id.authButton);
View.OnClickListener onClickListener = new View.OnClickListener() {
public void onClick(View v) {
if (checkCredentials())
dismiss();
else
showAlert();
}
};
authButton.setOnClickListener(onClickListener);
}
private void showAlert() {
alertMessage.setText("Wrong user/pass");
authEmail.setText(null);
authPass.setText(null);
}
private boolean checkCredentials() {
// Empty user/pass for now
boolean checkEmail = authEmail.getText().toString().equals("");
boolean checkPassword = authPass.getText().toString().equals("");
return checkEmail && checkPassword;
}
#Override
public void onBackPressed() {
cancel();
}
And I create a new AuthDialog like this:
private void authenticateThenAccept() {
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
accept();
}
};
OnCancelListener cancelListener = new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
cancel();
}
};
AuthDialog dialog = new AuthDialog(context, dismissListener, cancelListener);
dialog.show();
}
I'm using the debugger, and I see that when I cancel (using the back button or pressing outside the dialog) the app dismisses the dialog instead of cancelling.
Anybody has had this kind of issue with Dialogs?
Thanks in advanced.
onDismiss() is always fired when dialog closes. The documentation for setOnCancelListener() states: "This will only be invoked when the dialog is canceled, if the creator needs to know when it is dismissed in general, use setOnDismissListener", i.e. it's not either onCancel or onDismiss but both when a dialog is canceled. I agree though that it would have made more sense had that not been the case.
Assuming this dialog should be modal, make your dialog a new activity.
setCancelable(false) will prevent the back button from doing anything. Many developers just turn off the ability of the back button to close the dialog since it's unclear whether that is a cancel or ok action to the user.

Categories

Resources