Call random methods in Android - java

I have a question that I really don't know if it's possible realize it. This is the situation; I have five methods and one button. Actually if I want call a method tapping the button I write:
btnore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//i call the method I need
Met_one();
}
});
What I need is do something like:
btnore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// a random function call the methods.
Random = random of the methods(Met_one, Met_two,Met_three,Met_four,Met_five)
}
});
So in this way when I tap the button sometimes it does a kind of action and sometimes another one at random. It's it possible?

I think the best solution is to use switch with random numbers
Something like this:
Random random = new Random();
int numberOfMethods = 4;
switch(random.nextInt(numberOfMethods)) {
case 0:
method1();
break;
case 1:
method2();
break;
case 2:
method3();
break;
case 3:
method4();
break;
default:
method1();
}

In java Math.random() * 5 This would return a value in the range [0,5].when you press the Button you can invoke it.
inside the onCreate
Button btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(btnOnClickListener);
and
Button.OnClickListener btnOnClickListener=new Button.OnClickListener()
{
#Override
public void onClick(View v) {
if(v==b1)
{
// your Math.random() * 5 function can invoke.
}
}

Yes this is possible. If you have fixed number methods, the probability is going to be 1/n. Eg, with 5, probability is 0.2. You can have something like this, where rand is re-generated every time the button is clicked:
if (rand < 0.2)
Met_one()
else if (rand < 0.4)
Met_two()
else if (rand < 0.6)
Met_three()
... etc

Related

Using a running total for calculator

I made a calculator on android. I get results for only two numbers (1+1), but I would like to be able to do more then one calculation at a time instead of hitting enter every time I need a new answer (1+1-2).
Something like this: 2 + 2 (new operator pressed) 4 + 3 (equals is pressed) 7
But I'm not sure how to implement this on my code.
This is the button code for every operator:
btnPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
perform();
operation = "+";
}
}); // end btnPlus
This is my calculation method:
private void calculate() {
if (operation == null) {
numberInput.setText(null);
} else if (operation.equals("+")){
numResult = (secondNum + firstNum);
numberInput.setText(String.valueOf(numResult));
} else if (operation.equals("-")) {
numResult = (secondNum - firstNum);
numberInput.setText(String.valueOf(numResult));
} else if (operation.equals("/")) {
numResult = (secondNum / firstNum);
numberInput.setText(String.valueOf(numResult));
} else if (operation.equals("*")) {
numResult = (secondNum * firstNum);
numberInput.setText(String.valueOf(numResult));
} // end if statement
}
Also, perform if needed:
private void perform() {
str = "";
secondNum = firstNum;
}
A quick way to solve your problem given your current code is to use textChangeListener/TextWatcher(assuming you have an EditText or TextView) to detect every time an operator is entered then call the operate function. It would look something like this.
myEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// if 2nd operator is detected
// call calculate
// append 2nd operator
}
});
You could do as i suggested in the comment, and just make a list for every operation, and then calculate it every time the current data changes (there may be difffrent ways to "know" if some of the result is final depending on how you can delete from the app.
SOmething like this is what i would do, and then just everytime a button is pressed call the logic for adding the input, and then calculate it and write it out
public class Calc {
private List<String> inputs = new ArrayList<>();
public String calculate(List<String> input){
String result = "";
for(String current : input){
switch (current) {
case "(":
// do stuff
case "+":
//do stuff
default:
// do stuff
}
}
return result;
}
btnPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// add to list, and call calculate
}
}); // end btnPlus
}

How do I make two ImageViews change several images simultaneously

I am currently trying to build a dice rolling app in Android.
I managed to build my basic layout and methods with ease but I am currently stuck with the following issue:
I have two ImageView's on my screen and I need to make them change simultaneously 3 times, a basic simulation of a dice rolling, before the final dice face is presented to the user.
So far I tried it this way:
public void rollDiceAnim() {
////// diceone anim
final android.os.Handler handler = new android.os.Handler();
Runnable runnable = new Runnable() {
int counter = 0;
#Override
public void run() {
if (counter<4) {
counter++;
Log.e("Counter value",counter+"!");
int diceOneAnim = (int) ((Math.random() * 6) + 1);
ImageView dice1_img = (ImageView) findViewById(R.id.dice1_img);
switch (diceOneAnim) {
case 1:
dice1_img.setImageResource(R.drawable.d1);
break;
case 2:
dice1_img.setImageResource(R.drawable.d2);
break;
case 3:
dice1_img.setImageResource(R.drawable.d3);
break;
case 4:
dice1_img.setImageResource(R.drawable.d4);
break;
case 5:
dice1_img.setImageResource(R.drawable.d5);
break;
case 6:
dice1_img.setImageResource(R.drawable.d6);
break;
}
handler.postDelayed(this, 150);
} else {
rollDice();
}
}
};
/////////
///// dice two anim
final android.os.Handler handler2 = new android.os.Handler();
Runnable runnable2 = new Runnable() {
int counter2 = 0;
#Override
public void run() {
if (counter2<4) {
counter2++;
Log.e("Counter value",counter2+"!");
int diceTwoAnim = (int) ((Math.random() * 6) + 1);
ImageView dice2_img = (ImageView) findViewById(R.id.dice2_img);
switch (diceTwoAnim) {
case 1:
dice2_img.setImageResource(R.drawable.d1);
break;
case 2:
dice2_img.setImageResource(R.drawable.d2);
break;
case 3:
dice2_img.setImageResource(R.drawable.d3);
break;
case 4:
dice2_img.setImageResource(R.drawable.d4);
break;
case 5:
dice2_img.setImageResource(R.drawable.d5);
break;
case 6:
dice2_img.setImageResource(R.drawable.d6);
break;
}
handler2.postDelayed(this, 500);
} else {
rollDice();
}
}
};
////////////////////////
handler.postDelayed(runnable, 100);
handler2.postDelayed(runnable2, 100);
}
I have made two runnable objects, each iterating randomly, changing a set of dice faces before presenting the final one.
The problem is when running the two:
handler.postDelayed(runnable, 100);
handler2.postDelayed(runnable2, 100);
They do not run at the same time. After the first handler is finished, the second handler still has some work to do.
I've tried using threads instead of handlers, but my app just crashes.
I think you can try combining that two jobs into a same Runnable.
I would highly suggest checking out the Android API about AsyncTask. It a better way to work with asynchronous request especially if you have more than one.

Random Generator automatically Random

As we know the following code is to Random Number
Random generator = new Random();
number = generator.nextInt(VALUE) + 1;
and i make this code to Random generator if the button click
button1 = (Button)findViewById(R.id.buttonblack);
if(v==button1) {
// Here, we are generating a random number
Random generator = new Random();
number = generator.nextInt(5) + 1;
// The '5' is the number of values
// Here, we are checking to see what the output of the random was
switch(number) {
case 1: if(bla.. bla.. bla.. == 1){
//Do some blaa. blaa. blaa. logic
}
else if(bla.. bla.. bla.. == 2){
//Do some blaa. blaa. blaa. logic
}
break;
//and so on..
My question is how to make Random Generator method is automatically Random every 2 second then increasingly faster, not by clicking a button
and how to make random stop if some button clicked, example
buttonstop = (Button)findViewById(R.id.buttonstop);
buttonstop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//Stop Random generator
}
});
Anyone can Answer? Thank's
use it which starts from 2 seconds to faster by 20 milliseconds
private Handler mHandler = new Handler();
int ms=2000; //2secs.
Define a Runnable:
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
// get random number here
// You could do this call if you wanted it to be periodic:
ms=ms-20; //20ms faster
mHandler.postDelayed(this, ms);
}
};
mHandler.postDelayed(mUpdateTimeTask, 100);

Reset random generator Android

i am creating an app, that in the class i have this random:
public class Ejemplo extends Activity implements OnClickListener {
int ran=(int)(1*Math.random()) +1;
and also have this counter
int contador= 0; // this is just to know how many time i won
then i have 2 buttons a1 and a2
and in my onClick
switch (v.getId()) {
case R.id.a1:
if(ran == 1){
a1.setText("WIN");
contador= contador + 1;
}
else{
a1.setText("0");
}
a1.setClickable(false);
break;
case R.id.a2:
if(ran == 2){
a2.setText("WIN");
contador= contador + 1;
}
else{
a2.setText("0");
}
a2.setClickable(false);
break;
so the problem is that when i press the button: New Game the random is going to have the same number of the random, and i cant just call again the activity bc i dont want to reset my counter: contador.
How i can just reset my random, so it doesnt always select the same button?
just use a Random instead of Math.random it's easier to use, you can have like this:
Random random = new Random(); // random generator
// then inside your onClick this code
if(random.nextBoolean()){
// win
} else {
// lose
}
https://developer.android.com/reference/java/util/Random.html
edit:
it's really much simpler than what you trying to do:
public class Ejemplo extends Activity implements OnClickListener {
Random random = new Random(); // random generator
// then inside the click listener:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.a1:
if(random.nextBoolean()){
a1.setText("WIN");
contador= contador + 1;
gano();
}
else{
a1.setText("0");
}
a1.setClickable(false);
break;
Put int ran=(int)(1*Math.random()) +1; in the onClick rather than declaring it as an instance variable in the activity. So everytime a click happens, your ran variable will have a different value.

New to Android: App Crashes When Running While Loop (Threading?)

I am trying to write and application which, when a button is pressed, will display all the prime numbers from 23 to 499. Now, I know I have my algorithm correct, so that is not the issue as I can run it using S.o.pln in some other Java Development program. The issue I believe lies in my use of a thread as I've never used one before, or maybe my use of a runnable. I could also be where I am appending an integer to a TextView, but, as I am new, I have no idea. Any help is greatly appreciated and if you need anymore context I will be happy to provide it. Thanks...
public class PrimeNumbers extends Activity implements OnClickListener {
Button whatPrime, howManyPrime, resetPrime;
TextView numPrime, ctPrime;
int prime = 23, factor, ct = 0;;
StringBuilder strBuPrime;
String strPrime;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.primenumbers);
initialize();
whatPrime.setOnClickListener(this);
howManyPrime.setOnClickListener(this);
resetPrime.setOnClickListener(this);
}// end onCreate
private void initialize() {
// TODO Auto-generated method stub
whatPrime = (Button) findViewById(R.id.bPrime);
howManyPrime = (Button) findViewById(R.id.bPrimeCount);
resetPrime = (Button) findViewById(R.id.bPrimeReset);
numPrime = (TextView) findViewById(R.id.tvPrimeNumbers);
ctPrime = (TextView) findViewById(R.id.tvPrimeNumbersCount);
}// end initialize
Runnable findPrimes = new Runnable() {
#Override
public void run() {
while (prime <= 499 && prime >= 23) {
factor = 3;
while (prime % factor != 0) // if true start testing
// other
// factors
{
while (factor <= (Math.sqrt(prime))) // testing
// other
// factors
{
if (prime % factor == 0) // factor found, leave
// while
{
factor = 2000;
}
factor++;
}
if (factor != 2001) // no factor found but left
// while, print
// prime, add 1 to counter
{
strPrime = Integer.toString(prime);
strBuPrime.append(strPrime + '\n');
}
factor = 1; // leave while as 1 is a factor of
// everything
}
prime += 2; // test next prime
}
numPrime.post(new Runnable() {
#Override
public void run() {
numPrime.setText(strBuPrime);
}
});
}
};
Thread threadPrimes = new Thread(findPrimes);
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.bPrime:
threadPrimes.start();
break;
case R.id.bPrimeCount:
ctPrime.setText("There are " + ct
+ " prime numbers from 23 to 499.");
break;
case R.id.bPrimeReset:
numPrime.setText("");
ctPrime.setText("");
break;
}
}// end onClick
}
logcat would help, but you are probably overdoing it with the post(Runnable) to append the values to your TextView. Try using a StringBuilder to concatenate everything and set the text all at once. (Or at least in larger chunks.)
You should try using AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
I think your tread is still running in the UI threadpool and causes the UI to lockup.
Android will kill your thread if you lock the UI for ~2-3 seconds.
AsyncTask will also allow you to display a status bar or spinning ring while the runnable does the work.

Categories