Android: new random sum after each click? - android

In an android app I intend to allow users to answer a random sum then a new one appears on screen. This is repeated 10 times and then a final score will then be given. However I am unsure how to update the sum so that after each each a new random is shown on screen.
Below is my current code:
public class Test extends Activity {
//declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String question;
int correctAnswer;#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
//set up random
setUpRandom();
//Set text view equal to question
text.setText(question);
//updateQuestion?
}
public void initialiseVars() {
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
}
public void setUpRandom() {
//setting up randoms
Random random = new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
question = random1 + " x " + random2 + " = ";
correctAnswer = random1 * random2;
}
public void updateQuestion() {
//CODE TO UPDATE QUESTION
}
}

Add Button ClickListener so that when user press submit button it will update question and clean all previous values
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateQuestion();
}
}
Maintain a count in your activity and increase it in updateQuestion
public void updateQuestion() {
if (Int.parseString(answer.getText().toString()) != correctAnswer) {
// Show toast or something
return;
}
tries++;
if (tries == 10) return; // or do something else;
answer.setText("");
setUpRandom();
text.setText(question); // add this line in your setUpRandom();
}
To generate random integers look at this. Hopefully this will help you out.

Related

How to generate random order for a strings list?

Every time an user click on the button it has to show "John - Sue" or "Sue - John".
I tried with this code:
public class MyActivity extends Activity {
ArrayList<String> names = new ArrayList<String>();
int p1, p2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
names.add("John");
names.add("Sue");
Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p1 = (int)Math.random();
if (p1 == 0)
p2 = 1;
else
p2 = 0;
String msg = names.get(p1) + " - " + names.get(p2);
AlertDialog msgbox = new AlertDialog.Builder(About.this).setTitle("Click here").setMessage(msg).create();
//msgbox.setPositiveButton("OK", null);
msgbox.setCancelable(true);
msgbox.show();
TextView textView = (TextView) msgbox.findViewById(android.R.id.message);
textView.setTextSize(16);
}
});
}
}
But i get always the same order, even i close and run again the app. How to do that?
If you want shuffle list:
Collections.shuffle(names)
If you want random int between 0 or 1 (nextInt(int) javadoc):
Random random = new Random();
int randomInt = random.nextInt(2);
Math.random() returns a number between 0 and 1. So when you cast it to int it will always be 0.
Try this:
p1 = (int)(Math.random()*2);
It happens because
p1 = (int)Math.random();
always gives you zero.

Why does my score counter always reset?

I'm trying to make a game and can't seem to get the score counter to work. The problem is that every time the button is clicked the value of the integer goes back to 0.
public void button(View view){
Integer counter = Integer.valueOf(0);
counter = counter++;
final TextView score = (TextView) findViewById(R.id.score);
score.setText("Score: " + counter);
}
I obviously see why the score goes back to 0 every time but I don't know how to fix it. I'm new with development so some sample code would be appreciated. Thanks.
Here's some modified code from http://developer.android.com/reference/android/widget/Button.html
public class MyActivity extends Activity {
int counter = 0; // Counter variable.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter = counter++;
final TextView score = (TextView) findViewById(R.id.score);
score.setText("Score: " + counter);
}
});
}
}
This should do what you want. Hope it helps!
Because you are resetting it.
Integer counter = Integer.valueOf(0); // here
counter = counter++;
Use it a global variable instead.
public class MyActivity extends Activity{
int counter;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(...);
counter = 0;
}
public void button(View view){
counter = counter++;
final TextView score = (TextView) findViewById(R.id.score);
score.setText("Score: " + counter);
}
}
What you need to do is to initialize your counter in a more persistent part of your program or even as a global variable. Each time you call your function, you are initializing a new counter.
In order to tackle this problem, you should research variable scope.
(Sample link from a Google Search for "Java variable scope".(1) )

Android random number and edittext

What's wrong here ?
Random numbers work well.
Checking the part number also works well.
But when I type a the same number that has been randomly selected is always "Toast Bad".
Code: http://pastebin.com/0pdySnW9
Sorry but i can't paste code here.
In your onClick method you are infact generating another random number.
So the number you are typing in, is NOT going to be equal to the random number, as it is NOT the one displayed on screen.
Depending on what you are trying to achieve.. remove line 32, and make random a global variable.
In your onClick you are generating a new random number with this line
int random = random();
You should make your random variable amember variable so that it can be accessed throughout your activity without changing
ex
public class MainActivity extends Activity implements OnClickListener {
private TextView display;
private Button ok;
public EditText et;
private int random; //note this is now a member variable
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ok = (Button) findViewById(R.id.button1);
ok.setOnClickListener(this);
display = (TextView) findViewById(R.id.textView1);
et = (EditText) findViewById(R.id.etNumbers);
random = random();
display.setText("Random Number:" + random); // Show the random number
}
// ************RANDOM******************************
public static int random() {
Random generator = new Random();
int x = generator.nextInt(100);
return x;
}
// ************************************************
public void onClick(View v) {
// TODO Auto-generated method stub
int numberEntered = -1;
try {
numberEntered = Integer.parseInt(et.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "That's not a number!",
Toast.LENGTH_LONG).show();
}
if (random == numberEntered) {
Toast.makeText(et.getContext(), "Great!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}
}
}

Seekbar creating EditTexts and then getting entries for further use

This code creates a seekbar and makes the seekbar create as many EditText fields as the slider is at / remove ones that would be too much. This code is in OnActivityCreated
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
EditText editText = new EditText(getActivity());
editText.setId(i);
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
SeekBar bar = (SeekBar) getActivity().findViewById(R.id.npv_seekbar);
final TextView selection = (TextView) getActivity()
.findViewById(R.id.npv_selected);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekbar, int progress,
boolean fromUser) {
selection.setText("You have selected " + progress + " periods.");
if (progress == 0) {
String normalstring = getActivity().getResources()
.getString(R.string.npv1);
selection.setText(normalstring);
}
if (i > progress) {
while (i > progress) {
i--;
EditText editText = (EditText) getActivity()
.findViewById(i);
linearLayout.removeView(editText);
}
} else {
while (i < progress) {
EditText editText = new EditText(getActivity());
editText.setId(i);
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(editText);
editText.setHint("Cash Flow " + i);
i++;
}
}
}
public void onStopTrackingTouch(SeekBar arg0) {
}
public void onStartTrackingTouch(SeekBar arg0) {
}
});
This code is in the general class area:
int i = 0;
EditText r = (EditText) getActivity().findViewById(R.id.npv_rate);
Button calc = (Button) getActivity().findViewById(R.id.npv_calc);
EditText[] DynamicField = new EditText[16];
Now I want users to input numbers into those edittext fields and then I want to do some math on them: Entry / (Math.pow(1+r, i) with i beeing the id of the field. The first entry should therefore be calculated as this: entry/(1+r)^0. This is what I tried but it doesn't work. It just crashes on startup.
calc.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Double r1 = Double.parseDouble(r.getText().toString());
EditText editText = (EditText) getActivity().findViewById(i);
TextView answer = (TextView) getActivity().findViewById(R.id.npv_answer);
double[] CashFlows;
CashFlows = new double[i];
double result = 0;
CashFlows[i] = (Double.parseDouble(editText.getText()
.toString())) / (Math.pow(1 + r1, i));
for (double d : CashFlows) {
result += d;
}
answer.setText("answer is " + result);
}
});
What did I do wrong? by the way only the last code segment isnt working. if i comment that out it all works fine i tested it :) just dosent do anything obviuosly :)
ok a little background on the errorlog that you can see here: http://pastebin.com/G8iX6Pkm
EDIT: the entire class file can be seen here: http://pastebin.com/dxA91dst, the entire project can be found here: https://github.com/killerpixler/Android-Financial-Calculator.git
the class file is a fragment that gets loaded in a DetailsActivity when somebody clicks on a listitem from the Main activity. Like i said the error has to be in the button listener because it was working before i added it.
That NullPointerException comes from the fact that you initialize your Views using the getActivity() method where you declare them as fields in the F_NPV class. The method getActivity() method will return a valid Activity reference after the callback onAttach() is called, so the way you initialize the views will not work as, at that moment(when the fields of the Fragment class are initialized) the method getActivity will return null, no valid reference. The correct way to do that initialization is doing it in the onActivityCreated callback:
EditText r;
Button calc;
//...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
r = (EditText) getActivity().findViewById(R.id.npv_rate);
calc = (Button) getActivity().findViewById(R.id.npv_calc);
//...
Also, if I may, some suggestions regarding your code:
You're doing some double's parsing from Strings and it may be a good idea to check the input so you don't throw a NumberFormatException. For example, if the user creates some EditTexts and then clicks the calculate Button(I know, it sounds silly, but there are chances the user will do it(I did it for example)), you'll throw a NumberFormatException as you try to parse an empty String. Instead make a little check:
public void onClick(View arg0) {
Double r1 = Double.parseDouble((r.getText().toString())
.equals("") ? "0" : r.getText().toString());
EditText editText = (EditText) getActivity().findViewById(i);
TextView answer = (TextView) getActivity().findViewById(R.id.npv_answer);
double[] CashFlows;
CashFlows = new double[i];
double result = 0;
String tmp = editText.getText().toString();
CashFlows[i] = (Double.parseDouble(tmp.equals("") ? "0" : tmp))
/ (Math.pow(1 + r1, i));
//...
Also, even if you have correct values in the EditText the above code will throw a NullPointerException, as the editText variable will be null. The reason for this is in the while loops that you used to create the fields. For example, if the user moves the SeekBar to 3 than the while loop will run 3 times, each time incrementing the i value. So i will be 0, 1, 2, so far correct but because you increment i each time the final i will be 4. Now in the onClick method you'll look for an EditText with the id i, but as there is no EditText in the layout with the id 4, the view will be null.
Also, try to give your classes better names, you may know very well what they mean but you could be making things worse for someone that reads your code(like F_PNV, F_PV etc).
Code for the onActivityCreated method. This should solve what you're trying to do(if I understand what you want):
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
r = (EditText) getActivity().findViewById(R.id.npv_rate);
calc = (Button) getActivity().findViewById(R.id.npv_calc);
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
SeekBar bar = (SeekBar) getActivity().findViewById(R.id.npv_seekbar);
final TextView selection = (TextView) getActivity().findViewById(
R.id.npv_selected);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekbar, int progress,
boolean fromUser) {
selection
.setText("You have selected " + progress + " periods.");
if (progress == 0) {
String normalstring = getActivity().getResources()
.getString(R.string.npv1);
selection.setText(normalstring);
linearLayout.removeAllViews(); // the progress is 0 so
// remove all the views that
// are currently present
} else {
int currentChilds = linearLayout.getChildCount();
if (currentChilds < progress) {
while (currentChilds != progress) {
EditText editText = new EditText(getActivity());
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(editText);
currentChilds++;
}
} else if (currentChilds > progress) {
while (currentChilds != progress) {
linearLayout.removeViewAt(linearLayout
.getChildCount() - 1);
currentChilds--;
}
}
}
}
public void onStopTrackingTouch(SeekBar arg0) {
}
public void onStartTrackingTouch(SeekBar arg0) {
}
});
calc.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Double r1 = Double.parseDouble((r.getText().toString())
.equals("") ? "0" : r.getText().toString());
TextView answer = (TextView) getActivity().findViewById(
R.id.npv_answer);
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
int size = linearLayout.getChildCount();
double[] CashFlows = new double[size];
double result = 0;
for (int i = 0; i < size; i++) {
EditText editText = (EditText) linearLayout.getChildAt(i);
String tmp = editText.getText().toString();
CashFlows[i] = (Double.parseDouble(tmp.equals("") ? "0"
: tmp)) / (Math.pow(1 + r1, i));
}
for (double d : CashFlows) {
result += d;
}
answer.setText("answer is " + result);
}
});
}

Regarding android Development

I am doing an application in which I have to display the numbers on TextView randomly and automatically with the help of Timer. I am able to get the random Numbers in the log without repeating, but I am not able to print the same on device please help me...
Regards,
Akki
Source:
//RandomNumber.java
public class RandomNumber extends Activity{
static Random randGen = new Random();
int tambolanum,count=0;
private Button previousbutton;
private Button startbutton;
private Button nextbutton;
int bingonum[]=new int[90];
boolean fill;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.numbers);
LinearLayout number=(LinearLayout)findViewById(R.id.numbersview);
final TextView randomnum=(TextView)findViewById(R.id.numberstext);
previousbutton=(Button)findViewById(R.id.previous);
nextbutton=(Button)findViewById(R.id.next);
startbutton=(Button)findViewById(R.id.start);
startbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on click
//--- Initialize the array to the ints 0-90
do{
fill = true;
//Get new random number
tambolanum = randGen.nextInt(90) + 1;
//If the number exists in the array already, don't add it again
for(int i = 0; i < bingonum.length; i++)
{
if(bingonum == tambolanum)
{
fill = false;
}
}
//If the number didn't already exist, put it in the array and move
//To the next position
if(fill == true)
{
bingonum[count] = tambolanum;
count++;
}
} while(count < 90);
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
}
setText(CharSequence text)
The problem you're having is that you're overwriting your text in every itteration of this loop:
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
You need to build your string first then set it. Something like:
StringBuilder sb = new StringBuilder();
for(i=0;i /* where's the rest of this for-statement? */
{
sb.append(Integer.toString(bingonum[i]);
}
randomnum.setText(sb.toString());

Categories

Resources