Calling a function every 1.5 seconds after a button is pressed - java

The function I have created now gives me a random number between 0.8 and 1.2 every time I click on a button within my android application and displays the result in a TextView. However, I would like for this function to keep giving me a new number every 1.5 seconds without having to click on the button continuously for a new result. How would I go about doing this?
Below displays the function I would like to call every 1.5 seconds.
public void generate(View view) {
double min = 0.8;
double max = 1.2;
Random rand = new Random();
double number = rand.nextDouble()* max;
TextView myText = (TextView)findViewById(R.id.textView_RanNum);
String myString = String.valueOf(number);
myText.setText(myString);
}
All help will be greatly appreciated.

You can use Handler / Runnable:
public class MainActivity extends AppCompatActivity {
Handler handler;
Button buttonStart, buttonStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
buttonStart = findViewById(R.id.button);
buttonStop = findViewById(R.id.button2);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runnable.run();
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(runnable);
}
});
}
public Runnable runnable = new Runnable() {
public void run() {
generate();
handler.postDelayed(runnable, 1500); // 1500 miliseconds
}};
public void generate() {
double min = 0.8;
double max = 1.2;
double number;
Random rand = new Random();
TextView myText = findViewById(R.id.textView_RanNum);
number = rand.nextDouble() * max;
String myString = String.valueOf(number);
myText.setText(myString);
}
}

You can use Android's Handler class to do this.
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Handler myHand = new Handler();
myHand.postDelayed(new Runnable() {
#Override
public void run() {
generate();
}
}, 1500);
}
});
}
public void generate() {
double min = 0.8;
double max = 1.2;
Random rand = new Random();
double number = rand.nextDouble() * max;
TextView myText = (TextView) findViewById(R.id.textView_RanNum);
String myString = String.valueOf(number);
myText.setText(myString);
}
}
Read More about Handler here : https://developer.android.com/reference/android/os/Handler

Related

Multiple random number results

Currently working in Android Studio and running into a little trouble. Trying to get my rollScore button to roll over and over. At this point it "rolls" once and stops. I've tried a for loop and while loop and unable to get it to allow multiple "rolls".
public class GameScreen extends AppCompatActivity {
private Button rollButton; // Roll button being declared as a variable
private TextView rollScore; // Text view being declared as a variable
private TextView totalSCore; //
private int mCounter = 0;
private int totalRuns = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Random randomGenerator = new Random();
final int randomInt = randomGenerator.nextInt(7) + 1;
rollButton = (Button) findViewById(R.id.rollButton);
rollScore = (TextView) findViewById(R.id.rollScore);
totalSCore = (TextView) findViewById(R.id.totalScore);
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollScore.setText(Integer.toString(randomInt));
mCounter++;
}
});
}
}
You have to generate a new random number on each click on your button.
Like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Random randomGenerator = new Random();
int randomInt;
rollButton = (Button) findViewById(R.id.rollButton);
rollScore = (TextView) findViewById(R.id.rollScore);
totalSCore = (TextView) findViewById(R.id.totalScore);
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
randomInt = randomGenerator.nextInt(7) + 1;
rollScore.setText(Integer.toString(randomInt));
mCounter++;
}
});
}
You need to generate a new random number after every roll e.g.
rollScore.setText(Integer.toString(randomGenerator.nextInt(7) + 1));

Need to sum up the total amount and create order summary in another intent/activity

XML LAYOUT SCREENSHOT
Trying to calculate the final amount of selected items in an another activity. Need to create order summary in another activity.
Tried introducing multiplication function but also need to hard code the quantity values to auto calculate the final amount.
public class MainActivity extends AppCompatActivity {
EditText pantqty;
EditText pantrate;
TextView result;
Button SUBMIT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pantqty = (EditText) findViewById(R.id.et_pantqty);
pantrate = (EditText) findViewById(R.id.et_pantrate);
SUBMIT = (Button) findViewById(R.id.et_submit);
result = (TextView) findViewById(R.id.et_result);
SUBMIT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int q = Integer.valueOf(pantqty.getText().toString());
float r = Integer.valueOf(pantrate.getText().toString());
float amount = q * r;
result.setText(Float.toString(amount));
}
});
}
}
Need to create a method in OnCLickListener to calculate the amount from the items selected.can if else case be used on OnclickListerButton?
Thanks for the help.
You can do something like this:
public class MainActivity extends AppCompatActivity {
EditText pantqty;
EditText pantrate;
EditText shirtQty;
EditText shirtRate;
TextView result;
Button SUBMIT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pantqty = (EditText) findViewById(R.id.et_pantqty);
pantrate = (EditText) findViewById(R.id.et_pantrate);
shirtQty = (EditText) findViewById(R.id.shirtqtyId);
shirtRate = (EditText) findViewById(R.id.shirtRateId);
SUBMIT = (Button) findViewById(R.id.et_submit);
result = (TextView) findViewById(R.id.et_result);
SUBMIT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculateSum();
}
});
}
private void calculateSum(){
int q=0;
String pantQty=pantqty.getText().toString().trim();
if(!pantQty.isEmpty() && pantQty!="") {
q=Integer.valueOf(pantQty);
}
float r = Integer.valueOf(pantrate.getText().toString());
int a = Integer.valueOf(shirtQty.getText().toString());
float b = Integer.valueOf(shirtRate.getText().toString());
float amount = (q * r)+(a*b);
result.setText(Float.toString(amount));
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra("total",amount);
startActivity(intent);
}
}
On the secondActivity you get get the total as:
float total=getIntent().getFloatExtra("total",0.0);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pantqty = (EditText) findViewById(R.id.lo_pantqty);
shirtqty = (EditText) findViewById(R.id.lo_shirtqty);
shareesqty = (EditText) findViewById(R.id.lo_shareesqty);
suitqty = (EditText) findViewById(R.id.lo_suitqty);
result = (TextView) findViewById(R.id.et_result);
SUBMIT = (Button) findViewById(R.id.io_enter);
SUBMIT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculationSum();
}
});
}
private void calculationSum() {
int q = 0;
String pantQTY = pantqty.getText().toString().trim();
if (!pantQTY.isEmpty()&&pantQTY!=""){
q = Integer.valueOf(pantQTY);
}
int r = 0;
String shirtQTY = shirtqty.getText().toString().trim();
if (!shirtQTY.isEmpty()&&shirtQTY!=""){
r = Integer.valueOf(shirtQTY);
}
int a = 0;
String suitQTY = suitqty.getText().toString().trim();
if (!suitQTY.isEmpty()&&suitQTY!=""){
a = Integer.valueOf(shirtQTY);
}
int b = 0;
String shareesQTY = shareesqty.getText().toString().trim();
if (!shareesQTY.isEmpty()&&shareesQTY!=""){
b = Integer.valueOf(shirtQTY);
}
int amount = (q*30) + (r*35) + (a*220) + (b*60);
result.setText(Integer.toString(amount));
}
}

i want to create a counter with a text view

i want to create a counter with a text view and want for every 15 click , to change the text in the text view and that is what i have wrote to create the counter ........ i have two text views .... one for the no. of clicks and the another for the text i want to show ,,,,,,,,,,, so i want to use "if" to set the counter to 0 (the counter is tvx) and to change the text (tvx2) to "click 15 more"
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_2);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
btn.setOnClickListener(new View.OnClickListener()
{
public int mCounter;
public Integer tx;
#Override
public void onClick(View v) {
mCounter++;
txv.setText(Integer.toString(mCounter));
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_2);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
public int mCounter=0;
public Integer tx =15;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCounter++;
if(mCounter==tx){
txv.setText(Integer.toString(mCounter));
//reset the counter after 15 click
mCounter=0
}
}
}
);
}
}
you can this way, use the ValueAnimator
public void animateText(Integer startValue, Integer endValue) {
setStartValue(startValue);
setEndValue(endValue);
ValueAnimator animator = ValueAnimator.ofInt(startValue, endValue);
animator.setInterpolator(getInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
String cleanString = animation.getAnimatedValue().toString().replaceAll("[,]", "");
BigDecimal parsed = new BigDecimal(cleanString);
String formatted = NumberFormat.getNumberInstance(Locale.US).format(parsed);
tv.setText(formatted);
}
});
animator.setEvaluator(new TypeEvaluator<Integer>() {
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
return Math.round(startValue + (endValue - startValue) * fraction);
}
});
animator.setDuration(getDuration());
animator.start();
}
Hello Try this if it may help
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_2);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
btn.setOnClickListener(new View.OnClickListener() {
public int mCounter=0;
//initialize mCounter with 0
public Integer tx;
#Override
public void onClick(View v) {
if(mCounter==15){
//check if mCounter equals 15
txv2.setText(Integer.toString("text to display after 15 click"));
//reset mCounter for another iteration
mCounter=0;
}
mCounter++;
//increment the mCounter
txv.setText(Integer.toString(mCounter));
}
});
}
I'm not really understand what do you want, but if you want to increase the counter every 15 click, just add if conditional in your code like this:
btn.setOnClickListener(new View.OnClickListener() {
public int mCounter;
public Integer tx;
#Override
public void onClick(View v) {
mCounter++;
if(mCounter == 15){
tx++;
txv.setText(String.valueOf(tx));
}
}
}
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_2);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
btn.setOnClickListener(new View.OnClickListener() {
public int mCounter;
public Integer tx;
public int mCounter2;
#Override
public void onClick(View v) {
mCounter++;
mCounter2++;
txv.setText(""+mCounter);
if(mCounter2==15){
txv2.setText(""+mCounter2);
mCounter2=0;
}
}
}
);
}
I hope and you serve this
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView txv,txv2;
private int contador = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.bt);
txv = (TextView) findViewById(R.id.tx);
txv2 = (TextView) findViewById(R.id.tx2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
++contador;
if(contador <= 15){
txv.setText(String.valueOf(contador));
}else{
txv2.setText("your text");
}
}
});
}
}

Where do i add the timer code in my program ?

This is my top of my code:
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private String[] ipaddresses = new String[]{
"http://10.0.0.1:8098/?cmd=nothing",
"http://192.168.1.10:8098/?cmd=nothing"};
private String iptouse = "";
private TextView text;
private boolean connectedtoipsuccess = false;
private int counter = 0;
private NotificationCompat.Builder mbuilder;
private Timer timer = new Timer();
TextView timerTextView;
long startTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
And i want to add this code to my program so when i'm running my program i will the timer running.
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
timerTextView = (TextView) findViewById(R.id.timerTextView);
Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
#Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
What i want it to do is once i'm running the program the timer will start.
But i can't find how and where to add this part of the timer code.
I tried in the onCreate and i tried after the onCreate but it give errors since you can just add #override
You will probably want to set up another class (either in the same class or in its own class) and implement Runnable then from your on create make instance to that runnable.

Android integer conversion from EditText failed

I'm trying to set a value in a Handler from a Dialog edittext but i get an error. The code is this:
private Button btnstart;
private Button btnstop;
TimePicker myTimePicker;
final static int RQS_1 = 1;
TimePickerDialog timePickerDialog;
Context context;
private int n = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnstart = (Button)findViewById(R.id.btnstart);
btnstart.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
LayoutInflater l = LayoutInflater.from(MainActivity.this);
View dview = l.inflate(R.layout.dialog, null);
AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);
ad.setView(dview);
final EditText edit = (EditText) dview.findViewById(R.id.edit);
String e = edit.getText().toString();
n = Integer.parseInt(e);
ad.setCancelable(false)
.setTitle("Imposta i Secondi")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
Toast.makeText(getApplicationContext(), "Start",Toast.LENGTH_LONG).show();
}
}, n);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alertD = ad.create();
alertD.show();
}
});
the n value, usually could be 3000,4000,5000 or any other value in ms as integer value. So i converted the edit value of edittext in integer but i get an error in the logcat:
Invalid int "" at line n = Integer.parseInt(e); what's wrong here?
You need to move these two lines of code from where they are now to inside the onClick handler of the DialogInterface.OnClickListener.
String e = edit.getText().toString();
n = Integer.parseInt(e);
revised code
private Button btnstart;
private Button btnstop;
TimePicker myTimePicker;
final static int RQS_1 = 1;
TimePickerDialog timePickerDialog;
Context context;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnstart = (Button)findViewById(R.id.btnstart);
btnstart.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
LayoutInflater l = LayoutInflater.from(MainActivity.this);
View dview = l.inflate(R.layout.dialog, null);
AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);
ad.setView(dview);
final EditText edit = (EditText) dview.findViewById(R.id.edit);
ad.setCancelable(false)
.setTitle("Imposta i Secondi")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
String e = edit.getText().toString();
int n = Integer.parseInt(e);
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
Toast.makeText(getApplicationContext(), "Start",Toast.LENGTH_LONG).show();
}
}, n);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alertD = ad.create();
alertD.show();
}
});
At what point does your EditText get populated? This is in a create event so it appears that you are trying to extract an integer from an empty string?
int value;
try{
value = Integer.parseInt(stringValue);
}(Execption e){
value = 0; // If edittext contains letters, space, etc
}
First , you should use try catch for formatting numbers.
String e = edit.getText().toString().trim();
if(e!=null && !e.isEmpty())
{
int n ;
try {
n = Integer.valueOf(e);
} catch (NumberFormatException e) {
e.printStackTrace();
n = 0;
}
}
Hope it helps.

Categories