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.
Related
I am using SweetAlert Dialog for android.
https://github.com/pedant/sweet-alert-dialog
In the success dialog, I want to remove to the OK Button since I am using timer option, however no option for doing so has been mentioned in their docs. Please explain how can I remove the OK button.
MainActivity.java
public class Main2Activity extends AppCompatActivity {
private Firebase mRootRef;
private Button mBtn1;
private Button mBtn2;
int counter;
int counter1;
long value;
#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");
final Firebase mRefChild = mRootRef.child("Votes");
mRefChild.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(final MutableData currentData) {
if (currentData.getValue() == null) {
currentData.setValue(1);
} else {
currentData.setValue((Long) currentData.getValue() + 1);
}
return Transaction.success(currentData);
}
public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
}
});
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 SweetAlertDialog Voted = new SweetAlertDialog(Main2Activity.this, SweetAlertDialog.SUCCESS_TYPE);
Voted.setTitleText("Voted");
Voted.setContentText("You Have cast your Vote!");
Voted.show();
Voted.findViewById(R.id.confirm_button).setVisibility(View.GONE);
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Voted.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");
mRefChild.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(final MutableData currentData) {
if (currentData.getValue() == null) {
currentData.setValue(1);
} else {
currentData.setValue((Long) currentData.getValue() + 1);
}
return Transaction.success(currentData);
}
public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
}
});
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 SweetAlertDialog Voted = new SweetAlertDialog(Main2Activity.this, SweetAlertDialog.SUCCESS_TYPE);
Voted.setTitleText("Voted");
Voted.setContentText("You Have cast your Vote!");
Voted.show();
Voted.findViewById(R.id.confirm_button).setVisibility(View.GONE);
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Voted.dismiss();
t.cancel();
}
}, 5000);
}
}
});
}
#Override
public void onBackPressed() { }
}
I am assuming your code is look like
new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Good job!")
.setContentText("You clicked the button!")
.show();
So the answer is
SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Good job!")
.setContentText("You clicked the button!")
.show();
dialog.findViewById(R.id.confirm_button).setVisibility(View.GONE);
This also works
SweetAlertDialog sweetdialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Good job!")
.setContentText("You clicked the button!")
.show();
sweetdialog.getButton(SweetAlertDialog.BUTTON_CONFIRM).setVisibility(View.GONE);
new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Good job!")
.setContentText("You clicked the button!")
.show();
// dont forget to add this in build.gradle
implementation 'com.github.f0ris.sweetalert:library:1.6.2'
I am creating a voting app. A Firebase database counts the number of clicks of a button and displays it. However on closing the app and restarting, the number of clicks start back from zero. How can I keep adding the number the votes to the child node even after the app is closed and restarted instead of starting the votes from zero?
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() { }
}
From the Firebase documentation :
Use our transactions feature when working with complex data that could be corrupted by concurrent updates
public void incrementCounter() {
firebase.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(final MutableData currentData) {
if (currentData.getValue() == null) {
currentData.setValue(1);
} else {
currentData.setValue((Long) currentData.getValue() + 1);
}
return Transaction.success(currentData);
}
#Override
public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
if (firebaseError != null) {
Log.d("Firebase counter increment failed.");
} else {
Log.d("Firebase counter increment succeeded.");
}
}
});
}
can any 1 give me example to perform onClick on button for multiple times when user clicked for 1 time. when i click on button 1 time it should automatically click after delay of 5 seconds for 100 times. how to perform that.
This is my sample code
mUnlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//It should be already ensured that this mSelectedLock is something user is authorized to access
if (mSelectedLock.unlock("RANDOM")) {
mUnlock.setVisibility(View.INVISIBLE);
mUnlock.postDelayed(new Runnable() {
public void run() {
mUnlock.setVisibility(View.VISIBLE);
}
}, 5000);
} else {
Toast.makeText(MainActivity.this, "Unable to unlock.", Toast.LENGTH_LONG).show();
}
}
});
#Override
public void onClick(View v) {actionToBeDone();startLoop(0);}
private void startLoop(final int i) {
if(i!=100) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Log.e("i",""+i);
actionToBeDone();
startLoop(i+1);
}
}, 2000);
}
}
private void actionToBeDone() {
//enter actions you want to be done
Log.e("actionToBeDone","Button Action");
}
int count = 0;
Timer timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run(){
if(count < 100){
mUnlock.performClick();
}
}
}, 0, 5000);
5000 is the time in miliseconds you can +/- from here.
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
}
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]