Reset Horizontal Progress Bar to 0 every night 12oClock? - java

I want to reset my horizontal progressbar to 0 every night at 12.
Here is my code.
public class MainActivity extends AppCompatActivity {
private TextView textView;
Button btn;
private int Counter counter;
Progressbar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.txtvw);
progressbar = findViewById(R.id.progressbar_Horizontal);
progressbar.setMax(10);
btn = findViewById(R.id.btn_clc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter++;
textView.setText(String.valueOf(counter));
progressbar.setProgress(counter)
}
});
Calendar calendar = Calendar.getInstance();
int hour = 23;
int minute = 59;
int second = 59;
int curHour = calendar.get(Calendar.HOUR_OF_DAY);
int curMinute = calendar.get(Calendar.MINUTE);
int curSecond = calendar.get(Calendar.SECOND);
if (hour==curHour && minute==curMinute && second==curSecond) {
progressbar.setProgress(0);
}
}
}
In this method at the output there is no response to the progressbar! Is this the right way to do or is there any other way?

You don't get any response because you're defining the action in OnCreate method. This method is executed one time when you enter the Activity. So this action defined only works if you launch your Ativity exactly at 23:59:59.
If you want to do it right, implement AlarmManager. You can set the time you want (23:59:59) and do whatever you want (reset the bar) at that moment. You can implement it also when the app is closed, in the background or when the screen is off.
Take a look at this: Alarm Manager Example

Related

Plus/Minus button with a counter but counter does not work properly

I have 2 buttons and a TextView to update the counter based on how many times the plus or minus button was pressed.
But, the issue is that: (for example) When I press the "+" button to 4 and goes down to 3 after pressing "-" button. Then, when I try to press "+"(add) button again it jumps up to 5 instead of 4. (i.e. the counter continues adding 1 from when the last time "+" button was pressed.
This is the adapter class where the ImageButtons and TextView listeners are implemented
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
//inflate layout flavor_item.xml
View view = LayoutInflater.from(context).inflate(R.layout.flavor_item, container, false);
//initialize UID views from flavor_item.xml
ImageView imageIv = view.findViewById(R.id.imageIv);
TextView flavorTv = view.findViewById(R.id.flavorTv);
TextView quantityTv = view.findViewById(R.id.quantityTv);
ImageButton minusbutton = (ImageButton) view.findViewById(R.id.minusbutton);
ImageButton plusbutton = (ImageButton) view.findViewById(R.id.plusbutton);
//getting data
DashboardFlavorModel model = modelArrayList.get(position);
String title = model.getTitle();
int image = model.getImage();
String qty = model.getQuantity();
//setting data
imageIv.setImageResource(image);
flavorTv.setText(title);
quantityTv.setText(qty);
//plusbutton listener
plusbutton.setOnClickListener(new View.OnClickListener() {
int count = Integer.parseInt(model.getQuantity());
#Override
public void onClick(View view) {
count++;
model.setQuantity(""+count);
quantityTv.setText(""+count);
}
});
//listener
minusbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(model.getQuantity());
if (i > 0) {
i--;
model.setQuantity(""+i);
quantityTv.setText(""+i);
} else{
Snackbar.make(view,"Cannot have < 0 QTY",Snackbar.LENGTH_SHORT).setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setQuantity("0");
quantityTv.setText(model.getQuantity());
}[![enter image description here][1]][1]
}).show();
}
}
});
(Note***) I tried checking the counter using getter and setter to check whether it worked and it did so I have no idea why when pressing "+" after "-" it wouldn't just +1 from the value after "-" button.
try putting
int count = Integer.parseInt(model.getQuantity());
inside onClick for plusbutton onclicklistener

Calling nonstatic function when TimePicker is done

I'm kind of new to Android, and I'm currently struggling with the TimePicker. So, I've got the TimePicker here:
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public String time;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
time = hourOfDay + ":" + minute;
//update global variable
MockDB.setCheckout(time);
}
}
This is working, but after the user selects a time I want to call a function in the activity the picker is in to change the button colors and text. This is in a function called ReserveProduct that extends AppCompatActivity.
public void animateButtons() {
//picker disappears until next button is clicked
Button picker = (Button) findViewById(R.id.button6);
picker.setVisibility(View.GONE);
Button picker1 = (Button) findViewById(R.id.button7);
picker1.setVisibility(View.GONE);
if (settingReturn == false) {
//first button turns gray
Button bttn1 = (Button) findViewById(R.id.buttonCheckIn);
bttn1.setBackgroundResource(R.drawable.button_inactive);
String time = ((MockDB) this.getApplication()).getCheckout();
bttn1.setText("Check Out: 12:27 PM");
//new button appears
Button bttn2 = (Button) findViewById(R.id.buttonCheckOut);
bttn2.setVisibility(View.VISIBLE);
settingReturn = true;
} else {
//make 2nd button inactive
Button bttn2 = (Button) findViewById(R.id.buttonCheckOut);
bttn2.setBackgroundResource(R.drawable.button_inactive);
String time = ((MockDB) this.getApplication()).getReturn();
bttn2.setText("Return: 1:27 PM");
//show new buttons
Button set = (Button) findViewById(R.id.buttonSet);
set.setVisibility(View.VISIBLE);
Button home = (Button) findViewById(R.id.buttonHome);
home.setVisibility(View.VISIBLE);
}
}
My issue is that this function is not static, so I'm not able to simply call it from the TimePicker class. I can't move the button changing functionality to the TimePicker class because I need to be able to extend AppCompatActivity, but AppCompatActivity and DialogFragment have a conflicting class. I also can't make the animateButtons() class static because then the findViewById() functionality throws an error.
Please help!!
Instantiate the class first, i.e.
(new SomeClass()).someMethod();

Generate Random integers upon Button Click without refreshing activity

Hey everyone :) Ive been scratching my head on this one, and can't seem to find an appropriate answer that works even though I'm sure its a simple issue.
I have a program which generates a random letter text on a group of buttons when another button being pressed.
When I open the application it loads fine and the first time the button is pressed it generates correctly, but after that I can't seem to get it to regenerate random letters.
I can accomplish what I want by adding an Intent, and essentially "refreshing" (not sure of the wording) the main activity but I would like to add a counter for the button clicks, and it resets when the activity does.
{Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
I just cant seem to wrap my mind around how to do it otherwise. It's seems like I need to rerun the java every time the button is clicked. Any suggestions?
Here is some code, I used buttons rather than textview because I a)wanted to set an easy background b)may make them clickable later. Thanks so much in advance!
public class MainActivity extends Activity
{
Button spin;
Button reel1,reel2,reel3,reel4;
private String rnd,rnd2,rnd3,rnd4;
int count1=50;
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();}
private static String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}
private static String rndm2[] = {"A","B","C","D"};
{rnd2 = rndm2[(int) (Math.random() * rndm2.length)];}
private static String rndm3[] = {"A","B","C","D"};
{rnd3 = rndm3[(int) (Math.random() * rndm3.length)];}
private static String rndm4[] = {"A","B","C","D"};
{rnd4 = rndm4[(int) (Math.random() * rndm4.length)];}
public void perform_action(View v){}
public void addListenerOnButton() {
spin = (Button) findViewById(R.id.spin);
spin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
{Toast.makeText(getApplicationContext(),"button pressed", Toast.LENGTH_SHORT).show();}
{Button tv = (Button) findViewById(R.id.reel1);
tv.setText(String.valueOf(rnd));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel2);
tv.setText(String.valueOf(rnd2));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel3);
tv.setText(String.valueOf(rnd3));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel4);
tv.setText(String.valueOf(rnd4));
tv.setTextColor(Color.parseColor("#000000"));
I figured it out!!! Whoot. But I can't upvote myself for a correct answer.
public class MainActivity extends Activity
{
Button spin;
Button reel1,reel2,reel3,reel4;
private String rnd,rnd2,rnd3,rnd4;
int count1=50;
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();}
public void perform_action(View v){}
public void addListenerOnButton() {
spin = (Button) findViewById(R.id.spin);
spin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}
String rndm2[] = {"A","B","C","D"};
{rnd2 = rndm2[(int) (Math.random() * rndm2.length)];}
String rndm3[] = {"A","B","C","D"};
{rnd3 = rndm3[(int) (Math.random() * rndm3.length)];}
String rndm4[] = {"A","B","C","D"};
{rnd4 = rndm4[(int) (Math.random() * rndm4.length)];}
{Toast.makeText(getApplicationContext(),"button pressed", Toast.LENGTH_SHORT).show();}
{Button tv = (Button) findViewById(R.id.reel1);
tv.setText(String.valueOf(rnd));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel2);
tv.setText(String.valueOf(rnd2));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel3);
tv.setText(String.valueOf(rnd3));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel4);
tv.setText(String.valueOf(rnd4));
tv.setTextColor(Color.parseColor("#000000"));
I moved my random Strings into my Onclick event and removed the private and static parts. Then whala! Things work like a charm!

App is crashing before it starts

I'm creating a simple app with two NumberPickers used to select a certain number of minutes and seconds. There isn't too much code so I will post it here:
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "Interval Trainer";
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startButton;
public TextView text;
private final long interval = 1 * 1000;
//Create NumberPickers
NumberPicker numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker1);
NumberPicker numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker2);
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG,"Entering onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button) this.findViewById(R.id.button);
startButton.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
//Set min and max values for NumberPickers
numberPicker1.setMaxValue(100);
numberPicker1.setMinValue(0);
numberPicker2.setMaxValue(59); //This is the seconds picker
numberPicker2.setMinValue(0);
Log.i(TAG,"Exiting onCreate()");
}
#Override
public void onClick(View v) {
//Calculate total time from NumberPickers in seconds
long startTime = (numberPicker1.getValue() * 60) + numberPicker2.getValue();
//Create CountDownTimer with values from NumberPickers
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime / 1000)); //should be removed
if(!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startButton.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startButton.setText("RESTART");
}
//Disable the NumberPickers after 'Start' is pressed
numberPicker1.setEnabled(false);
numberPicker2.setEnabled(false);
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
text.setText("Time's up!");
//re-enable the NumberPickers once countdown is done
numberPicker1.setEnabled(true);
numberPicker2.setEnabled(true);
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1000);
//Changes the value of the NumberPickers after each tick
}
}
}
I have a feeling the crash is related to me declaring the two NumberPickers outside of any methods (this would automatically make them static?). Originally I had these two lines of code in my onCreate() but since I needed them in my inner class and other methods I moved it outside. Is this what is causing the crash? If so, how do I do this correctly and still have access to numberPicker1 and 2 all around my class (including inner class)?
Thank you!
You cant intiate object like this
//Create NumberPickers
NumberPicker numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker1);
NumberPicker numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker2);
after onCreate only you layout loads so you dont have you object yet initialized.
You can initlize you object in onCreate after
setContentView(R.layout.activity_main);
For example
// init variable
NumberPicker numberPicker1 = null;
NumberPicker numberPicker2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
// After here only your Activity gets the layout objects
numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker1);
numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker2);
}
You should put your findViewById inside onCreate method and create local variables:
// init variable
NumberPicker numberPicker1, numberPicker2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker1);
numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker2);
}
Then, you will able to call these variables inside other methods. According to this reference:
Non-static nested classes (InnerClasses) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. [...] InnerClass has direct access to the methods and fields of its enclosing instance.

Text view if statement not working

Can anyone help me work out where I'm going wrong here. On the button click the media player plays one of the mfiles at random and I'm trying to set a textview depending on which file was played. Currently the setText if statements only match the audio playing half the time. Really not sure where I'm going wrong here.
private final int SOUND_CLIPS = 3;
private int mfile[] = new int[SOUND_CLIPS];
private Random rnd = new Random();
MediaPlayer mpButtonOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfile[0] = R.raw.one;
mfile[1] = R.raw.two;
mfile[2] = R.raw.three;
//Button setup
Button bOne = (Button) findViewById(R.id.button1);
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, mfile[rnd.nextInt(SOUND_CLIPS)]);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[0]){
textOne.setText("one");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[1]){
textOne.setText("two");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[2]){
textOne.setText("three");
}
mpButtonOne.setOnCompletionListener(new soundListener1());
{
}
So just to clarify the problem I am having is that the setText only matches the audio occasionally, not on every click. The rest of the time it displays the wrong text for the wrong audio.
You are choosing another random file
mfile[rnd.nextInt(SOUND_CLIPS)]
set that to a variable in onClick() then check against that variable in your if statement
public void onClick(View v) {
int song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
if (song == mfile[0]){
textOne.setText("one");
}
Edit
To make it a member variable so you can use it anywhere in the class, just declare it outside of a method. Usually do this before onCreate() just so all member variables are in the same place and it makes your code more readable/manageable.
public class SomeClass extends Activity
{
int song;
public void onCreate()
{
// your code
}
then you can just initialize it in your onClick()
public void onClick(View v) {
song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);

Categories

Resources