how to delay put on button click android - android

public class MainActivity extends Activity implements NetworkMonitorListener {
double _mylat = 0;
double _mylong = 0;
TextView textView1;
Button clcikbutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
clcikbutton = (Button) findViewById(R.id.button1);
clcikbutton.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
});
}
}, 5000));
clcikbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"MM/dd/yyyy hh:mm:ss aa");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
textView1.setText(DateFormat.getDateTimeInstance().format(
new java.util.Date("11/7/2014 5:19:11 AM UTC")));
}
});
}
}
this is my code for delay on button click.I am trying to implement that when i click on the button and after that it should disable for 5 seconds and then it should work.Please help me where i am doing wrong because there is Error coming .

Try to use Handler to disable button for given time :
clcikbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
textView1.setText(DateFormat.getDateTimeInstance().format(new java.util.Date("11/7/2014 5:19:11 AM UTC")));
clcikbutton.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
},5000);
}
});

why not this:
clcikbutton = (Button) findViewById(R.id.button1);
clcikbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
clcikbutton.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
}, 5000));
}
});

There are two closing bracket after 5000 please check that.
Try like adding Some period 1000.
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
});
}
}, 5000, 1000);

You can use Handler to execute the line of code after some delay :
clickbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
clickbutton.setEnabled(true);
}
}, 5000);
}
});
Hope it will help you ツ

Timer is flaky, consider using Handler's postDelay() method. Try this:
clcikbutton = (Button) findViewById(R.id.button1);
clcikbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Do what you need to do..
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"MM/dd/yyyy hh:mm:ss aa");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
textView1.setText(DateFormat.getDateTimeInstance().format(
new java.util.Date("11/7/2014 5:19:11 AM UTC")));
// Set the button not-clickable..
clcikbutton.setEnabled(false);
// Then re-enable it after 5 seconds..
final Runnable enableButton = new Runnable() {
#Override
public void run() {
clcikbutton.setEnabled(true);
}
};
new Handler().postDelayed(enableButton, 5000);
}
});
Those code should get you what you want: It will make the button clickable at first, then disable it for 5 seconds the time you click it.
Hope this helped. :)

This is how you do it in Kotlin:
lifecycleScope.launch {
buttonTimer.isEnabled = false
delay(400) // debounce effect
buttonTimer.isEnabled = true
}

Related

Disable button after a click for 2 seconds and resume back

When I click a resend button first time, the button will disable for 2 seconds.After 2 seconds the button will enable?
I am using this code
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn.setEnabled(false);
btn.postDelayed(new Runnable() {
public void run() {
btn.setEnabled(true);
Log.d(TAG,"resend1");
}
},1000);
}
});
But this code is not working properly.
try this for this purpose you can use Handler(import android.os.Handler;)
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
btn.setEnabled(true);
Log.d(TAG,"resend1");
}
},2000);// set time as per your requirement
}
});
You can use a timer for this
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myButton.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
myButton.setEnabled(true);
}
});
}
}, 5000);
}
});
Find the solution
In your button click
long mLastClickTime;
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disableButtonTwoSecs();
// Here your implementation
}
});
public static boolean disableButtonTwoSecs() {
if (SystemClock.elapsedRealtime() - mLastClickTime < 2000) {
return true;
}
mLastClickTime = SystemClock.elapsedRealtime();
return false;
}

Persistent Firebase Database

I am making a voting app. There are two buttons and the number of clicks are stored in a Firebase database. However on closing the app(kill app process), the database gets refreshed and the counter starts from zero again. Is it possible for the database to start counting from where it left even after the app is killed.
Source Code for MainActivity.java
public class Main2Activity extends AppCompatActivity {
private Firebase mRootRef;
private Button mBtn1;
private Button mBtn2;
int counter = 0;
int counter1 = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Firebase.setAndroidContext(this);
mBtn1 = (Button) findViewById(R.id.btn1);
mBtn2 = (Button) findViewById(R.id.btn2);
mBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.equals(mBtn1)) {
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 1");
Firebase mRefChild = mRootRef.child("Votes");
counter++;
mRefChild.setValue(counter);
MediaPlayer click1 =MediaPlayer.create(getApplicationContext(), R.raw.click);
click1.start();
mBtn1.setEnabled(false);
mBtn2.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mBtn1.setEnabled(true);
mBtn2.setEnabled(true);
}
});
}
}, 5000);
final AlertDialog.Builder Voted = new AlertDialog.Builder(Main2Activity.this);
Voted.setTitle("Voted");
Voted.setMessage("You have cast Your Vote!");
Voted.setCancelable(false);
final AlertDialog dlg = Voted.create();
dlg.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
dlg.dismiss();
t.cancel();
}
}, 5000);
}
}
});
mBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 2");
if (v.equals(mBtn2)) {
Firebase mRefChild = mRootRef.child("Votes");
counter1++;
mRefChild.setValue(counter1);
MediaPlayer click2 =MediaPlayer.create(getApplicationContext(), R.raw.click);
click2.start();
mBtn2.setEnabled(false);
mBtn1.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mBtn2.setEnabled(true);
mBtn1.setEnabled(true);
}
});
}
}, 5000);
final AlertDialog.Builder Voted = new AlertDialog.Builder(Main2Activity.this);
Voted.setTitle("Voted");
Voted.setMessage("You Have cast your Vote");
Voted.setCancelable(false);
final AlertDialog dlg = Voted.create();
dlg.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
dlg.dismiss();
t.cancel();
}
}, 5000);
}
}
});
}
#Override
public void onBackPressed() { }
}
Thanks
Counter and counter1 are the local variable and you are not persisting them. As you are storing the value of counter and counter1 to the database, you should simply retrieve the value and increment it by 1.
mRefChild.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// you can retrieve your stored value from dataSnapshot
Object data = dataSnapshot.getValue()
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
It sounds like you are using order version of Firebase. Please refer this link https://firebase.google.com/support/guides/firebase-android and upgrade your project.
Above link also provides details about reading the data. In your case addListenerForSingleValueEvent(..) will solve your problem.
https://www.firebase.com/docs/java-api/javadoc/com/firebase/client/DataSnapshot.html
from your code it sounds like you directly storing value for Votes and there is no table structure or anything. So dataSnapshot.getValue() should return your value. however, I advise you to debug the code and and put a breakpoint Object data = dataSnapshot.getValue() and analyze the information in the dataSnapshot instance. Its all there.
once you retrieve the value, assign it to the counter or counter1 variable. so everytime you will start app, you will have updated value of votes back to your variable. you are already doing counter++ on button click so that should work as it is.

Is there anything wrong with this code where i am using Timer

I am trying to take the recent time and show it in a TextView. And using a Timer and timerTask to get current time every second and update the UI using post method of View object.
Below is my code:
public class MainActivity extends Activity implements OnClickListener
{
Button btnStart,btnStop;
TextView txtRcntTime;
Calendar c;
private Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize(); // method where i initialized all components
c = Calendar.getInstance();
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonStart:
start();
break;
case R.id.buttonStop:
stop();
break;
}
}
public void stop()
{
if (timer!=null){
timer.cancel();
timer = null;
}
}
private void start()
{
if(timer != null)
{ timer.cancel(); }
TimerTask task = new TimerTask() {
#Override
public void run() {
SimpleDateFormat df1 = new SimpleDateFormat("hh-mm-ss a");
String formattedDate1 = df1.format(c.getTime());
updateView(formattedDate1);
}
};
timer = new Timer(true);
timer.schedule(task, 0, 1000);
}
public void updateView(final String t)
{
txtRcntTime.post(new Runnable() {
String t2 = t;
#Override
public void run()
{ txtRcntTime.setText(t2); }
});
}
}
Result is showing the time for the first time when button is clicked but not updating.
problem:
c = Calendar.getInstance();
It is actually updating but you are only getting one instance of the calendar thus giving you the same time when the timer task is called every 1 second.
solution:
update the calendar by getting the instance of it each second
TimerTask task = new TimerTask() {
#Override
public void run() {
SimpleDateFormat df1 = new SimpleDateFormat("hh-mm-ss a");
Calendar cal = Calendar.getInstance();
String formattedDate1 = df1.format(cal.getTime());
updateView(formattedDate1);
}
};

cancel countdowntimer on onbackpressed

I'm trying to cancel the countdowntimer on onbackpressed, I put counter.cancel; there but "'count' cannot be resolved" error appears. I think It can't find the countdowntimer!
There is a btn_riazi1_1_1 that can cancel the timer.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_riazi1_1);
//// handling timer
final TextView textic = (TextView) findViewById(R.id.riazi1_1_timer);
final CountDownTimer Count = new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
textic.setText(getResources().getString(R.string.remaintime) + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText(getResources().getString(R.string.timesup));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(Riazi1_1.this,Riazi1_2.class);
startActivity(i);
}
}, 1000);
}
};
Count.start();
/////////////////
//// handling button1
Button btn1 = (Button) findViewById(R.id.btn_riazi1_1_1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Count.cancel();
TextView txtwrong = (TextView) findViewById(R.id.txt_wrong_riazi1_1);
txtwrong.setVisibility(View.VISIBLE);
Button btn2 = (Button) findViewById(R.id.btn_riazi1_1_2);
btn2.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(Riazi1_1.this,Riazi1_2.class);
startActivity(i);
}
}, 1000);
}
});
}
#Override
public void onBackPressed(){
super.onBackPressed();
Count.cancel(); // error: Count cannot be resolved ///
}
}
You have declared the TImer within onCreate method. So you cannot access it outside of onCreate. Declare it as a member variable.
private CountDownTimer Count; /// declare it as a member variable
and in the onCreate method initialize it like
Count = new CountDownTimer(5000, 1000).....
[A suggestion, use the naming convension. naming a variable starting with capital letter is really confusing]

changing image s for 1 second in android imageview

I am trying to change image after 1 second for image view.but its doesn't show any image on screen. following is code.please help.thank you.
code-
public class Shapes extends Activity {
Timer timer = new Timer();
int flag;
String images[]={};
ImageView iv;
static int v[]={R.drawable.round,R.drawable.rectangle};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.shapes);
iv=(ImageView) findViewById(R.id.imageView1);
timer.schedule(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (flag > 1) {
timer.cancel();
timer = null;
} else
iv.setImageResource(v[flag++]);
}
});
}
}, System.currentTimeMillis(), 1000);
}
}
how can i check resource image and change it
Use Handler instead of Timer
Handler handler = new Handler();
Runnable changeImage = new Runnable(){
#Override
public void run(){
if(flag>1)
handler.removeCallbacks(changeImage);
else{
iv.setImageResource(v[flag++]);
handler.postDelayed(changeImage, 1000);
}
}
};
start the first time from oncreate()
public void onCreate(Bundle b){
handler.postDelayed(changeImage, 1000);
}
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
flag++;
if (flag > 1) {
timer.cancel();
timer = null;
}
else
iv.setImageResource(v[flag]);
}
});
}
}, 1000, 1000); // wait 1 second before start.. then repeat every second..
It's because you put System.currentTimeMillis() as delay.
Try replacing that with 0, because the time should start after 0 ms.

Categories

Resources