infinity double operation resulting in infinity java/android studio - java

I'm trying to do a division (double/double) and the result is Infinity. Can someone help me and explain why that's happening?
I searched some forums, but I didn't get the answer.
I have something like that:
public class CalculoSapIsolada extends AppCompatActivity
{
double areaAcoX;
double numeroBarrasX;
double areaBarraX;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculo_sap_isolada);
//Here is where i get the value of areaBarraX
if(SapataIsolada.getAço()==50)
{
final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner_diametro_aço_x);
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.diametro_aço_CA_50, android.R.layout.simple_spinner_item);
staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
staticSpinner.setAdapter(staticAdapter);
staticSpinner.setPrompt("Selecione o diâmetro da armadura");
staticSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
Object item = adapterView.getItemAtPosition(i);
if (i == 0) {
diametroAçoX = 0.5;
areaBarraX = 0.196;
}
if (i == 1) {
diametroAçoX = 0.63;
areaBarraX = 0.31;
}
if (i == 2) {
diametroAçoX = 0.8;
areaBarraX = 0.5;
}
if (i == 3) {
diametroAçoX = 1;
areaBarraX = 0.785;
}
if (i == 4) {
diametroAçoX = 1.25;
areaBarraX = 1.22;
}
if (i == 5) {
diametroAçoX = 1.6;
areaBarraX = 2.01;
}
if (i == 6) {
diametroAçoX = 2;
areaBarraX = 3.14;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
/* the value of areaAcoX is calculated previously and during the testrun it receives areaAcoX=11.36016 and the value of areaBarraX=0.5 */
numeroBarrasX=areaAcoX/areaBarraX;
Button calcular =(Button)findViewById(R.id.calcular_resultado);
calcular.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//in altura.setText, areaAcoX==11.36016
TextView altura = (TextView)findViewById(R.id.alturaTotal);
altura.setText(""+areaAcoX);
//In ladoLtopo.setText, areaBarraX==0.5
TextView ladoLtopo = (TextView)findViewById(R.id.ladoL_topo);
ladoLtopo.setText(""+areaBarraX);
//In numBarrasX.setText, numeroBarrasX==Infinity
TextView numBarrasX = (TextView)findViewById(R.id.numeroBarras_x);
numBarrasX.setText(""+numeroBarrasX);
});
}
}
I have some similar operations in the code that is not shown here and I didn't get the infinity error in their value.

Dividing by 0.0 of type double yields infinity. Perhaps there's a divide by 0.0 at this line before areaBarraX has been initialized:
numeroBarrasX=areaAcoX/areaBarraX;

Related

Check if a property of a custom object ArrayList is an empty string or not?

I want to hide a WebView object (txtCode) if the code property of a custom object Arraylist (arrQues) contains nothing.
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
Its an ArrayList of custom objects fetched from a database table which is shown below
And if the code property does contains code then I have dynamically added rules to layout as shown below:
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
}
The issue is when I load the second question and so on... the layout gets messed up and the current question number does not shows as 2 even if its 2 as shown in below:
Both of these issues only arises whenever I use...
arrQues.get(count).code.isEmpty() in the code
I have also tried using "" instead of isEmpty() and even null, but the result was same.
Also what I have noticed is only those questions are loaded from database which have something in the code column.
Below is the complete code for Java file
public class QuestionsFragment extends Fragment implements View.OnClickListener {
TextView txtTimer, txtStatus;
LinearLayout boxA, boxB, boxC, boxD, mainContainer;
RelativeLayout submitContainer;
RelativeLayout.LayoutParams submit_params;
RelativeLayout.LayoutParams main_params;
ScrollView scrollView;
Button btnSubmit;
DBHelper dbHelper;
SharedPreferences sharedPreferences;
TextView txtQues;
WebView txtCode;
TextView txtOptA, txtOptB, txtOptC, txtOptD;
String ans;
ArrayList<QuestionModal> arrQues = new ArrayList<>();
ArrayList<String> arrAnswers = new ArrayList<>();
CountDownTimer countDownTimer;
boolean timerSwitch;
int selectedVal, id;
int curr_quesNo = 0;
int count = 0;
int right = 0;
int non_attempted = 0;
public QuestionsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_questions, container, false);
txtQues = view.findViewById(R.id.txtQues);
txtOptA = view.findViewById(R.id.txtOptionA);
txtOptB = view.findViewById(R.id.txtOptionB);
txtOptC = view.findViewById(R.id.txtOptionC);
txtOptD = view.findViewById(R.id.txtOptionD);
txtCode = view.findViewById(R.id.txtCode);
txtStatus = view.findViewById(R.id.txtStatus);
boxA = view.findViewById(R.id.boxA);
boxB = view.findViewById(R.id.boxB);
boxC = view.findViewById(R.id.boxC);
boxD = view.findViewById(R.id.boxD);
scrollView = view.findViewById(R.id.scrollView);
btnSubmit = view.findViewById(R.id.btnSubmit);
submitContainer = view.findViewById(R.id.submitContainer);
mainContainer = view.findViewById(R.id.mainContainer);
submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);
timerSwitch = sharedPreferences.getBoolean("timer_switch", true);
selectedVal = sharedPreferences.getInt("selectedVal", 10);
dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
String levelKey = sharedPreferences.getString("level_key", null);
arrQues = dbHelper.getQues(levelKey, selectedVal);
loadQues(timerSwitch);
txtTimer = view.findViewById(R.id.txtTimer);
switch (sharedPreferences.getString("db_name", null)) {
case "Android":
((MainActivity) getActivity()).setFragTitle("Android Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "Java":
((MainActivity) getActivity()).setFragTitle("Java Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "C":
((MainActivity) getActivity()).setFragTitle("C Quiz");
((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
break;
case "C++":
((MainActivity) getActivity()).setFragTitle("C++ Quiz");
break;
case "Python":
((MainActivity) getActivity()).setFragTitle("Python Quiz");
break;
case "Kotlin":
((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
break;
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerSwitch)
countDownTimer.cancel();
if (id == 0) {
non_attempted++;
arrAnswers.add("NotAttempted");
Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
}
switch (id) {
case R.id.boxA:
arrAnswers.add("A");
break;
case R.id.boxB:
arrAnswers.add("B");
break;
case R.id.boxC:
arrAnswers.add("C");
break;
case R.id.boxD:
arrAnswers.add("D");
break;
}
if ((id == R.id.boxA && ans.equals("A"))
|| (id == R.id.boxB && ans.equals("B"))
|| (id == R.id.boxC && ans.equals("C"))
|| (id == R.id.boxD && ans.equals("D"))) {
right++;
count++;
Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
} else {
count++;
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
}
}
});
return view;
}
public void setBtnDefault() {
boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
public void sendResult() {
int attempted = selectedVal - non_attempted;
Gson gson = new Gson();
String jsonAnswers = gson.toJson(arrAnswers);
String jsonQues = gson.toJson(arrQues);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("right_key", right);
editor.putInt("wrong_key", attempted - right);
editor.putInt("total_key", selectedVal);
editor.putInt("attempted_key", attempted);
editor.putString("arr_answers", jsonAnswers);
editor.putString("arr_ques", jsonQues);
editor.commit();
((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);
}
public void LoadTimer() {
countDownTimer = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("0:" + millisUntilFinished / 1000);
}
#SuppressLint("SetTextI18n")
#Override
public void onFinish() {
txtTimer.setText("Time Over");
}
};
}
#SuppressLint("NewApi")
public void loadQues(boolean timer_switch) {
try {
id = 0;
setBtnDefault();
if (timer_switch) {
LoadTimer();
countDownTimer.start();
}
curr_quesNo++;
txtStatus.setText(curr_quesNo + "/" + selectedVal);
txtOptC.setVisibility(View.VISIBLE);
txtOptD.setVisibility(View.VISIBLE);
txtCode.setVisibility(View.VISIBLE);
main_params.removeRule(RelativeLayout.ABOVE);
submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
txtQues.setText(arrQues.get(count).ques);
txtOptA.setText(arrQues.get(count).optionA);
txtOptB.setText(arrQues.get(count).optionB);
txtOptC.setText(arrQues.get(count).optionC);
txtOptD.setText(arrQues.get(count).optionD);
txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);
if (txtOptC.getText().toString().isEmpty())
txtOptC.setVisibility(View.GONE);
if (txtOptD.getText().toString().isEmpty())
txtOptD.setVisibility(View.GONE);
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
scrollView.arrowScroll(View.FOCUS_DOWN);
}
}, 1000);
}
ans = arrQues.get(count).answer;
boxA.setOnClickListener(this);
boxB.setOnClickListener(this);
boxC.setOnClickListener(this);
boxD.setOnClickListener(this);
} catch (Exception e) {
((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
}
}
#Override
public void onClick(View v) {
setBtnDefault();
id = v.getId();
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
public float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}
}
I solved it, all issues were happening because arrQues.get(count).code was fetching null values from the database(The column "Code" had null values). As soon as I replaced null values with empty strings "" isEmpty() worked perfectly. I guess isEmpty() doesn't work with null values and is only intended for empty strings.

Disabling onClick until int = something

public class MainActivity extends AppCompatActivity {
int foulCounterA = 0;
int scoreOnePointTeamA = 0;
int periodCount = 0;
private TextView tv1;
private TextView period;
private Button startbtn, cancelbtn;
private ToggleButton togbtn;
private boolean isPaused = false;
private boolean isCanceled = false;
private long remainingTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
period = (TextView) findViewById(R.id.period_number);
startbtn = (Button) findViewById(R.id.startBtn);
cancelbtn = (Button) findViewById(R.id.cancelBtn);
togbtn = (ToggleButton) findViewById(R.id.togBtn);
cancelbtn.setEnabled(false);
togbtn.setEnabled(false);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
foulCounterA = 0;
foulCounterB = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
if (periodCount < 3)
periodCount = periodCount + 1;
else periodCount = 4;
period.setText("Period " + periodCount);
startbtn.setEnabled(false);
cancelbtn.setEnabled(true);
togbtn.setEnabled(true);
isPaused = false;
isCanceled = false;
long millisInFuture = 20000; /////20sec
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
});
togbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (togbtn.isChecked()) {
isPaused = true;
} else {
isPaused = false;
long millisInFuture = remainingTime;
long countDownInterval = 1000; /////1sec
new CountDownTimer(millisInFuture, countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
if (isPaused || isCanceled) {
cancel();
} else {
tv1.setText("" + millisUntilFinished / 1000);
remainingTime = millisUntilFinished;
}
}
#Override
public void onFinish() {
startbtn.setEnabled(true);
togbtn.setEnabled(false);
if (periodCount < 4)
tv1.setText("Times up!");
else tv1.setText("Game Over!");
}
}.start();
}
}
});
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isCanceled = true;
period.setText("Period");
tv1.setText("Timer");
startbtn.setEnabled(true);
togbtn.setEnabled(false);
cancelbtn.setEnabled(false);
foulCounterA = 0;
foulCounterB = 0;
periodCount = 0;
displayForTeamAFoul(foulCounterA);
displayForTeamBFoul(foulCounterB);
}
});
}
public void onePointForTeamA(View v) {
scoreTeamA = scoreTeamA + 1;
scoreOnePointTeamA = scoreOnePointTeamA + 1;
displayForTeamA(scoreTeamA);
displayForTeamAOnePoint(scoreOnePointTeamA);
}
public void foulCountForTeamA(View v) {
if (foulCounterA < 5)
foulCounterA = foulCounterA + 1;
else
foulCounterA = 5;
displayForTeamAFoul(foulCounterA);
}
public void displayForTeamAOnePoint(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score_1_point);
scoreView.setText(String.valueOf(score));
}
public void displayForTeamAFoul(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_foul);
scoreView.setText(String.valueOf(score));
}
}
I wanted to make the java code as simple as I can so I've just added the lines for my question. What I'm trying to do is
android:onClick="onePointForTeamA"make this button only clickable when foulCounterA = 5 Failed to add if (foulCounterA = 5); inside public void foulCountForTeamA(View v) {
It gave me an error that way. Says required: boolean, found: int.
What should I do with the code? Any help will be appreeciated
Regarding your concrete question, the syntax of if (foulCounterA = 5); is wrong, because the equation check is have to made by == operator.
So the correct syntax would be if (foulCounterA == 5);
As #OH GOD SPIDERS wrote in the comment, you should check the basics of java operators.
Also I recommend You to search for the answer before asking a new question.

My Calculations are off when Creating a BMI Calculator

Problem: My Calculations are off when I compared the results on my app to the bmi website. THank you so much in advance, also my math is really bad so I apologize in advance.
Here are the results that my app is giving me:
http://www.tiikoni.com/tis/view/?id=8bd04d4
Here are the results based of the BMI Website NIH
http://www.tiikoni.com/tis/view/?id=86d4458
BMIFRAG.java
public class BmiFrag extends Fragment implements View.OnClickListener
{
Button BmiButton;
public static EditText heightFT;
public static EditText heightIn;
public static EditText weightIn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_bmi, container,
false);
BmiButton = (Button) myView.findViewById(R.id.CalculateBmi);
BmiButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.CalculateBmi:
weightIn = (EditText)
getActivity().findViewById(R.id.ETtweight);
heightIn = (EditText)
getActivity().findViewById(R.id.ETHeightIn);
heightFT = (EditText)
getActivity().findViewById(R.id.ETHeightFT);
final TextView tv4 = (TextView)
getActivity().findViewById(R.id.TFDisplayBmi);
String getWeightIN = weightIn.getText().toString();
String getHeightIN = heightIn.getText().toString();
String getHeightFT = heightFT.getText().toString();
if (TextUtils.isEmpty(getWeightIN)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(getHeightIN)) {
heightIn.setError("Please enter your height in Inches");
heightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(getHeightFT)) {
heightFT.setError("Please enter your height in Feet");
heightFT.requestFocus();
return;
}
else {
float weight = Float.parseFloat(getWeightIN );
float heightIN = Float.parseFloat(getHeightIN) ;
float heightFT = Float.parseFloat(getHeightFT) ;
float bmiValue = calculateBMI(weight,heightIN,heightFT);
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" +
bmiInterpretation));
}
break;
}
}
private float calculateBMI(float weight, float heightIN, float v) {
float bmi= (float) (weight/ (heightIN*v)*4.88);
float total= Math.round(bmi);
return total;
}
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
You don't use the same formula. Try this:
float bmi = weight * 703f / (float)Math.pow(heightIN+12f*v,2);
The formula above can be found here.
I hope it helps.

Input Validation not working android studio

For some reason my input Validation is not working. Every time I put calculate it crashes "app" when it should have an error saying that I need to input height/weight. When I do input the numbers it does calculate. Thanks for the help :). I'm new to android studio .
here is my calculation java file
public class BmiFrag extends Fragment implements View.OnClickListener {
Button BmiButton;
private double weight1=0;
private double height1=0;
public static EditText heightIn;
public static EditText weightIn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_bmi, container, false);
BmiButton = (Button) myView.findViewById(R.id.CalculateBmi);
BmiButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.CalculateBmi:
weightIn = (EditText)
getActivity().findViewById(R.id.ETtweight);
heightIn = (EditText) getActivity().findViewById(R.id.ETHeight);
final TextView tv4 = (TextView)
getActivity().findViewById(R.id.TFDisplayBmi);
String str1 = weightIn.getText().toString();
String str2 = heightIn.getText().toString();
float weight = Float.parseFloat(str1);
float height = Float.parseFloat(str2) ;
float bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" + bmiInterpretation));
if (TextUtils.isEmpty(str1)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(str2)) {
heightIn.setError("Please enter your height");
heightIn.requestFocus();
return;
}
break;
}
}
private float calculateBMI(float weight, float height) {
float bmi= (float) (weight/ (height*height)*4.88);
float total= Math.round(bmi);
return total;
}
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
}
#Override
public void onDetach() {
super.onDetach();
}
}
Try to change the code like the following,
if (TextUtils.isEmpty(str1)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(str2)) {
heightIn.setError("Please enter your height");
heightIn.requestFocus();
return;
}else{
float weight = Float.parseFloat(str1);
float height = Float.parseFloat(str2) ;
float bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" + bmiInterpretation));
}
if (TextUtils.isEmpty(str1)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
if (TextUtils.isEmpty(str2)) {
heightIn.setError("Please enter your height");
heightIn.requestFocus();
return;
}
firstly, sort your indentation and variable names out. Never name a variable str1, str2: always meaningful names. Indentation should always be consistent. This will help out but fixing in the future for readability and speed.
You're doing input validation after you actually input and assign things through
calculateBMI() method
That part of your code reads: Lets take text from text fields, interpret the BMI and then see if the textfields are empty

Stuck in while loop / index out of bounds exception

I am trying to figure out when a step occurs. So I have written a method called countSteps to do this. The problem with it is that I get stuck in it because with the while loop I keep getting new data and I don't think it ever returns back to onSensor. I also get an error called indexoutofboundsexception: invalid index 2,size 2.
So my first question is are there any other ways to implement the method I have without the while loop? Second is how can I fix the indexoutofboundsexception.
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationVector;
private Sensor mAccelerometer;
private TextView mTextView4;
private TextView mTextView5;
private TextView mTextView6;
private TextView mTextView7;
private TextView mTextView8;
float a, b, c, d, x, y, z, xyz;
float[] retVals = new float[3];
float avg = 10;
float factor = (float) 1.15;
ArrayList<Float> accelData = new ArrayList<Float>();
public int peakCounter = 0;
public int underAvgCounter = 0;
public void countSteps() {
int n = 0;
float controlPoint = accelData.get(0);
while (accelData.iterator().hasNext()) {
if (accelData.get(n) != accelData.get(n + 1)) {
if (accelData.get(n) > accelData.get(n + 1)) {
if (accelData.get(n) < controlPoint) {
n++;
} else {
if (accelData.get(n) < avg * factor) {
underAvgCounter++;
}
peakCounter++;
n++;
}
} else {
controlPoint = accelData.get(n + 1);
n++;
}
} else {
n++;
}
peakCounter -= underAvgCounter;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView4 = (TextView) findViewById(R.id.textView4);
mTextView5 = (TextView) findViewById(R.id.textView5);
mTextView6 = (TextView) findViewById(R.id.textView6);
mTextView7 = (TextView) findViewById(R.id.textView7);
mTextView8 = (TextView) findViewById(R.id.textView8);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
accelData.add((float) 0);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#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;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
x = event.values[0];
y = event.values[1];
z = event.values[2];
xyz = (float) Math.sqrt((x * x) + (y * y) + (z * z));
accelData.add(xyz);
mTextView7.setText("magnitude accel " + xyz);
countSteps();
mTextView8.setText("steps " + peakCounter);
}
}
while (accelData.iterator().hasNext()) {
Is always true if you have at least 1 element in collection.
accelData.iterator() creates new iterator every time,
accelData.iterator().hasNext() checks for the first element to be in collection every time
n++ is executed until end is reached and
accelData.get(n + 1) throws IndexOutOfBoundsException
One of the things you can do is to use for loop.
for (int n = 0; n < accelData.size() - 1; n++) { // size-1 is used since you're accessing n+1 index
if (accelData.get(n) != accelData.get(n + 1)) {
if (accelData.get(n) > accelData.get(n + 1)) {
if (accelData.get(n) >= controlPoint) {
if (accelData.get(n) < avg * factor) {
underAvgCounter++;
}
peakCounter++;
}
} else {
controlPoint = accelData.get(n + 1);
}
}
}
peakCounter -= underAvgCounter;
Iterator it = accelData.iterator();
while(it.hasNext()) {
float elem = it.next();
...
}
With IndexOutOfBounds, the following code code snippets is an issue:
accelData.get(n) and accelData.get(n + 1)
You are doing a check for iterator().hasNext(), but it doesnt guarantee the existence of n+1 element.
Infinite loop, I think is because you never used iterator().next() to traverse to the next element. Please refer to a simple iterator code for better understanding.
And you can use any looping techniques like for, do while, while and advanced for loops in java, it doesnt matter. All that matters is if you are doing it efficiently and its readable.

Categories