Multiple random number results - java

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));

Related

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));
}
}

Calling a function every 1.5 seconds after a button is pressed

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

How to use accelerometer to press a button in android?

I am trying to use accelerometer to press a button in android studio for my dice app. Does anyone know how to hook it up to a button, so that when I shake my phone the dice will roll? I've tried to use SensorEventListener but couldn't get it to work. Thanks for any feedback/suggestion.
PS. I'm a noob.
Here is my java code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button rollButton;
rollButton = findViewById(R.id.rollButton);
final ImageView leftDice = findViewById(R.id.diceLeft);
final ImageView rightDice = findViewById(R.id.diceRight);
final ImageView topDice = findViewById(R.id.diceTop);
final int [] diceArray = {
R.drawable.perspective_dice_one,
R.drawable.perspective_dice_two,
R.drawable.perspective_dice_three,
R.drawable.perspective_dice_four,
R.drawable.perspective_dice_five,
R.drawable.perspective_dice_six,
};
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Dice", "You pressed the button!");
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(6);
Log.d("Dice", "The random number is: " + number);
leftDice.setImageResource(diceArray[number]);
number = randomNumberGenerator.nextInt(6);
rightDice.setImageResource(diceArray[number]);
number = randomNumberGenerator.nextInt(6);
topDice.setImageResource(diceArray[number]);
}
});
}
}

every button click to change text view

i coded this lines to change textview1 Continuous when user clicked button but it sucks at value 1 in output why :\
public class dobeyti extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dobeyti);
final TextView tView;
Button mButton;
tView = (TextView)findViewById(R.id.textView1);
mButton = (Button)findViewById(R.id.button);
assert mButton != null;
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = 0;
num++;
tView.setText(Integer.toString(num));
}
});
}
}
Becuase you defined the num value inside the onclick method so it will be reassigned to 0 every time.
Just put int num=0 outside the method like below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dobeyti);
final TextView tView;
Button mButton;
tView = (TextView)findViewById(R.id.textView1);
mButton = (Button)findViewById(R.id.button);
assert mButton != null;
mButton.setOnClickListener(new View.OnClickListener() {
int num = 0;
#Override
public void onClick(View v) {
num++;
tView.setText(Integer.toString(num));
}
});
}
}
Move int num = 0; outside OnClickListener. Every time you click button value on variable num is set to 0 -> increased to 1 and set as text, that is why it stuck at 1.
int num = 0;
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num++;
tView.setText(Integer.toString(num));
}
});
}
}

Android:How to set listener on multiple image buttons?

First of all, I'm using Andorid and Java only for a week and I'm a total newbie.
I need to know which button user clicked and then compare it with good or bad answer.
Here is the code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
Integer[] flags = {
R.drawable.flag_albania,
R.drawable.flag_andorra,
R.drawable.flag_angola,
R.drawable.flag_avganistan,
};
String[] questions = {
"What is the flag of Albania",
"What is the flag of Andorra",
"What is the flag of Angola",
"What is the flag of Avganistan",
};
TextView tv = (TextView) findViewById(R.id.textView1);
int arraySize = flags.length;
Random rand = new Random();
ImageButton button1 = (ImageButton) findViewById(R.id.imageButton1);
int index = rand.nextInt(arraySize);
int questionIndex1 = index;
button1.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button2 = (ImageButton) findViewById(R.id.imageButton2);
index = rand.nextInt(arraySize);
int questionIndex2 = index;
button2.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button3 = (ImageButton) findViewById(R.id.imageButton3);
index = rand.nextInt(arraySize);
int questionIndex3 = index;
button3.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button4 = (ImageButton) findViewById(R.id.imageButton4);
index = rand.nextInt(arraySize);
int questionIndex4 = index;
button4.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
Integer[] question = {
questionIndex1,
questionIndex2,
questionIndex3,
questionIndex4
};
int questionArraySize = question.length;
int questionArray = rand.nextInt(questionArraySize);
tv.setText(questions[question[questionArray]]);
My idea is to compare questionIndex that is randomly selected to a button id but I really don't know how to implement it. Every help is appreciated.
Use this reduced code
ImageButton button1,button2,button3,button4;
ImageButton imagebuttons[]={ button1,button2,button3,button4};
int ids[]={R.id.imageButton1,R.id.imageButton2,R.id.imageButton3,R.id.imageButton4};
for(final int i=0;i<imagebuttons.length;i++)
{
imagebuttons[i]=(ImageButton) findViewById(ids[i]);
int index=rand.nextInt(arraySize);
imagebuttons[i].setImageResource(flags[index]);
flags[index] = flags[--arraySize];
indexes.put(i,index);
imagebuttons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( questionArray==indexes.get(i))
{
}
}
});
I hope this will help you
Try out this way:
button1.setOnClickListener(onClickListener);
button2.setOnClickListener(onClickListener);
/**
* Common click listener
*/
OnClickListener onClickListener = new OnClickListener()
{
#Override
public void onClick(View p_v)
{
switch (p_v.getId())
{
case R.id.imageButton1:
//Your logic here.
break;
case R.id.imageButton2:
//Your logic here.
break;
}
}
}
Write below code
public class MainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
/// Your Above Code ///
tv.setText(questions[question[questionArray]]);
Imagebutton1.setOnClickListener(this);
Imagebutton2.setOnClickListener(this);
Imagebutton3.setOnClickListener(this);
Imagebutton4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == Imagebutton1){
// Write Your Code Here
} else if(v == Imagebutton2){
// Write Your Code Here
} else if(v == Imagebutton3){
// Write Your Code Here
} else if(v == Imagebutton4){
// Write Your Code Here
}
}
}
You can do it this way:
First, make your activity implements onClick Listener:
public class MyActivity extends Activity implements View.OnClickListener{
Then set the action listeners to your buttons:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
.....
then in the listener, check the id:
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
break;
case R.id.imageButton2:
break;
....
}
}
You can do the it this way also. You have to use some int variables to keep the tag value of the button. And also you have to create a onClickListner for the button actions. Coding is as follow
public class MyActivity extends Activity{
//Define the Tag values for image buttons.
private static final int TAG_IMAGE_BTN_1 = 0;
private static final int TAG_IMAGE_BTN_2 = 1;
private static final int TAG_IMAGE_BTN_3 = 2;
private static final int TAG_IMAGE_BTN_4 = 3;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initActivity();
}
private void initActivity(){
//Initialize the image buttons via xml or from the code itself.
//Add the onClickListner_BTN_CLICK and the corresponding tag to the image button
imageBtn1.setTag(TAG_IMAGE_BTN_1);
imageBtn1.setOnClickListener(onClickListner_BTN_CLICK);
imageBtn2.setTag(TAG_IMAGE_BTN_2);
imageBtn2.setOnClickListener(onClickListner_BTN_CLICK);
.......................................................
.......................................................
}
OnClickListener onClickListner_BTN_CLICK = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int iTag = (Integer)v.getTag();
switch (iTag) {
case TAG_IMAGE_BTN_1:
break;
case TAG_IMAGE_BTN_2:
break;
case TAG_IMAGE_BTN_3:
break;
case TAG_IMAGE_BTN_4:
break;
}
}
};
}
The advantages of using the tag values for capture the action,
1)If we use R.id....... then we have to change the value in switch case if we change it in the xml file
2)We can use only one onClickListner for every action in an activity.

Categories