Android calculator with single edit text displaying complete input and output - android

I want to display the complete input and output of my app.
For example:
2+2=4 needs to be displayed after clicking "=" in the calculator.
My problem is that app closes unexpectedly.
package com.scientific.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ToggleButton;
public class Calculator extends Activity{
EditText display;
Button btn,btnop,add,sub,mul,div;
ToggleButton shift;
String operator,result;
float value=0;
Character op = 'q';
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
display = (EditText)findViewById(R.id.etDisplay);
shift = (ToggleButton)findViewById(R.id.tbShift);
}
public void set_number(View v) {
// TODO Auto-generated method stub
btn = (Button)findViewById(v.getId());
result = display.getText().toString();
display.setText(result+btn.getText().toString());
}
public void btnplusclicked(View v){
perform(v);
op = '+';
}
public void btnminusclicked(View v){
perform(v);
op = '-';
}
public void btndivideclicked(View v){
perform(v);
op = '÷';
}
public void btnmulticlicked(View v){
perform(v);
op = '×';
}
public void btnequalClicked(View v){
evaluate();
}
public void perform(View v) {
// TODO Auto-generated method stub
btnop=(Button)findViewById(v.getId());
result=display.getText().toString();
operator=btnop.getText().toString();
display.setText(result+operator);
}
private void evaluate() {
// TODO Auto-generated method stub
value=Float.valueOf(display.getText().toString());
if(op == '+')
value=Float.valueOf(display.getText().toString())+value;
else if(op == '-')
value=Float.valueOf(display.getText().toString())-value;
else if(op == '/')
value=Float.valueOf(display.getText().toString())/value;
else if(op == '*')
value=Float.valueOf(display.getText().toString())*value;
display.setText(String.valueOf(value));
}
}

It seems you are trying to parse '123+25' to float. so it will give error.
And what if user presses '1+2-3*4' what would be your operator '*' . so it might not work properly. please check here for a good example on calculator for android..

Try to understand this way. When you click equal to evaluate() is called.
In which the first line is value=Float.valueOf(display.getText().toString());
That is converting what is the display to Float.
Though computer is able to convert the first digits but when it come and reads the operator in between. It can't convert that. Hence the crash. Just to be assured.
Type 2 and then press equal I bet it won't crash.
Now either you can do is. When ever a operator ( + - * / ) is called. Use a float variable and calculate it and keep it in the memory. Once the user presses Equal to. Display that Value. Simple as it is.
For more reference Have a look at simple cal or complex calc

Related

How can i have a handler if one of these fields don't have values when user pressed post?

I have this fields where every field is important and I don't have an idea how to do this. Where I want it if I pressed post there will be a message that not all fields have values. Here is my code.
InsertActivity
package com.example.kun.carkila;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.util.HashMap;
public class InsertActivity extends AppCompatActivity implements View.OnClickListener {
EditText etCarModel,etCarType,etCapacity,etImageURL,etFuelType,etPlateNumber;
Button btnPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etCarModel = (EditText)findViewById(R.id.etCarModel);
etCarType = (EditText)findViewById(R.id.etCarType);
etCapacity = (EditText)findViewById(R.id.etCapacity);
etImageURL = (EditText)findViewById(R.id.etImageURL);
etFuelType = (EditText)findViewById(R.id.etFuelType);
etPlateNumber = (EditText)findViewById(R.id.etPlateNumber);
btnPost = (Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
}
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("txtCarModel",etCarModel.getText().toString());
postData.put("txtCarType",etCarType.getText().toString());
postData.put("txtCapacity",etCapacity.getText().toString());
postData.put("txtImage",etImageURL.getText().toString());
postData.put("txtFuelType",etFuelType.getText().toString());
postData.put("txtPlateNumber",etPlateNumber.getText().toString());
PostResponseAsyncTask taskPost = new PostResponseAsyncTask(InsertActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if(s.contains("New records created successfully")){
Toast.makeText(InsertActivity.this, "Car Posted!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(InsertActivity.this, ownerhome.class);
startActivity(in);
}else{
}
}
});
taskPost.execute("http://carkila.esy.es/insert.php");
}
}
Hope for a kind response and I wanted to learn in an easy way. Thank you guys.
Before executing your asynctask you have to check is any EdiText feilds are empty or not. Like
TextUtils.isEmpty(etCarModel.getText().toString())
You have to check for each EditText In starting of OnClick method and if any editText is empty then show alert and do not execute your asynktask.
Check first if each field is empty:
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
if (TextUtils.isEmpty(etCarModel.getText().toString())) {
Toast.makeText(this, "Car model is empty", LENGTH_SHORT).show()
return;
}
postData.put("txtCarModel",etCarModel.getText().toString());
if (TextUtils.isEmpty(etCarType.getText().toString())) {
Toast.makeText(this, "Car type is empty", LENGTH_SHORT).show();
return;
}
postData.put("txtCarType",etCarType.getText().toString());
//and so on
}
Yours is a simple problem. I have, because I needed these checks a lot, created a couple of utility methods for this purpose. You may place them in any class that you want.
safeGetText() to get text from a TextView:
public static String safeGetText(TextView textView, boolean isNullable)
{
String result = null;
if(textView != null)
{
CharSequence text = textView.getText();
if(text != null)
{
result = text.toString();
}
}
if(result == null && !isNullable)
{
// This check is for situations where the text cannot be null.
// Now, I find this utterly pointless, but what the hell.
result = "";
}
return result;
}
'isStringNullOrEmpty()' to check for null/empty strings:
public static boolean isStringNullOrEmpty(#Nullable String input)
{
if (input == null || input.length() <= 0)
{
return true;
}
else
{
return false;
}
}
Although these methods don't do anything magical, they helped me clean up the way I checked for Strings in my TextViews.
When you need to check the input (possibly in onClick()), put up empty checks for each field like:
boolean isEmpty = isStringNullOrEmpty(safeGetText(field, true)); // true/false in arg2 doesn't matter here
You would need to apply this check for every field in your current implementation. You could make arrangements to iterate through all fields in a loop like this:
boolean areFieldsValid = true;
for(TextView field : arrayOfAllFields)
{
boolean isCurrentFieldValid = isStringNullOrEmpty(safeGetText(field, true));
areFieldsValid &= isCurrentFieldValid;
}
// Here, the flag 'areFieldsValid' will only be true if all fields are valid
Let me know if this solves your purpose, and/or if you need more help.
You can use an editText array so that you can use a for loop instead of writing it all over. For key name in Hashmap you can use id name of editText in a for loop
String str = editText[i].getResources().getResourceName(id);
str = str.substring(str.lastIndexOf(":id/") + 4);
postData.put(str,editText[i].getText().toString());
This code will be in a for loop to put all the data.
and in similar way you can check where this strings are null or not.
for(int i=0;i<6;i++){
if(editText[i].getText().toString().equals("")){
//Error alert
}
}
I think this will reduce a lot of LOC.

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

How do I create an android application that takes in numbers in pairs, multiplies them, and adds the result?

Until three weeks ago I knew nothing about developing applications for android, and with very basic Java background.
However, I took up the interest, and I'm now tying to develop a simple application that performs basic arithmetic operations.
What I would like the application to do is take in figures input by the user, up to 20 pairs, multiply each pair separately, and then add the results.
I have gotten through the multiplication of the pairs, but can't get onto adding up the results.
This is what I have so far for the multiplication part, and it works okay....
public class CalcAlgorithm extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final String LOG_TAG = "MainScreen";
super.onCreate(savedInstanceState);
setContentView(R.layout.calc_algorithm);
final EditText value1=(EditText) findViewById(R.id.value1);
final EditText value2=(EditText) findViewById(R.id.value2);
final EditText value3=(EditText) findViewById(R.id.value3);
final EditText value4=(EditText) findViewById(R.id.value4);
final EditText value5=(EditText) findViewById(R.id.value5);
final EditText value6=(EditText) findViewById(R.id.value6);
final EditText value7=(EditText) findViewById(R.id.value7);
final EditText value8=(EditText) findViewById(R.id.value8);
final EditText value9=(EditText) findViewById(R.id.value9);
final EditText value10=(EditText) findViewById(R.id.value10);
final TextView result=(Button) findViewById (R.id.multiplyValues);
final TextView result2=(Button) findViewById (R.id.multiplyValues2);
final TextView result3=(Button) findViewById (R.id.multiplyValues3);
final TextView result4=(Button) findViewById (R.id.multiplyValues4);
final TextView result5=(Button) findViewById (R.id.multiplyValues5);
final TextView result6=(Button) findViewById (R.id.addButton);
Button multiplyButton = (Button)findViewById(R.id.multiplyValues);
multiplyButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try {
int val1=Integer.parseInt(value1.getText().toString());
int val2=Integer.parseInt(value2.getText().toString());
Integer answer = val1*val2;
result.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to multiply numbers",e);
}
}
});
Button multiplyButton2 = (Button) findViewById(R.id.multiplyValues2);
multiplyButton2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val3 = Integer.parseInt(value3.getText().toString());
int val4 = Integer.parseInt(value4.getText().toString());
Integer answer = val3 * val4;
result2.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to multiply numbers",e);
}
}
});
Button multiplyButton3 = (Button) findViewById(R.id.multiplyValues3);
multiplyButton3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val5 = Integer.parseInt(value5.getText().toString());
int val6 = Integer.parseInt(value6.getText().toString());
Integer answer = val5 * val6;
result3.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
});
Button multiplyButton4 = (Button) findViewById(R.id.multiplyValues4);
multiplyButton4.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val7 = Integer.parseInt(value7.getText().toString());
int val8 = Integer.parseInt(value8.getText().toString());
Integer answer = val7 * val8;
result4.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
});
Button multiplyButton5 = (Button) findViewById(R.id.multiplyValues5);
multiplyButton5.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val9 = Integer.parseInt(value9.getText().toString());
int val10 = Integer.parseInt(value10.getText().toString());
Integer answer = val9 * val10;
result5.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG,"Failed to multiply number",e);
}
}
});
Is this the right path? And, i realize that there is a way of summarising the code into fewer lines and not as i have it. Could someone please show me how I can go about having fewer lines of code, and then adding up the results all at once?
After adding the values, I'd again like to perform some more (basic) operations on the results, but i think after I have known how to add the results, I should be able to figure my way from there.
**Perhaps i should point out that i would require the addition to be done once separately i.e on clicking of an added button (TotalSum,maybe) separately and not progressively as the multiplication goes on, such that the user can see the multiplied results for each pair of figures entered, and the total of all paired results on clicking a separate button..
It would also be of immense help if i could get links to some books/documentation/videos that could help with arithmetic functions in writing android applications.
Any help will be greatly appreciated guys. :)
You could add a calculateResultSum() method, which you call at the end of each onClick method with does something like
void calculateResultSum() {
Integer res1 = Integer.parse(result.getText.toString());
// .. get all the other results
Integer finalResult = res1 + res2 + res2 + res4 + res5;
//do something with the result
}
BUT your approach is very redundant, i.e. you have the same code in all of you onClick methods. This is considered bad code style, you should try to extract the actual processing of the numbers into one single method and call this method from each of the listeners, for example
void addNumbers(TextView tv1, TextView tv2, TextViev res){
try {
Integer val1=Integer.parseInt(value1.getText().toString());
Integer val2=Integer.parseInt(value2.getText().toString());
Integer answer = val1*val2;
res.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
}
and set the onClicks to
multiplyButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
addNumbers(value1,value2,result);
calculateResultSum();
});
with the corresponding views for each Button. Hope I could help.
If I understood correctly, here is the solution.
Create a class variable like private int total=0; and in each setOnClickListener add your answers to this variable.
Integer answer = val1*val2;
total += answer;
Also instead of using 5 Button and 10 TextViews you can do this with simply one Button and one TextView storing results in another TextView but you said you are practicing, if it is just to practice it should be alright.
package com.example.calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num1_edt=(EditText)findViewById(R.id.num1_edt);
final EditText num2_edt=(EditText)findViewById(R.id.num2_edt);
final Button add_btn=(Button)findViewById(R.id.add_btn);
findViewById(R.id.sub_btn);
findViewById(R.id.mul_btn);
findViewById(R.id.div_btn);
add_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int a=Integer.parseInt(num1_edt.getText().toString());
int b=Integer.parseInt(num2_edt.getText().toString());
Integer n=a*b;
Toast.makeText(getApplicationContext(),"Your Num Is:"+n.toString(),Toast.LENGTH_LONG).show();
}
});
}
}

how to hide the context of a text field and show it when click button

how do i hide the context of the text field and show it when i click
the button
i do not want to hide the whole text filed just the context i wrote inside it
and show ot when i click a button
*
this is a small code*
package com.example.nonachan;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
char a;
char b;
char c;
int i = 0;
char buf;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText t =(EditText)findViewById(R.id.t1);
ImageButton n = (ImageButton)findViewById(R.id.b1);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
a = 'a';
t.setText(t.getText().toString() + a);
// t.setVisibility(View.INVISIBLE);
}
});
ImageButton a = (ImageButton)findViewById(R.id.b2);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
b = 'b' ;
t.setText(t.getText().toString() + b);
// t.setVisibility(View.INVISIBLE);
i++;
}
});
ImageButton m = (ImageButton)findViewById(R.id.b4);
m.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
c = 'c' ;
t.setText(t.getText().toString() + c);
//t.setVisibility(View.INVISIBLE);
i++;
}
});
Button l = (Button)findViewById(R.id.b3);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// t.setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Assuming you have misspelled contents as context in your question (looks very likely)
instead of trying to hide the contents of the EditText, just save it to a variable and set the text of the EditText to empty. Then in your button click just set the text back to the contents in your local variable
Eg
String hiddenText = null;
EditText text = (EditText)findViewById(R.id.t1);
ImageButton hide = (ImageButton)findViewById(R.id.b1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// save and hide
hiddenText = text.getText();
text.setText("");
}
});
ImageButton unhide = (ImageButton)findViewById(R.id.b2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// unhide the text and 'clear' hiddenText
if (hiddenText != null) {
text.setText(hiddenText);
hiddenText = null;
}
}
});
There are several ways of doing it. It depends how you want to do it. These are just some suggestions off the top of my head, you can even use them all together.
You can put any entered text in a separate string and then if invisible set the TextView to show an empty string, if visible set the TextView to the saved string.
You can use the visibility tag.
You can set the text color to the background color.
You can create/remove the TextView on visible/invisible states.
You can replace the text with symbols for secure inputs if you want (for each character in edittext display an asterisk or something) and then change that back to plain text.
There are a hundred and one ways of doing it, if you search around on previously answered questions you will see several different methods.

Change Text in TextView Box when Button is pressed

I'm fairly new to programming and I am learning to develop in Java and building Android applications.
I am trying to create a Dreidel game, on my xml file, I have a button, an imageview, and a TextView (I will be working on keeping the score a little later, I can figure that out on my own easily enough I imagine).
But the objective is that when I push the button, a random number generator produces a number from 0-3,
If 0, I want the TextBox to display "You get nothing"
If 1, I want the TextBox to display something else
If 2, I want the TextBox to display something else
If 3, I want the TextBox to display something else
Here is the code. When I run it in the Android Emulator, it starts up but nothing happens when I click the button
package com.secondtry;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
numGen.nextInt(4);
if (numGen.nextInt() == 0)
{
display.setText("You get nothing");
}
else if (numGen.nextInt() == 1)
{
display.setText("You get half!");
}
else if (numGen.nextInt() == 2)
{
display.setText("You get it all");
}
else if (numGen.nextInt() == 3)
{
display.setText("Chip in a coin");
} }
});
}
}
Use numGen.nextInt(4) instead of numGen.nextInt() in your condition. Grab its value inside a variable(say x) and use that value in every condition.
You may try this:
int ran = numGen.nextInt(4);
switch (ran){
case 0:
display.setText("You get nothing");
break;
case 1:
display.setText("You get half!");
break;
case 2:
display.setText("You get it all");
break;
case 3:
display.setText("Chip in a coin");
break;
}
You need to either define your button in onCreate with something like
final Button spinButton = (Button) findViewById(R.id.spinbuttonIdInXML);
Or pull the onClick outside of the onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
...
}
#Override
public void onClick(View v) {
...
}
Define your Button in OnCreate Like this..
spinButton = (Button)findViewById(R.id.urbuttonid);
updated try this
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinButton = (Button)findViewById(R.id.ButtonId);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(4);
if (rNumber == 0)
{
display.setText("You get nothing");
}
else if (rNumber == 1)
{
display.setText("You get half!");
}
else if (rNumber == 2)
{
display.setText("You get it all");
}
else if (rNumber == 3)
{
display.setText("Chip in a coin");
} }
});
}
}

Categories

Resources