I am a newbie at writing Android apps and using Java in general. I have went through most of the Android hello view tutorials but still seem to be lacking some understanding of the basics. Here is a snippet of code I wrote for an app. My goal was to have three edittext boxes for the user to input information. I want the user to put information in two of the three boxes and when they hit the calculate button, it will calculate the third edittext value based on a specific equation. Is there anyway that I can avoid initializing these 3 edittext objects in each of my methods within this class? Any other suggestions for cleaning up or improving this code?
public class PlantPopulation extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText seedSpacing = (EditText)
findViewById(R.id.seedSpacing);
EditText rowSpacing = (EditText)
findViewById(R.id.rowSpacing);
EditText population = (EditText)
findViewById(R.id.population);
seedSpacing.setText(""); //clear values
rowSpacing.setText("");
population.setText("");
}
//check how many boxes are empty
public int checkifempty(String array[]) {
int i = 0;
for (String string : array) {
if (string.equals("")) {
i = i+1;
}
}
return i;
}
//run the calculation
public void calc(View v) {
EditText seedSpacing = (EditText)
findViewById(R.id.seedSpacing);
EditText rowSpacing = (EditText)
findViewById(R.id.rowSpacing);
EditText population = (EditText)
findViewById(R.id.population);
String sS = seedSpacing.getText().toString();
String rS = rowSpacing.getText().toString();
String pop = population.getText().toString();
String boxes[] = {sS,rS,pop};
//determine which box is empty
if (checkifempty(boxes) <2) {
if (sS.equals("")) {
double calc1=(43560*144)/new Double(rS)/
new Double(pop);
calc1 = Math.floor(calc1 * 100 +.5)/100;
seedSpacing.setText(Double.toString(calc1));
} else if (rS.equals("")) {
double calc2=(43560*144)/new Double(sS)/
new Double(pop);
calc2 = Math.round(calc2);
rowSpacing.setText(Double.toString(calc2));
} else if (pop.equals("")) {
Double calc3=((43560*144)/new Double(rS)/
new Double(sS));
Integer calc = calc3.intValue();
//calc3 = Math.round(calc3);
population.setText(calc.toString());
} else {
Toast.makeText(PlantPopulation.this,
"Leave one item blank.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(PlantPopulation.this,
"You must fill in two of the three boxes.", Toast.LENGTH_SHORT).show();
}
}
}