I'm brand new to Android development and right now I am building a simple calculator for healthcare workers. My program implements the OnClickListener class, but every time I click on the button to initiate the calculation, I get an error saying the "Source is not Found".
Here is the code:
public class KidneyeGFR extends Activity implements OnClickListener {
TextView EditAge;
TextView EditSerum;
TextView Gfrtext;
RadioButton Male;
RadioButton Female;
RadioButton EveryoneElse;
RadioButton African;
Button Calculate;
double gender;
double race;
double finalgfr;
private static final int GFRCONST = 186;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditAge = (TextView)this.findViewById(R.id.EditAge);
EditSerum = (TextView)this.findViewById(R.id.EditSerum);
Male = (RadioButton)this.findViewById(R.id.Male);
Male.setChecked(true);
Female = (RadioButton)this.findViewById(R.id.Female);
EveryoneElse = (RadioButton)this.findViewById(R.id.EveryoneElse);
EveryoneElse.setChecked(true);
African = (RadioButton)this.findViewById(R.id.African);
Calculate = (Button)this.findViewById(R.id.Calculate);
Calculate.setOnClickListener(this);
}
public void onClick(View v) {
if (Female.isChecked()) {
gender = 0.742;
}
else {
gender = 1.0;
}
if (African.isChecked()) {
race = 1.212;
}
else {
race = 1.0;
}
calculateGFR();
}
protected void calculateGFR() {
int age = Integer.parseInt(EditAge.getText().toString());
double serum = Double.parseDouble(EditSerum.getText().toString());
finalgfr = GFRCONST * Math.pow(serum, -1.154) * Math.pow(age, -0.203) * gender * race;
Gfrtext.setText(Double.toString(finalgfr));
}
define the TextView Gfrtext...
Gfrtext = (TextView)this.findViewById(R.id.Gfrtext);
Actually you are getting a NullPointerException, check the LogCat or Debug view to have more specific details about your app exceptions.
Thats the big problem!!! =)
I think that you are missing the initialization of Female/African/EditAge/etc. in the onCreate method. Here you should load all of these using the findViewById method. This can easily be checked when debugging (try placing a breakpoint on the first line of the onClick method).
By the way, the convention in Java is that members and methods of an object always start with a lower case and that object names start with an upper case.
Your code doesn't have any trouble ! thats an Eclipse Exception
check this...
Eclipse debugging “source not found”
Related
I'm trying to get the value from Android SpinnerWheel. There are very few post in SO giving answer for this and not one post shows any true information. I found only one link which was a bit descriptive but still didn't have the result I wanted. So if anyone can show me how exactly we can get the value and set it in a TextView, it will be really great
My Code
public class MainActivity extends Activity {
TextView textvalue;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textvalue = (TextView)findViewById(R.id.textvalue);
final AbstractWheel mins = (AbstractWheel) findViewById(R.id.mins);
NumericWheelAdapter minAdapter = new NumericWheelAdapter(this, 0, 59, "%02d");
minAdapter.setItemResource(R.layout.wheel_text_centered_dark_back);
minAdapter.setItemTextResource(R.id.text);
mins.setViewAdapter(minAdapter);
//OnWheelChangedListener listener = null;
//mins.addChangingListener(listener);
}
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(AbstractWheel wheel, int oldValue, int newValue) {
String value = String.valueOf(newValue);
textvalue.setText(value);
}
};
}
.
The only thing I see is, that You haven´t added the listener to Your wheel, because You had commented it out:
//mins.addChangingListener(listener);
It must be:
mins.addChangingListener(changedListener);
In the Following code I am taking an answer from a user for a mathematical question. When the answer is entered the question then updates to a new one.
How would I add validation so that when a user enters letters or hits submit without entering an answer, the question just stays the same and allows the user to enter again. At the minute, when that happens the app crashes. (note: Main functionality I am refering to occurs in onClick).
public class PracticeTest extends Activity implements View.OnClickListener{
//declare vars
int multiplier;
int[] results=new int[12];
int numberPassed;
TextView question;
EditText answer;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practicetest);
// This declares and int variable, assigns it an int value from the
// calling Intent if its not there it is defaulted to 0
numberPassed = getIntent().getIntExtra("convertedNumber2", 0);
//setting up vars(possibly do this in different method?
Button submit = (Button) findViewById(R.id.btnGoPractice2); //declared here as it is only used once
answer = (EditText) findViewById(R.id.etEnterNumberPractice2);
question = (TextView) findViewById(R.id.tvTopPractice2);
//setting listeners
submit.setOnClickListener(this);
updateQuestion();
}
public void onClick(View view) {
// sets text view equal to whats typed in in editText
final String entry = answer.getText().toString();
// convert from string value to int
int a = Integer.parseInt(entry); //note: maybe change name
results[multiplier-1]=a;
score++;//Irrelevant?
if(multiplier<12){
//called after an answer is given
updateQuestion();
} else{
//System.out.println(score);
Intent intent = new Intent(this, Results.class);
intent.putExtra("results", results);
intent.putExtra("numberPassed", numberPassed);
this.startActivity(intent);
}
}
public void updateQuestion(){
multiplier++;
//string to hold quest
String q= numberPassed + "x" + multiplier + "=";
question.setText(q);
answer.setText("");
}
}
So entry is the answer you get? Maybe try regex, you can use this code after submitting the answer or you could check this when a user edits the EditText. The last thing can be done with a TextWatcher, but that would make it a bit more complicated than necessary.
if(entry.matches("[0-9]+") {
// new question
} else {
// warning no valid answer
}
If you want your users only have the option to input numbers. You should set in your EditText:
android:inputType="number"
I'm new to android and I am making an app as part of an assignment, and can't get this function to return a value - the app closes and I get an error message: "Unfortunately, APP has stopped".
I have two classes, one is the MainActivity and one is a class that I am wanting to use to do arithmetic, and they are:
import com.calc.Calculation;
public class MainActivity extends Activity {
private Calculation util;
calculate = (Button) findViewById(R.id.btnCalc);
private TextView tvMultiply;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMultiply = (TextView) findViewById(R.id.tvMult);
}
btnCalc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tvMiltiply.setText(String.valueOf(util.CalculateMult(4,6)));
}
});
}
and
package com.calc;
public class Calculation{
public int CalculateMult(int numOne, int numTwo)
{
return numOne * numTwo;
}
}
I've tried a few alternatives but to no avail. It's going to be something simple that I am not doing quite right.
Any help appreciated.
Thanks
You need to create instance to the class before acccessing the member.
private Calculation util = new Calculation()
Else make the method in the class as static and access without creating instance.
This would be done by defining the class as:
package com.calc;
public class Calculation{
public static int CalculateMult(int numOne, int numTwo)
{
return numOne * numTwo;
}
}
and calling the method as:
Calculation.CalculateMult(4,6)
You should move the line
calculate = (Button) findViewById(R.id.btnCalc);
to the onCreate() function after you have set the content view. You should also move the assignment of the onClickListener to your button to the onCreate() method.
Finally, you should initialize your Calculation object by using the new operator in onCreate(), i.e:
util = new Calculation();
I"m trying to add the onValueChangeListener to my number picker (np1) in android 4.2.2.
Here's what I have so far
public class main extends Activity {
ViewFlipper vf = null;
HttpClient client = null;
private ArrayList<String> captionList = new ArrayList<String>();
ListView lv = null;
private String custid = null;
ImageView iv = null;
private int vfloginview = 0;
private int vflistview = 0;
private boolean vfsentinal = false;
NumberPicker np1 = null;
TextView totalcost = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystuffmobile);
vf = (ViewFlipper) findViewById(R.id.vf);
client = new DefaultHttpClient();
lv = (ListView) findViewById(R.id.lv);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
np1 = (NumberPicker) findViewById(R.id.np1);
np1.setMinValue(1);
np1.setMaxValue(400);
//np1.setOnValueChangedListener;
//np1.setOnValueChangedListener(onValueChange);
}
to try to test it's functionality I've been using this
public void onValueChange (NumberPicker np1, int oldVal, int newVal) {
Log.v("NumberPicker", np1.getValue() +"");
}
Does anyone know an easy way to implement this listener without having my main activity implement NumberPicker.OnValueChangeListener?
Note: the only reason I'm opposed to having my main activity implement NumberPicker.OnValueChangeListener is because then I have to set main to abstract and my application won't run.
You're going to do this just like a click listener on a button.
np1.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// do something here
}
});
A fully working example can be found here: http://samplecodez.com/android/numberpicker.php
Some stylistic points ...
Main should be capitalized and it's a good practice to make it more descriptive like MainActivity.
Use fields only when necessary. I'm guessing you're not using most of those variables outside of onCreate() so make them local variables instead.
TextView totalCost is your best named variable of the lot :) Consider using verbose names. You'll thank yourself 6 months down the road when you look back at this code for the first time in a long time.
No magic values (or Strings)! Create a constant for your min and max values and those should be private static final int with the your fields.
In Eclipse setup the java save actions in preferences to auto format all lines of code when you save.
Of course none of those things will make your code run any better, but it sure will be easier to read.
this is my first time on this forum, so forgive me if my question seems odd. I'll try to be as thorough as possible.
I am creating a translation program.
this program has a menu activity, translate activity, addword activity.
The three activities are linked together via intents and they are
added in the manifest file.
In the translate activity I want to create a method for translating.
After I press the translate button, the program crashes.
public class VertaalActivity extends Activity {
private Button vertaal;
private Button terug;
private EditText ET_NL;
private EditText ET_EN;
private ArrayList<String>nlWoorden = new ArrayList<String>();
private ArrayList<String>enWoorden = new ArrayList<String>();
public void Vertaal(){
String woord = ET_NL.getText().toString();
if(nlWoorden.contains(woord)){
int i = nlWoorden.indexOf(woord);
ET_EN.setText(enWoorden.get(i));
}else{
ET_EN.setText("Woord niet gevonden");
}
}
public void ArrayVullen(){
nlWoorden.add("auto");
nlWoorden.add("bord");
nlWoorden.add("trein");
nlWoorden.add("spel");
nlWoorden.add("scherm");
nlWoorden.add("toetsenbord");
nlWoorden.add("foto");
enWoorden.add("car");
enWoorden.add("plate");
enWoorden.add("train");
enWoorden.add("game");
enWoorden.add("screen");
enWoorden.add("keyboard");
enWoorden.add("picture");
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.vertalerlayout);
terug = (Button)findViewById(R.id.terug);
vertaal = (Button)findViewById(R.id.vertalen);
ArrayVullen();
vertaal.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Vertaal();
/*
* Tested the toast and the toast shows the text
*
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
*/
}
});
terug.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(VertaalActivity.this,MenuActivity.class);
startActivity(intent);
}
});
}
}
I can't see that you get the EditTexts from your XML (like you do with the buttons). Before using ET_NL you need to do something like this:
ET_NL = (EditText)findViewById(R.id.etnl); // Or whatever id you've declared in your layout XML
Same thing goes for the ET_EN variable. Otherwise the will be null in your Vertaal() method, causing the app to crash.
Try this code before using the editText field
ET_NL= (EditText)findViewById(R.id.edittext1);
ET_EN = (EditText)findViewById(R.id.edittext2);