basic android: syntax for switch statement instead of else-if - java

I am working on an android beginner's tutorial that is a tip calculator. It runs properly, but I was wondering how to replace the else-if statement with a switch statement. Not that it is that important for the purposes of this program, but I'm just trying to wrap my mind around the syntax.
package com.android.tipcalc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Button;
import android.widget.RadioButton;
import android.view.View;
public class tipcalc extends Activity
{
private EditText txtbillamount;
private EditText txtpeople;
private RadioGroup radiopercentage;
private RadioButton radio15;
private RadioButton radio18;
private RadioButton radio20;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople = 0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
radiopercentage = (RadioGroup)findViewById(R.id.radiopercentage);
radio15 = (RadioButton)findViewById(R.id.radio15);
radio18 = (RadioButton)findViewById(R.id.radio18);
radio20 = (RadioButton)findViewById(R.id.radio20);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
txtperperson=(TextView)findViewById(R.id.txtperperson);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
if (radio15.isChecked()) {
percentage = 15.00;
} else if (radio18.isChecked()) {
percentage = 18.00;
} else if (radio20.isChecked()) {
percentage = 20.00;
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
radiopercentage.clearCheck();
radiopercentage.check(R.id.radio15);
txttipamount.setText("...");
txttotal.setText("...");
txtperperson.setText("...");
}
}

What the people above me said is correct, but for the sake of using a switch statement for the hell of it, you could set an OnCheckedChangedListener on your RadioGroup, then use a class like this:
private class MyCheckedChangedListener implements OnCheckedChangeListener {
#Override
public void onCheckedChanged( RadioGroup group, int checkedId ) {
switch (checkedId) {
case R.id.radio15:
percentage = 15f;
break;
case R.id.radio18:
percentage = 18f;
break;
case R.id.radio20:
percentage = 20f;
break;
}
}
}

A switch is used on one variable - i.e. you have x, which can equal 3,5 or 7. Then you switch x and give several cases - what to do on each possible value (you can also have a default case, when none of the given values match). In your case, you're checking several different variables, so if ... else if ... else is the correct method. You can, of course, make the radio boxes set a shared variable, which you can then switch.

If you're talking about the if-else statements in calculate(), you can't replace it directly with a switch statement. The case values in a switch statement need to be compile-time constants (either integers or enum values). Besides, the if-else here perfectly expresses the logic of what you are trying to do.
You could compute a "switch test value" based on the states of radio15, radio18, and radio20 (say, an integer from 0 to 8, based on the eight possible combinations of values) and switch on that, but I would strongly recommend against such an approach. Not only would it needlessly complicate and obscure the logic of what's going on, you would be cursing yourself if you needed to maintain the code six months from now after you had forgotten the clever trick.

Related

Value of sum is not changing when buttons are clicked android

I am trying to change the value of sum based on the buttons that are clicked on my app but the value of sum is not changing.
How do I get the value of sum to change based on the user's choice of button clicking? Thank you.
Here is my code attached below. Any help would be greatly appreciated.
package com.example.admin.project3;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
public class Project3 extends AppCompatActivity {
private TextView textView;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project3);
SeekBar seekBar = findViewById(R.id.mySeekbar);
textView = findViewById(R.id.mySeekBarNumber);
TextView myPrice = findViewById(R.id.myPrice);
RadioButton thickButton = findViewById(R.id.Thick);
RadioButton soggyButton = findViewById(R.id.Soggy);
RadioButton deliveryButton = findViewById(R.id.Deliver);
CheckBox anch = findViewById(R.id.Anchovies);
CheckBox pine = findViewById(R.id.Pineapple);
CheckBox garlic = findViewById(R.id.Garlic);
CheckBox okra = findViewById(R.id.Okra);
double myInches = Double.parseDouble(textView.getText().toString());
double sum = 0;
if(thickButton.isActivated()) sum += 2.50;
if(soggyButton.isActivated()) sum += 5.00;
if(deliveryButton.isActivated()) sum += 3.00;
if(anch.isChecked()) sum += .05*myInches;
if(pine.isChecked()) sum += .05*myInches;
if(garlic.isChecked()) sum += .05*myInches;
if(okra.isChecked()) sum += .05*myInches;
sum += myInches*.05;
String Price = Double.toString(sum);
myPrice.setText(Price);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#SuppressLint("SetTextI18n")
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(progress + " in");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
You're checking if buttons are "activated" and if your CheckBoxes & RadioButtons are checked in onCreate(),
which means this test will only occur once the activity has started.
Instead, use setOnClickListener() on your Buttons, and setOnCheckedChangeListener()
for the RadioButtons & CheckBoxes, and then, whenever a change occurs - change the sum & set the text.
p.s
Variables shouldn't be named with capital letters in the beginning,
so change String Price to String price.

My Simple Interest calculator is crashing with a null pointer exception error

My Simple Interest calculator is crashing with a null pointer exception error, not sure what the problem is, there are no errors in the IDE before I complile, this is new to me. Here is my code and logcat: edit: Icouldn't post a logcat as the editor thinks it's code and I can't get it to format correctly
Code:
package com.codeherenow.sicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.SeekBar;
public class SICalculatorActivity extends Activity
implements SeekBar.OnSeekBarChangeListener, View.OnClickListener{
private int years;
private TextView YT;
private SeekBar bar;
private EditText principal = (EditText) findViewById(R.id.PA_field);
private EditText interest = (EditText) findViewById(R.id.IR_field);
public EditText pvalue;
public EditText ivalue;
private double mPvalue = 0;
private double mIvalue = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
bar = (SeekBar)findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
pvalue = (EditText) principal.getText();
ivalue = (EditText) interest.getText();
String s = principal.getText().toString();
mPvalue = Double.parseDouble(s);
String s2 = interest.getText().toString();
mIvalue = Double.parseDouble(s2);
}
#Override
public void onProgressChanged (SeekBar seekBar,int i, boolean b){
years = i;
YT = (TextView) findViewById(R.id.Years);
YT.setText(years + " Year(s)");
}
#Override
public void onStartTrackingTouch (SeekBar seekBar){
}
#Override
public void onStopTrackingTouch (SeekBar seekBar){
}
#Override
public void onClick(View view) {
TextView fTextView = (TextView) findViewById(R.id.finalText);
double finValue = mPvalue * (mIvalue/100) * years;
fTextView.setText("The interest for " + pvalue + "at a rate of " + ivalue + "for " + years + "year(s) is " + finValue);
}
}
You can't instantiate view variables by calling findViewById as you're declaring them. You have to declare them first and then instantiate either in onCreate or some method invoked after the Activity is bound with the view. Make sure to do it after setContentView(R.layout.sicalculator);
Okay, after seeing your layout, stacktrace and reading more in to your code, I saw that there are fundamental issues which ought to give you more crashes, so let's fix them.
First, pvalue and ivalue variables are unnecessary! Remove them.
Related: You cannot assign an Editable to an EditText. So this line is invalid ivalue = (EditText) interest.getText(); Because getText() returns an Editable. But these are all redundant and unnecessary anyways.
Second, in onCreate method, let's just initialize views and not try to get values and parse them yet; the user (or you) haven't interacted nor entered any values there yet; so trying to parse null values in to Doubles will crash your app.
Your onCreate method should look something like this. (Note that I'm also initializing your button and setting the click listener here).
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
principal = (EditText) findViewById(R.id.PA_field);
interest = (EditText) findViewById(R.id.IR_field);
bar = (SeekBar) findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
calcBtn = (Button)findViewById(R.id.calc_btn);
calcBtn.setOnClickListener(this);
}
Now, you should get the values and parse them in your onClick listener - only when the user has entered values and clicked on the Calculate button, so your onClick() method should look something like this:
#Override
public void onClick(View view)
{
TextView fTextView = (TextView) findViewById(R.id.finalText);
mPvalue = Double.valueOf(principal.getText().toString());
mIvalue = Double.valueOf(interest.getText().toString());
double finValue = mPvalue * (mIvalue / 100) * years;
fTextView.setText("The interest for " + mPvalue + "at a rate of " + mIvalue + "for " + years + "year(s) is " + finValue);
}
And that should clear the logic and order or declaring, initializing, retrieving values from variables for you. I hope this explains how Java and Android basics work.
Oh by the way, I actually ran the code and it's running on my phone so this isn't just off the top of my head. If this helped you, please accept the answer.
Best wishes,

Calling values from an array in the string.xml file in an Android app

I have built a fortune cook app that previously currently has values hardcoded into an array
FortuneActivity.java
package juangallardo.emofortunecookie;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
package juangallardo.emofortunecookie;
import java.util.Random;
public class FortuneBox {
public String[] mFortunes = {
"What is the point?",
"Sometimes it is best to just sleep in.",
#98 other fortunes...
};
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
The problem is that now I want to add a Spanish version. So I realize that i should add that array into the strings.xml.
I looked up string resources on the Android developer page. and it gave me the idea to add this to my code
strings.xml
<string-array name="emo_fortunes">
<item>What is the point?</item>
<item>Sometimes it is best to just sleep in.</item>
</string-array>
But now I am stuck on where to add this part that has the part about Resources, etc.
I followed along to a tutorial from Treehouse about strings but my app kept crashing.
Basically the change that I made was to make the original array into
FortuneBox.java
# above unchanged from previous code
public String[] mFortunes;
# below unchanged from previous code
FortuneActivity.java
# same imports as before
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
Resources resources = getResources();
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
These were my errors, but not sure where to go from here as I am new to Android and I have not touched Java since college.
log
FortuneActivity.java
FortuneBox.java
Mikki has the right answer, but it is a little confusing. In your code above, you are using the same name for two different variables: mFortuneBox. This is the root of your trouble:
private FortuneBox mFortuneBox = new FortuneBox();
...
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Change the second one to a different name, like this, and the errors go away:
final String[] fortunes = resources.getStringArray(R.array.emo_fortunes);
However, you still aren't using these fortunes from the array anywhere. You can actually delete fortunes from your Activity and move it to your FortuneBox class instead. This is slightly tricky, though, as you need to know what the context is to get a string array resource in your other class. The context is the Activity, so you need to pass this along as a parameter when you create your FortuneBox object.
I'd recommend a slight restructuring. Below are the two files that should work for you:
FortuneActivity.java
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
mFortuneBox = new FortuneBox(this);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
public class FortuneBox {
public String[] mFortunes;
public FortuneBox(Context context) {
Resources resources = context.getResources();
mFortunes = resources.getStringArray(R.array.emo_fortunes);
}
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
Your problem is simple. You can not access a non-final from an inner class (in this case your OnClickListener).
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Try just changing the line to look like this one above.
Hope it helps.
The mFortuneBox variable in the previous way you have used is an object of FortuneBox class and hence this call mFortuneBox.getFortune() works.
In the later changed code, you have made mFortuneBox variable a reference to an Array of strings. But still tried calling mFortuneBox.getFortune(). 'getFortune()' is a method of FortuneBox class right, so you can call it with an object of Forune Box class itself.
Try doing this:
final String[] fortuneArray = resources.getStringArray(R.array.emo_fortunes);
and
private FortuneBox mFortuneBox = new FortuneBox();
Now call mFortuneBox.getFortune(fortunearray) sending it this array to the getfortune method.
Now let the getFortune() method randomly pick one from this array passed and return the random string picked

Android variable availability (can not be resolved)

While trying to run my app, I noticed that a few errors claiming that many variables can not be resolved, even though declared in the code
i changed it to the following code, but once I enter the app, it collapses:
public String GetErr(){
String error="";
if(Facebook_name.toString().equals("")&& Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name.toString().equals(""))
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id.toString().equals(""))
error+="Id entered is invalid/n";
if(Pass.toString().length()<5 || Pass.toString().equals(""))
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
EDIT: Now the geterr() returns an empty string at all times.
You are declaring variables in the onCreate() method, so that is their scope. You can not use them outside this function. So when you use them in the GetErr() method, you get an error. You can solve this by moving the variables you need in multiple methods to global variables (so declare them in the class instead of in the method.
Edit
package com.example.app;
//import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
//import android.widget.DatePicker;
import android.widget.TextView;
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
Button Btn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Btn1 = (Button) findViewById(R.id.Btn1);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
Btn1.setOnClickListener(this);
Facebook_chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(Facebook_chk.isChecked())
Facebook_name.setEnabled(true);
else
Facebook_name.setEnabled(false);
;
}
});
}
public String GetErr(){
String error="";
if(Facebook_name==null && Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name==null)
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id==null)
error+="Id entered is invalid/n";
if(Pass.toString().length()<5)
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
#Override
public void onClick(View v) {
if(v == Btn1){
String err = GetErr();
if(err != ""){
Txterr.setText(err);
}
}
}
}
define:
CheckBox Facebook_chk
TextView Facebook_name
TextView Name
TextView Id
TextView Txterr
TextView Pass
As Global Variables, like:
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
...
}
...
}
UPDATE:
If you would like to make a View to respond for Click Event, you'll need to make sure you've set that View clickable.
Since you did:
View v = findViewById(R.id.Btn1);
v.setOnClickListener((OnClickListener) this);
I've no idea R.id.Btn1 is really a Button or just a View. If it is a Button, please change to:
Button button = findViewById(R.id.Btn1);
button.setOnClickListener(this);
If it's not a button, just some View and you want it to respond to your Click, please add one line after findViewById
v.setClickable(true);
Again, if you intend to use this v sometime later in your code, you need to declare it as a global variable just like you did on your TextViews
Ref public void setClickable (boolean clickable)

NullPointerException after changing class ( Code worked before )

I'm doing basic calculator for Android in Java. My calculator worked but i had all code in one class. Then i wanted to make code more readable and i created another Calculation class and i put calculation code in there. And now for some reason my app crashes. LogCat says: NullPointerException. (My app starts fine and then when i choose desirable currency to convert and when i click on ImageButton(convert) then app crashes). Here is my code:
CroToEu class:
package com.eu.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class CroToEur extends Activity {
TextView resultView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cro_to_eur);
final ImageButton convert = (ImageButton) findViewById(R.id.converButton);
convertButton(convert);
}
private void convertButton(final ImageButton convert) {
resultView = (TextView) findViewById(R.id.resultView);
convert.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Calculate now = new Calculate();
now.croToEu();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
convert.setImageResource(R.drawable.convert_button_ontouch);
checkForEmptyEntry();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
convert.setImageResource(R.drawable.convert_button);
}
return false;
}
private void checkForEmptyEntry() {
if(Calculate.HRKfield.getText() == null || "".equals(Calculate.HRKfield.getText().toString())) {
resultView.setText("You left empty field");
} else {
resultView.setText(Calculate.HRKfield.getText()+" HRK = "+Calculate.fixDecimal+" EUR");
}
}
});
}
}
And my calculation class:
package com.eu.calculator;
import java.math.BigDecimal;
import android.app.Activity;
import android.widget.EditText;
public class Calculate extends Activity {
public static EditText HRKfield; //S tem dobimo vrednost iz polja edittext
public static double EUR = 0.133;//drži vrednost
public static Double HRK; // Možnost uporabe double za parsing
public static double result; // rezultat
public static BigDecimal fixDecimal; // rezultat pretvori na decimalko
public BigDecimal croToEu() {
HRKfield = (EditText) findViewById(R.id.enterField);
try {
HRK = Double.parseDouble(HRKfield.getText().toString()); //tukaj dobimo čisto številko, ki jo uporabnik vnese v polje
result = HRK * EUR;
fixDecimal = new BigDecimal(result);
fixDecimal = fixDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
} catch (NumberFormatException e) {
}
return fixDecimal;
}
}
Don' t extend Calculate class with Activity . Remove extends Activity in Calculate class
If you are trying to just create a helper class whcih does the calculation for you then don't extend Activity on your Calculate class. Instead get your croToEu method to return a variable and call this from the other class as follows.
Calculate now = new Calculate();
BigDecimal val = now.croToEu();
Id actually have the caluclate class as follows
public abstract class Calculate {
public static final double EUR = 0.133;//drži vrednost
public static BigDecimal croToEu(double hrkValue) {
BigDecimal fixDecimal = new BigDecimal(hrkValue * EUR);
fixDecimal = fixDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
return fixDecimal;
}
}
Then in your main activity class call
BigDecimal val = Calculate.croToEu(hrkValue);
if(Calculate.HRKfield.getText() == null || "
this is wrong to get the view of other activity .........
you are in CroToEur and your acessing the HRKfield of Calculate activity which will be null
So should pass the data from CroToEur activity to Calculate activity using intent and set that in HRKfield in onCreate of CroToEur
You are missing your onCreate() method and even setContentView in Calculate.class and so it cannot find your edittext HRKfield, and so it is throwing NullpointerException

Categories

Resources