Prevent ProgressDialog from being dismissed onClick event - java

This has been asked in previous posts, but I've tried many and none of them seem to work. I have a boolean flag that should in theory prevent my dialog from being closed. Here is what I have so far:
boolean start_match = false;
public void WarmupDialog()
{
if(use_warmup == true)
{
final ProgressDialog spinner = new ProgressDialog(this);
spinner.setTitle("Warmup");
spinner.setCancelable(false);
spinner.setCanceledOnTouchOutside(false);
timer = new CountDownTimer(300000, 1000)//5 minutes
{
#Override
public void onFinish()
{
spinner.cancel();
}
#Override
public void onTick(long l)
{
spinner.setMessage(((int)Math.round(l/1000.0)-1)+"secs remaining of warmup");
}
};
spinner.setButton(DialogInterface.BUTTON_POSITIVE, "Start Warmup", (DialogInterface.OnClickListener)null) ;
spinner.show();
Button button = spinner.getButton(DialogInterface.BUTTON_NEUTRAL);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(start_match)
{
spinner.dismiss();
}
else
{
start_match = true;
Button button = spinner.getButton(DialogInterface.BUTTON_POSITIVE);
button.setText("Start Match");
timer.start();
}
}
});
spinner.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
timer.cancel();
ChooseServer();
}
});
}
else
{
ChooseServer();
}
}
This open a warm up timer for a tennis match. When the button is pressed for the first time the timer should start. When the button is pressed again the dailog should then cancel. At the moment the dialog is dismissed immediately. Any ideas?
Thanks in advance for any help!

As far as my knowledge about Progress dialogs goes, it should be the normal behavior.
As ProgressDialog inherits from AlertDialog -> Dialog and by default they get dismissed when user press a button on the dialog, regardless of which button it is (positive/negative etc).
Suggestion: intercepting the touch event & detecting the source position of the touch event (i.e on which button user has touched), we should be able to override this behavior.

Related

Dialog popping up again several times (not a duplicate of any similar question)

So this thing is troubling me since past few days now. I have a dialog in my PostAdapter class. When someone clicks on 'more' menu, a dialog (which appears as a bottom sheet) appears. There is no issue in showing the dialog. It is working perfectly fine. But the issue is after clicking on 'more', if I perform any other action, the dialog opens several times automatically. I have to tap on the screen that many times to dismiss each opened dialog. I have dismissed the dialog in the code but the behaviour is quite unexpected. The dialog keeps opening everytime I perform some action with the post even after switching between fragments and coming back to Home Fragment where all the posts are displayed.
Its very strange because the dialog should only open on clicking 'more' and not on any other action. I have tried solutions given in some similar questions but none of them have worked.
viewHolder.binding.more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase.getInstance().getReference()
.child("Posts")
.child(post.getPostId())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String postedBy = snapshot.child("postedBy").getValue().toString();
if (FirebaseAuth.getInstance().getCurrentUser().getUid().equals(postedBy)) {
showBottomSheetDialog(post, holder);
} else {
showBottomSheetDialogForOthersPosts(post, holder);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
private void showBottomSheetDialogForOthersPosts(Post post, RecyclerView.ViewHolder holder) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.bottomsheetlayout_othersposts);
LinearLayout share = dialog.findViewById(R.id.share);
LinearLayout report = dialog.findViewById(R.id.report);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(context, "Share is clicked", Toast.LENGTH_SHORT).show();
}
});
report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(context,"Report is Clicked",Toast.LENGTH_SHORT).show();
}
});
dialog.show();
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.BottomSheetDialogAnimation;
dialog.getWindow().setGravity(Gravity.BOTTOM);
}
You must be getting multiple callbacks in
public void onDataChange(#NonNull DataSnapshot snapshot) {}
I will suggest you to declare dialog globally and check whether that dialog is already visible or not, if not then only show the dialog.
final Dialog dialog = new Dialog(context);

Change text in button

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_apple = (Button) findViewById(R.id.button_apple);
Button btn_cherry = (Button) findViewById(R.id.button_cherry);
Button btn_orange = (Button) findViewById(R.id.button_orange);
Button btn_waterLemon = (Button) findViewById(R.id.button_waterlemon);
btn_apple.setOnClickListener(new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_apple:
if (!action) {
action = true;
btn_apple.setText("1");
}
else {
int i = Integer.parseInt(btn_apple.getText().toString());
btn_apple.setText(String.valueOf(i + 1));
}
break;
case R.id.button_cherry:
action = false;
if (!action) {
action = true;
btn_cherry.setText("1");
}
else {
int i = Integer.parseInt(btn_cherry.getText().toString());
btn_cherry.setText(String.valueOf(i + 1));
}
break;
}
}
});
}
}
I need to make it so that if a user clicks on button_apple and doesn't click on it for 3 seconds, its text becomes so superfluous. And if anyone knows why my text changes in button_apple, but not in button_cherry. Tell me, please.
You're setting the listener on your apple button. The cherry button doesn't have a listener on it.
Reconsider what you're trying to achieve and simplify it.
If the user clicks the apple button you need to do something.
If the user clicks the cherry button you need to do something (maybe something else).
If the user clicks the watermellon button, ... and so on.
// define your listeners
View.OnClickListener appleListener = new View.OnClickcListener() {
#Override
public void onClick(View v) {
// do whatever you need to do when the apple button is clicked
}
};
// same thing for cherry listener, make a listener to handle the click action
View.OnClickListener cherryListener = ...
// register the listeners
btnApple.setOnClickListener(appleListener);
btnCherry.setOnClickListener(cherryListener);
...
EDIT
To make something happen after a set amount of time you have to consider:
the inputs: which objects / variables influence the action
the output: what's supposed to happpen if all inputs are valid
the duration
With android you could use a handler. See the postDelayed method.
long delayMillis = 3000L; // duration after which to run your task
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after the delay in milliseconds
}
}, delayMillis);
All of this stuff has to be inside the click listener with the logic you need to implement.
"If a user clicks on button apple and doesn't click on it for three seconds"
You could do something like
View.OnClickListener appleListener = new View.OnClickcListener() {
AtomicInteger clicks = new AtomicInteger(0);
#Override
public void onClick(View v) {
int numClicks = clicks.incrementAndGet();
if (numClicks == 1) {
long delayMillis = 3000L; // duration after which to run your task
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (clicks.get() == 1) {
// they only clicked once, do whatever you need to do to make the text superfluous
}
// put the number of clicks back to 0
clicks.set(0);
}
}, delayMillis);
}
} else {
// TODO
// it's been clicked more than once
// show a toast if you need to or do something else
}
}
I didn't test this so you'll probably have to modify it a bit but that's the general idea.

how to play different audio on button click android java

I want to play music when a button is clicked, but I want to play different music with different button then the first music stopped and the second music would play.
code:
charge = MediaPlayer.create(this, R.raw.charge);
santai1 = MediaPlayer.create(this, R.raw.santai1);
}
public void charge(View view) {
charge.start();
}
public void santai1(View view) {
santai1.start();
}
Say, I clicked charge button and then played the charge.mp3. Then I want to play santai1.mp3 but when I clicked the santai1 button the charge.mp3 will stop playing and the santai1.mp3 will play.
I want this to be able the opposite and it can be done continuously.
When I clicked santai1 button then santai1.mp3 will be played, while the santai.mp3 still playing I clicked the charge button. I want the santai1.mp3 stopped and then play the chage.mp3.
When I clicked on charge button, then I clicked on santai1 button, both music started together.
if you need it for many
create a mediaplayer object and a method.
private MediaPlayer media;
private void stopMusic() {
if (media != null) {
media.stop();
media.release();
media= null;
}
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopMusic();
media= MediaPlayer.create("you acivityname".this, "mp3file directory");
media.start();
}
});
try this:
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(charge.isPlaying()){
charge.stop();
}
santail.start();
}
});
and do the same for other button
well it's simple you need 2 if statments for the buttons to check if one of them is playing.
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(santail.isPlaying()){
santail.stop();
}
charge.start();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(charge.isPlaying()){
charge.stop();
}
santail.start();
}
});

onClickListener is called only after soft-keyboard press

I write an android app
I set an editText.setOnClickListener(...)
but i see that when the user clicks, the soft-keyboard is opened and only
when the user clicks on a keyboard key - the onClick() is called.
how to catch the click before the soft keyboard is opened?
I want to avoid the keyboard opening.
here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phone_login);
initMembers();
setOnClickListeners();
initFieldsTexts();
setKeyboardVisibilityListener();
}
private void setOnClickListeners() {
mPhoneNumberField.setInputTextOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
}
and:
public class PhoneLoginFillInField extends LinearLayout {
..
public void setInputTextOnClickListener(OnClickListener onClickListener)
{
mInputText.setOnClickListener(onClickListener);
}
during debugging i see this line is called twice
mPhoneNumberField.setInputTextOnClickListener(new OnClickListener() {
though it's called only from onCreate and there setOnClickListeners(); is called once
You mean EditText should not gain focus; it needs to respond only to click events. Do this:
editText.setFocusableInTouchMode(false);
And then carry on:
editText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Your code...
}
}
Set an onTouchListener to the EditView. Remember to return true to avoid the event propagation.

Pass the name of button clicked to different class in Android

I am new to android (and not so hot with it, but trying to learn).
I am creating an application that has a number of various buttons that start countdown timers when they are clicked.
On the activity that has these buttons the following code is used to start the timer:
//Button 1 Start On Click
final CountDown buttonOneTimer = new CountDown(15000,1000);
buttonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
buttonOneTimer.start();
}
});
//Button 2 Start On Click
final CountDown buttonTwoTimer = new CountDown(15000,1000);
buttonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
buttonTwoTimer.start();
}
});
my CountDown class looks like this:
public class CountDown extends CountDownTimer {
public CountDown (long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
System.out.println("Timer Completed.");
****NAMEOFTHEBUTTONCLICKED****.setText("Timer Completed.");
}
#Override
public void onTick(long millisUntilFinished) {
****NAMEOFTHEBUTTONCLICKED****.setText((millisUntilFinished/1000)+"");
System.out.println("Timer : " + (millisUntilFinished/1000));
}
}
I am trying to get the name of the button pressed into the class so I can set the text on the button to countdown.
I'm sure I am doing all sorts of things wrong or there may be better ways to do it - so if you see areas where I could improve - feel free to critique me!
I read over the tutorial here however it has an 'inner class' (I believe that is what it is called?) inside the current class. A friend of mine said that's very rarely done and to just create a separate class such as CountDown. If I do it the same way as in the tutorial I can get the timer to work (by hardcoding the buttons name where it says *NAMEOFTHEBUTTONCLICKED* above, which means it only works for that button) - but I still need to figure out how to pass that class the buttons name so I don't have to write a separate class for each timer.
Would that be done through Extras? I have had a hard time finding any more info to my specific issue. Any help is appreciated!!
Try passing off the button instance to the Timer:
public class CountDown extends CountDownTimer {
Button button;
public CountDown (long millisInFuture, long countDownInterval, Button button) {
super(millisInFuture, countDownInterval);
this.button = button;
}
#Override
public void onFinish() {
System.out.println("Timer Completed.");
button.setText("Timer Completed.");
}
#Override
public void onTick(long millisUntilFinished) {
button.setText((millisUntilFinished/1000)+"");
System.out.println("Timer : " + (millisUntilFinished/1000));
}
}
Then call like this:
//Button 1 Start On Click
final CountDown buttonOneTimer = new CountDown(15000,1000,buttonOne);
buttonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
buttonOneTimer.start();
}
});

Categories

Resources