android pass a number through onclicklistener - android

I am trying to ask a user for 2 numbers x and y. When the user clicks the button it will subtract y from x and give the total. What I would like it to do is save the total, and the next time you click the button, it will subtract y from the total. I know I am not passing the total back through again, but I am not sure where to begin.
subtract.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws NumberFormatException {
if (v == subtract)
{
NumberFormat currencyFormatter;
currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
String bString;
String x = startingmoney.getText().toString();
String y = submoney.getText().toString ();
double total = 0.00;
double xm = 0.00;
double ym =0.00;
try
{
xm = Double.parseDouble(x);
}
catch(NumberFormatException n)
{
xm = 0.00;
}
try
{
ym = Double.parseDouble(y);
}
catch(NumberFormatException n)
{
ym = 0.00;
}
total = xm -ym;
bString = currencyFormatter.format(total);
endmoney.setText(bString);
tracker.setText("you have entered " + bString +"\n" + tracker.getText().toString());

There are many ways to do this. One possible way is to make the variable "x" and "y" static. This may not meet your requirement, since you may change the value of "x" and "y" dynamically.
Another way is to change the implement of OnClickListener. You can use it as,
class MyOnClickListener implements OnClickListener
and pass the class (the class which calls "setOnClickListener") to MyOnClickListener, that is, the constructor of MyOnClickListener is like,
MyOnClickListener(CLASS clazz){
this.clazz = clazz;
}
And you can do subtraction with clazz.getX() and clazz.getY().

Related

calculate percentage and display in a texview android studio

I am developing an application where I pass 1 variables int through a string of an activity to next activity, in the next activity I take that string and return it again and an int, then I calculate a percentage and display and a textview, the past variable and approx1 so I check if it is not empty, then I calculate the percentage ex: ((3/45) * 100) and display in a text view, reviewing again for string ... but in any way I make a mistake, what can be ?
Bundle bundle = getIntent (). GetExtras ();
String aprox1 = bundle.getString ("aprox1");
if (aprox1! = null)
try {
num3 = Integer.parseInt (aprox1);
 result = Math.round ((num3 / 45) * 100);
 TextView counter2 = (TextView) findViewById(R.id.textView16);
String abcString2 = Integer.toString (result);
counter2.setText (abcString2);
}
 catch (NumberFormatException e) {
 }
You need to have {} after the if statement like so:
if (aprox1! = null) {
try {
num3 = Integer.parseInt (aprox1);
result = Math.round ((num3 / 45) * 100);
TextView counter2 = (TextView) findViewById(R.id.textView16);
String abcString2 = Integer.toString (result);
counter2.setText (abcString2);
}
catch (NumberFormatException e) {
}
}
Its also worth noting that because num3 is an integer when you divide it by 45 you will get an Integer not a percentage.
To fix this issue, make num3 a double or cast either num3 or 45 to a double before computing the division.
For example, a simple fix would include changing line 4 to the following:
result = Math.round ((num3 / 45.0) * 100);

Code crashes my application for unknown reason

I am making a simple currency calculator for learning purposes and I just have no idea why my code won't work. Currently, when I press the "Convert" button there is a message saying "Appname stopped working"
Here is the code :
public class MainActivity extends AppCompatActivity {
//Button convertButton;
public void convert(View view) {
EditText dkk = (EditText) findViewById(R.id.dkkField);
EditText gbp = (EditText) findViewById(R.id.gbpField);
EditText eur = (EditText) findViewById(R.id.eurField);
EditText usd = (EditText) findViewById(R.id.usdField);
Double dkkNum = Double.parseDouble(dkk.getText().toString());
Double gbpNum = Double.parseDouble(gbp.getText().toString());
Double eurNum = Double.parseDouble(eur.getText().toString());
Double usdNum = Double.parseDouble(usd.getText().toString());
TextView textView = (TextView) findViewById(R.id.resultView);
double dkkTogbp;
double dkkToeur;
double dkkTousd;
double gbpToDkk;
double eurToDkk;
double usdToDkk;
if(dkk!=null){
dkkTogbp = dkkNum * 0.114001;
dkkToeur = dkkNum * 0.134489;
dkkTousd = dkkNum * 0.142729;
textView.setText(dkk+ "DKK is "+ dkkTogbp+" GBP, "+dkkToeur+"EUR, "+ dkkTousd +"USD");
}else if(gbp!=null){
gbpToDkk = gbpNum * 8.77189;
textView.setText(dkk+ "GBP is "+ gbpToDkk+" DKK");
}else if(eur!=null){
eurToDkk = eurNum * 7.43555;
textView.setText(dkk+ "EUR is "+ eurToDkk+" DKK");
}else if(usd!=null){
usdToDkk = usdNum * 7.00630;
textView.setText(dkk+ "USD is "+ usdToDkk+" DKK");
Toast.makeText(getApplicationContext(), dkk.toString() + " DKK", Toast.LENGTH_LONG).show();
}
dkk.setText("");
gbp.setText("");
eur.setText("");
usd.setText("");
}
I discovered that when i remove the code block below and the if statements the program can run without crashing :
Double dkkNum = Double.parseDouble(dkk.getText().toString());
Double gbpNum = Double.parseDouble(gbp.getText().toString());
Double eurNum = Double.parseDouble(eur.getText().toString());
Double usdNum = Double.parseDouble(usd.getText().toString());
Can someone,please, explain why is this happening?
I don't get any errors.
The problem is by parsing the text to a double value.
At first, you should use a try-catch block to save your application for crashing, like this:
try
{
Double dkkNum = Double.parseDouble(dkk.getText().toString());
Double gbpNum = Double.parseDouble(gbp.getText().toString());
Double eurNum = Double.parseDouble(eur.getText().toString());
Double usdNum = Double.parseDouble(usd.getText().toString());
}
catch(NumberFormatException ex)
{
// If the format of the input string is wrong, then you get here the error message
}
catch(NullPointerException ex)
{
// If the input string is null, then you get here the error message
}
Check, whether the text, that should be parsed, has the right syntax, like "1.9".
UPDATE:
If the input string is null, the "parseDouble" method throws a "NullPointerException". For more informations see this link. I have updated the code.

how to add 1 decimal place to score system

Im trying to make the score of my inspection have 1 decimal place so i can have more precise answer.
result = (TextView) findViewById(R.id.displaym1score);
sum=0;
total=0;
box1 = (CheckBox) findViewById(R.id.box1);
box1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (box1.isChecked()) {
sum += 1; int total = 100*sum/37;
result.setText(total + "%");
}
else {
sum -= 1; int total = 100*sum/37;
result.setText(total + "%");
}
}
});
each box you check it updates instantly and the score just needs to have a decimal place like "72.1%" instead of "72%". there is also 36 more boxes set up the same way.
Ive tried a few things and i cannot figure it out. what do i do?
First total must be a float or a double, not int
instead setText( ... put:
result.setText(String.format("%.1f", total) + "%"); // 1 is the decimal places you want
Probably the easiest way is to use a double instead of an int then format the output to display one decimal place.
use double for total and use following method to get your answer.
public double getFormattedTotal(double total){
DecimalFormat precision = new DecimalFormat("0.0");
return precision.format(total);
}

How to Double Score the point for a word?

I have my first Android app and I am having difficulty on how can I double the point for a word/words whenever a player click an imageview. Basically, I want it to function like this: If the player hasn't click the imageview, the pointing system stays the same. If the player clicks the imageview the a message will pop-out (a toast perhaps telling the player that the points for the next 3 words will be doubled). How can I make this happen? How can I double the points for the 3 consecutive words without exceeding?
Here's my code for searching and calculation
//CALCULATE SCORE
private int optionTxtView = 0 ; //which textview to use for addition purposes
private int addClick = 0 ; //No. of clicks for search for calculation
private void calculate(){
x = Integer.parseInt(tv3.getText().toString().replaceAll("\\s",""));
y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
z = x + y;
score.setText(Integer.toString(z));
}
//SEARCH WORD, DISPLAYING SCORE
public void viewWord(View view)
{
String s1= search.getText().toString(); //What word to search
String s2= dbHelper.getData(s1); // If in db, display equivalent score
if(optionTxtView == 0){
//display the score on textview1
tv2.setText(s2);
optionTxtView = 1;
}
else{
if(optionTxtView == 1){
//display the score on textview2
tv3.setText(s2);
optionTxtView = 0;
}
}
//Display search word/s
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();
if(addClick ==0){
calculate();
addClick = 1;
text.setText("");
generatedString="";
}
else{
if(addClick == 1){
calculate();
addClick = 2;
text.setText("");
generatedString="";
}}
boolean sDouble = false
imgView.setOnClickListener(new View.OnClickListener() {
//#Override
public void onClick(View v) {
// Show your Toast message
// double = true;
}
});
and where you are running your game code check the value of sDouble, if its true then double the scoring system inside a for loop, or set an integer value to 0 and increment it for next 3 words, after that set the value of sDouble back to false.
You may also need to make sure that the user doesn't click on the image for the next 3 tries after clicking it once.
Update:
Since your score is a String, you need to parse it to an Integer before performing any mathematical operation, use Integer.parseInt(s2).

For Loop reading infinity

I am trying to make a simple screen that shows you the amount of money you have earned by the second, so im trying to create a live feed type textveiw that updates every second with the amount of money you have earned, with my code when it runs on my phone it only reads "infinity" and when i tried to add in a 1 second delay it froze all together, here is the code that i wrote, i am using a for loop because i didnt know of a better way if anyone has a better way of achieving what i am trying to do please let me know..
// Calculate pay per second
double PPS = (HW/3600);
double OTPPS = (OTW/3600);
double HPDPS = (HPD*3600);
double money = 0;
double Reserve = 0;
loc = 0;
// Display
for(int i=0; i<HPDPS & loc!=7; i++)
{
money = (PPS+Reserve);
Reserve = (Reserve+money);
TextView textView = (TextView) this.findViewById(R.id.yourpay);
textView.setText(String.valueOf(money));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks in advance for any help!
======================================================================================
Here is an edited version but i am still having a problem where it just displays infinity on the screen, how do i fix this? or how do i use the timer method?
public void sendMessage(View view) {
// Receive messages from options page
Intent intent = getIntent();
double HW = intent.getDoubleExtra(Options.MESSAGE_HW, 0);
double OTW = intent.getDoubleExtra(Options.MESSAGE_OTW, 0);
double HPD = intent.getDoubleExtra(Options.MESSAGE_HPD, 0);
// Calculate pay per second
double PPS = (HW/3600);
double OTPPS = (OTW/3600);
double HPDPS = (HPD*3600);
double money = 0;
double Reserve = 0;
// Display
for(int i=0; i<HPDPS; i++)
{
money = (PPS+Reserve);
Reserve = (Reserve+money);
TextView textView = (TextView) this.findViewById(R.id.yourpay);
textView.setText(String.valueOf(money));
}
// set textView
}
Better way is to user a Timer and TimerTask.
EDIT:
Here is a sample application code to user Timer and TimerTask:
final TextView t1 = (TextView) findViewById(R.id.textView1);
final Timer t =new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
t1.setText("Hello" + counter++); //Place your text data here
//Place your stopping condition over here. Its important to have a stopping condition or it will go in an infinite loop.
if(counter == 10)
t.cancel();
}
});
}
}, 1000, 1000);
Hope this helps.
[1] You are doing Bitwise ANDing (Bitwise ANDing -> &) here
for(int i=0; i<HPDPS & loc!=7; i++)
^
[2] Your loc in always 0, because you did loc=0 and in for loop loc is never updated
So loc!=7 is ALWAYS TRUE

Categories

Resources