Android random number and edittext - android

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

Related

why i get invalid integer exception each time i click my button?

I have is an android class. I get some data from get extra which are displayed fine. All of the data is strings. Here is my class:
package adapter;
public class AddToCart extends Activity {
EditText quantity=null;
TextView total=null;
TextView name=null;
TextView price=null;
TextView ava=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
Intent intent = getIntent();
final String itemprice = intent.getStringExtra("price");
String itemname = intent.getStringExtra("item");
final String itemava = intent.getStringExtra("ava");
int imagehandler = intent.getIntExtra("image", 0);
Log.e("image handler",imagehandler+"");
name = (TextView)findViewById(R.id.textView2);
price = (TextView)findViewById(R.id.textView4);
total = (TextView)findViewById(R.id.textView7);
ava = (TextView)findViewById(R.id.textView9);
quantity = (EditText)findViewById(R.id.editText1);
Button addtocart = (Button)findViewById(R.id.button1);
ImageView imageview=(ImageView)findViewById(R.id.imageView1);
name.setText(itemname);
price.setText(itemprice);
ava.setText(itemava);
imageview.setImageResource(imagehandler);
addtocart.setOnClickListener(new OnClickListener() {
int currentava = Integer.parseInt(itemava);
#Override
public void onClick(View v) {
try{
String checked = quantity.getText().toString();
if(checked==null) {
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
else {
int x=0;
double y=0.0;
x = Integer.parseInt(quantity.getText().toString());
y = Double.parseDouble(itemprice);
Log.e("x",x+"");
Log.e("y",y+"");
double totalprice=x*y;
total.setText(totalprice+"");
Toast.makeText(AddToCart.this,"your item added succesfully !", Toast.LENGTH_LONG).show();
}
}//view
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
As you can see that quantity is edit text and when some number inserted into it multiply it by price value and show the total price in text view which works just fine when i click the button, but what I really need to do is to handle this functionality with two if statements. First if the edit text for quantity was empty and the user click the button I want a toast to be displayed to says : "please enter a value for quantity" and the other statement that if quantity larger than available to refuse the value and also toast : "please enter value less than available" It doesn't work as I have an invalid integer value exception. Please what is wrong with my code and how can i handle the previous issues?
Declare "itemava" globally and try again
Looks to me where you use ,
if(checked==null){
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
that there are 2 alternatives to this.
1.
Probably the easiest
if(checked==null || quantity.isEmpty()){
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
The addition is the || quantitiy.isEmpty()
I had tons of issues trying to solve for cases when the string was empty and this is the best way and also uses built in functions that are very easy to use.
2.
Not quite as easy but probably the better bet
Rather than checking to see if the string itself is null, it would be best to check if the editText has been changed at all, and then if it has been changed, make sure that it was changed to a non-empty string, like in 1. To do this add a textChangedListener like so:
quantity.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
//set a textChangedFlag to true
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
This will require a boolean flag that should always be initialized to false. Then after setting the flag to true in the onTextChanged method, you should still double check the string, just to be safe (this may be overkill, but I tend to error on the side of caution) by using a similar method as in 1.
if(textChangedFlag && !(checked == NULL || quantity.isEmpty())){
//do your math here
}
else{
Toast.makeText(AddToCart.this,"please enter a valid quantity", Toast.LENGTH_LONG).show();
}
Text can still be empty... Try something like this:
import android.text.TextUtils;
String value = quantity.getText().toString();
if (TextUtils.isEmpty(value)) {
// enter a value toast
} else if (!TextUtils.isDigitsOnly(value)) {
// must be numeric toast (notice the exclamation mark in condition)
} else {
int valueInt = Integer.parseInt(value);
// ...
}

Android: new random sum after each click?

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.

Infinite loop when button is clicked on Android

What I'm trying to do is:
If the EditText input is equal to the random number generated, then stop the loop otherwise keep on the loop and reset input text.
For some reason, I'm getting an infinite loop. I am new to programming, any help is really appreciated.
Here is the code:
public class Main extends Activity implements OnClickListener{
private TextView tvResult;
private TextView tvRandTest;
private EditText et1;
private String randonNumber;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvResult = (TextView) findViewById(R.id.textView4);
tvRandTest = (TextView) findViewById(R.id.textView3);
et1 = (EditText) findViewById(R.id.editText1);
}//End Main
public void myClickHandler(View view)
{
if(view.getId() == R.id.button1)
{
//Generates 6 one digit Random Numbers
int randonNumber1 = (int) (0 + Math.random() * 9);
//Parse Numbers
String rd1 = Integer.toString(randonNumber1);
randonNumber = rd1;
boolean done = false;
do
{
et1.getText().toString();
if(et1.equals(randonNumber))
{
Toast.makeText(Main.this,"Equal Number", Toast.LENGTH_SHORT).show();
tvResult.setText(randonNumber);
done = true;
}//end if
else
{
Toast.makeText(Main.this,"Not Equal Number", Toast.LENGTH_SHORT).show();
et1.setText("");
}//end else
}//End While
while(!done);
}//End if
if(view.getId() == R.id.button2)
{
tvRandTest.setText(randonNumber);
}
}//End Method
#Override
public void onClick(View arg0) {
// TODO
}
}//End Class
if(et1.equals(randonNumber))
I will change it with
if(et1.equals(String.valueOf(randonNumber)))
you put directly the int value inside the equals method two things will happen:
the autboxing will create an Integer object starting from the int value
the toString() method will be called through this object.
the toString() method of Integer in android, as the doc stands:
Returns a string containing a concise, human-readable description of this object.
So you are compareing the address of the new object with the content of et1 and not with its real value. Here the reference
In this line et1.getText().toString(); you need to assign result to variable, for example String input = et1.getText().toString(); Then in next line you need to compare two strings, if(input.equals(randonNumber)) But your program can hang cause of infinity loop on UI thread. You should use TextWatcher
to handle when text in EditText was changed

Using a button and then showing dynamic text

I am writing a program that when the user enter a number text appears according to that number. My problem is that the button line has public void ... after this I am trying to use if statements and return methods, but because of the public void, the return method can not return anything. I tried to close the public void, but I am getting errors. Please help.
The code is as follows. I have included the different codes that I have tried like toast, etc..
ente#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.go);
button.setOnClickListener(mAddListener);
// tv = (TextView) findViewById(R.id.textView1);
}
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v) {
}}
;
//Toast.makeText(Num.this, "This Display", Toast.LENGTH_SHORT).show();
//toast.show();
//finish ();
// long id = 0;
// try
{
PleaseEnter=(EditText)findViewById(R.id.PleaseEnter);
{
}
if (PleaseEnter.equals("1"))
// tv.setText("This is the display 1.");
return "This display";
// Context context = getApplicationContext();
// CharSequence text ="this display";
// int duration =Toast.LENGTH_LONG;
// Toast toast =Toast.makeText(context, text, duration);
// toast.show();
else if (PleaseEnter.equals("2"))
return;
//tv.setText("Dispaly 2");
You can define your own method at Activity level, such as:
private void onTextEdited(String content) {
// deal with the String
}
In the onClick method of your OnClickListener, you can call it such as:
public void onClick(View v) {
EditText myEditText = (EditText) findViewById(R.id.PleaseEnter);
onTextEdited(myEditText.getText().toString());
}

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