Spinner Value is not preserved for 2nd spinner onStart - android

I have two spinners, the information on the 2nd spinner is based on the 1st spinner selection
EXAMPLE
SPINNER 1 PROTEIN DAIRY FRUITS
IF SPINNER 1 IS SET WITH PROTEIN then SPINNER 2 EGG CHICKEN
IF SPINNER 1 IS SET WITH FRUITS then SPINNER 2 APPLE ORANGE
Last value selected SPINNER 2 ORANGE
Now I want to preserve the last values selected of the SPINNER1 and SPINNER2, I am using SharedPreferences to accomplish this, it works as expected for SPINNER 1 FRUITS
Position 2 however for SPINNER2 it does not set the last value selected even though the position is correct position 1 when it is called onStart(); it selects the 1st value that is on the array APPLE
Any help would be appreciated
Thanks
public class TEST extends AppCompatActivity implements View.OnTouchListener {
SharedPreferences sharedPrefStoreInfo, sharedPrefGetInfo;
public String keyRow1, getBackInformationRow1;
String concatenateInfoRow1, currentDateString, concatenateInfoTotals, getBackInformationTotals,
getBackInformationParseTotals[],
getBackInformationParseRow1[]
;
// declare adaptors to bind with spinners
ArrayAdapter<String> spinnerFoodCategoryRow1Adapter;
// declare the references for the UI elements
public static Spinner spinnerFoodCategoryRow1,
spinnerFoodNameRow1,;
private String[] oilsFoodInformation, fruitsFoodInformation, foodCategoryInformation;
TextView day, date, textViewProteinRow1, textViewCarbsRow1, textViewFatRow1, textViewCaloriesRow1,
textViewDailyTotalProtein, textViewDailyTotalCarbs, textViewDailyTotalFat, textViewDailyTotalCalories
;
EditText editRow1;
String textInputRow1, textInputRow1ResultProtein, textInputRow1ResultCarbs, textInputRow1ResultFat,
textInputRow1ResultCalories,
dailyTotalProtein, dailyTotalCarbs, dailyTotalFat, dailyTotalCalories
;
int gramsEditTextInputParseRow1;
double resultIntProteinRow1, resultIntCaloriesRow1, resultIntCarbsRow1, resultIntFatRow1,;
double proteinInfoRule3Row1, carbsInfoRule3Row1, fatInfoRule3Row1, caloriesInfoRule3Row1,;
public String foodNameTempRow1,;
double canolaProtein = 0;
double canolaCarbs = 0;
double canolaFat = 1;
double canolaCalories = 8.84;
double coconutOilProtein = 0;
double coconutOilCarbs = 0;
double coconutOilFat = 1;
double coconutOilCalories = 8.62;
double cornProtein = 0;
double cornCarbs = 0;
double cornFat = 1;
double cornCalories = 9;
double applesProtein = 0;
double applesCarbs = 0;
double applesFat = 0;
double applesCalories = 0;
double apricotsProtein = 0;
double apricotsCarbs = 0;
double apricotsFat = 0;
double apricotsCalories = 0;
double bananasProtein = 0;
double bananasCarbs = 0;
double bananasFat = 0;
double bananasCalories = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_tracker_layout); -
editRow1 = (EditText) findViewById(R.id.editRow1);
textViewProteinRow1 = (TextView) findViewById(R.id.textViewProteinR1);
textViewCarbsRow1 = (TextView) findViewById(R.id.textViewCarbsR1);
textViewFatRow1 = (TextView) findViewById(R.id.textViewFatR1);
textViewCaloriesRow1 = (TextView) findViewById(R.id.textViewCaloriesR1);
spinnerFoodCategoryRow1 = (Spinner) findViewById(R.id.spinner1R1);
spinnerFoodNameRow1 = (Spinner) findViewById(R.id.spinner2R1);
initializeSpinnerFoodCategoryAdapters();
// CHANGE THE FONT SIZE OF SPINNER FOOD CATEGORY
spinnerFoodCategoryRow1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Change the selected item's text color
((TextView) view).setTextColor(Color.BLACK);
((TextView) view).setTextSize(12);
getSelectedFoodCategoryRow1(); // **
// THIS IS TO CHANGE THE FONT SIZE OF SPINNER FOOD NAME
spinnerFoodNameRow1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Change the selected item's text color
((TextView) view).setTextColor(Color.BLACK);
((TextView) view).setTextSize(10);
getSelectedFoodNameRow1();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});// end
} // end
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}// End Main
public void initializeSpinnerFoodCategoryAdapters() {
Resources res = getResources();
spinnerFoodCategoryRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoFoodCategory));
spinnerFoodCategoryRow1.setAdapter(spinnerFoodCategoryRow1Adapter);
spinnerFoodCategoryRow2Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoFoodCategory));
spinnerFoodCategoryRow2.setAdapter(spinnerFoodCategoryRow2Adapter);
}
public String getSelectedFoodCategoryRow1() {
Resources res = getResources();
String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();
sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);
// FOOD NAME OILS ROW1
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 0) {
spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoOils));
spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putInt("ROW1", selectedPosition);
editor.commit();
return selectedspinnerFoodCategoryRow1;
}
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 2) {
spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoFruits));
spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putInt("ROW1", selectedPosition);
editor.commit();
return selectedspinnerFoodCategoryRow1;
}
return selectedspinnerFoodCategoryRow1;
}
// RETRIEVE INFO FOODNAME FROM THE SPINNER ROW1
public String getSelectedFoodNameRow1() {
Resources res = getResources();
String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();
String selectedspinnerFoodNameRow1 = (String) spinnerFoodNameRow1.getSelectedItem();
foodCategoryInformation = res.getStringArray(R.array.SpinnerArrayInfoFoodCategory);
oilsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoOils);
fruitsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoFruits);
for (int n = 0; n < foodCategoryInformation.length; n++) {
// SELECTS INFORMATION ON THE FOOD CATEGORY SPINNER
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == n) {
// SELECT TYPE OF FOOD CATEGORY
switch (selectedspinnerFoodCategoryRow1) {
case "OILS":
foodCategoryTempRow1 = selectedspinnerFoodCategoryRow1;
// ITERATE THE ARRAY TO SELECT THE FOOD NAME ITEM IN OILS
for (int i = 0; i < oilsFoodInformation.length; i++) {
// SELECT FOOD NAME BASED ON POSITION IN DAIRY
if (spinnerFoodNameRow1.getSelectedItemPosition() == i) {
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putInt("ROW1-OILS", i);
editor.commit();
if (selectedspinnerFoodNameRow1.equals("Canola")) {
// ASSIGN THE FOOD NAME SELECTED TO A
// foodNameTempRow1 VARIABLE
foodNameTempRow1 = selectedspinnerFoodNameRow1;
// ASSIGN INFO TO VARIABLES THAT WILL BE USED ON
// THE CALCULATION CLICK BUTTON
proteinInfoRule3Row1 = canolaProtein;
carbsInfoRule3Row1 = canolaCarbs;
fatInfoRule3Row1 = canolaFat;
caloriesInfoRule3Row1 = canolaCalories;
} // end IF CANOLA
if (selectedspinnerFoodNameRow1.equals("Coconut Oil")) {
// ASSIGN THE FOOD NAME SELECTED TO A
// foodNameTempRow1 VARIABLE
foodNameTempRow1 = selectedspinnerFoodNameRow1;
proteinInfoRule3Row1 = coconutOilProtein;
carbsInfoRule3Row1 = coconutOilCarbs;
fatInfoRule3Row1 = coconutOilFat;
caloriesInfoRule3Row1 = coconutOilCalories;
} // end IF Coconut Oil
if (selectedspinnerFoodNameRow1.equals("Corn")) {
// ASSIGN THE FOOD NAME SELECTED TO A
// foodNameTempRow1 VARIABLE
foodNameTempRow1 = selectedspinnerFoodNameRow1;
proteinInfoRule3Row1 = cornProtein;
carbsInfoRule3Row1 = cornCarbs;
fatInfoRule3Row1 = cornFat;
caloriesInfoRule3Row1 = cornCalories;
} // end IF Corn
} // end if OILS POSITION
} // end for OILS
break;
case "FRUITS":
// ASSIGN THE FOOD CATEGORY SELECTED TO A
// foodCategoryTempRow1 VARIABLE
foodCategoryTempRow1 = selectedspinnerFoodCategoryRow1;
// ITERATE THE ARRAY TO SELECT THE FOOD NAME ITEM IN DAIRY
for (int i = 0; i < fruitsFoodInformation.length; i++) {
// SELECT FOOD NAME BASED ON POSITION IN DAIRY
if (spinnerFoodNameRow1.getSelectedItemPosition() == i) {
if (selectedspinnerFoodNameRow1.equals("Apples")) {
// ASSIGN THE FOOD SELECTED TO A
// foodNameTempRow1Dairy VARIABLE
foodNameTempRow1 = selectedspinnerFoodNameRow1;
// ASSIGN INFO TO VARIABLES THAT WILL BE USED ON
// THE CALCULATION CLICK BUTTON
proteinInfoRule3Row1 = applesProtein;
carbsInfoRule3Row1 = applesCarbs;
fatInfoRule3Row1 = applesFat;
caloriesInfoRule3Row1 = applesCalories;
} // end if Apples
if (selectedspinnerFoodNameRow1.equals("Apricots")) {
foodNameTempRow1 = selectedspinnerFoodNameRow1;
proteinInfoRule3Row1 = apricotsProtein;
carbsInfoRule3Row1 = apricotsCarbs;
fatInfoRule3Row1 = apricotsFat;
caloriesInfoRule3Row1 = apricotsCalories;
} // end if Apricots
if (selectedspinnerFoodNameRow1.equals("Bananas")) {
foodNameTempRow1 = selectedspinnerFoodNameRow1;
proteinInfoRule3Row1 = bananasProtein;
carbsInfoRule3Row1 = bananasCarbs;
fatInfoRule3Row1 = bananasFat;
caloriesInfoRule3Row1 = bananasCalories;
} // end if Bananas
} // end if FRUITS POSITION
} // end for FRUITS
break;
}// END SWITCH
} // IF OUTER
} // OUTER FOR LOOP
return selectedspinnerFoodNameRow1;
}// end METHOD GET FOODNAME ROW1
public boolean onTouch(View v, MotionEvent ev) {
boolean handledHere = false;
final int action = ev.getAction();
final int evX = (int) ev.getX();
final int evY = (int) ev.getY();
int nextImage = -1;
ImageView imageView = (ImageView) v.findViewById(R.id.image);
if (imageView == null)
return false;
Integer tagNum = (Integer) imageView.getTag();
int currentResource = (tagNum == null) ? R.drawable.background_food_tracker : tagNum.intValue();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (currentResource == R.drawable.background_food_tracker) {
handledHere = true;
} else
handledHere = true;
break;
case MotionEvent.ACTION_UP:
int touchColor = getHotspotColor(R.id.image_areas, evX, evY);
ColorTouchAreas ct = new ColorTouchAreas();
int tolerance = 25;
nextImage = R.drawable.background_food_tracker;
if (ct.closeMatch(Color.RED, touchColor, tolerance))
{
// GET INPUT EDIT INFORMATION ENTERED IN GRAMS
textInputRow1 = editRow1.getText().toString();
// VALIDATION NOT EMPTY FIELD EDITTEXT
if (textInputRow1.equals(""))
{
MainActivity.mpButtonSumit.start(); // sound
tToast("Please Enter Weight Of Grams For " + foodNameTempRow1);
}
else {
// SELECTS THE TYPE OF FOOD CATEGORY
switch (foodCategoryTempRow1) {
case "OILS":
// tToast("CLICK OILS ROW1"); // TESTING
for (int i = 0; i < oilsFoodInformation.length; i++) {
if (foodNameTempRow1.equals(oilsFoodInformation[i])) {
MainActivity.mpButtonSumit.start(); // sound
// tToast("STRING VALUE= " + textInputRow1);
if (!"".equals(textInputRow1)) {
gramsEditTextInputParseRow1 = Integer.parseInt(textInputRow1);
// tToast("INT VALUE= " +
// String.valueOf(gramsEditTextInputParseRow1));
// //TESTING
resultIntProteinRow1 = (double) (gramsEditTextInputParseRow1
* proteinInfoRule3Row1);
resultIntProteinRow1 = (int) Math.round(resultIntProteinRow1);
// MAKE CALCULATION CARBS
resultIntCarbsRow1 = (double) (gramsEditTextInputParseRow1 * carbsInfoRule3Row1);
resultIntCarbsRow1 = (int) Math.round(resultIntCarbsRow1);
// MAKE CALCULATION FAT
resultIntFatRow1 = (double) (gramsEditTextInputParseRow1 * fatInfoRule3Row1);
resultIntFatRow1 = (int) Math.round(resultIntFatRow1);
// MAKE CALCULATION CALORIES
resultIntCaloriesRow1 = (double) (gramsEditTextInputParseRow1
* caloriesInfoRule3Row1);
resultIntCaloriesRow1 = (int) Math.round(resultIntCaloriesRow1);
// PARSE BACK FROM INTEGER TO STRING TO SET
// THE TEXT WHEN CLICK BUTTON IS CLICED
textInputRow1ResultProtein = Integer.toString((int) resultIntProteinRow1);
textInputRow1ResultCarbs = Integer.toString((int) resultIntCarbsRow1);
textInputRow1ResultFat = Integer.toString((int) resultIntFatRow1);
textInputRow1ResultCalories = Integer.toString((int) resultIntCaloriesRow1);
// CONCATENATE INFORMATION IN ROW 1
concatenateInfoRow1 = textInputRow1ResultProtein + " - " + textInputRow1ResultCarbs
+ " - " + textInputRow1ResultFat + " - " + textInputRow1ResultCalories
;
// CREATE KEY ROW1
keyRow1 = currentDateString + "-" + "keyRow1"; /
sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);
// now get Editor
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
// put your value the key would be current
// date + keyRow1
editor.putString(keyRow1, concatenateInfoRow1);
// commits your edits
editor.commit();
} // end if initial edittext is empty
textViewProteinRow1.setText(textInputRow1ResultProtein);
// CARBS GRAMS
textViewCarbsRow1.setText(textInputRow1ResultCarbs);
// FAT GRAMS
textViewFatRow1.setText(textInputRow1ResultFat);
// CALORIES GRAMS
textViewCaloriesRow1.setText(textInputRow1ResultCalories);
} // end if Oils
} // end for Oils
break;
case "FRUITS":
for (int i = 0; i < fruitsFoodInformation.length; i++) {
if (foodNameTempRow1.equals(fruitsFoodInformation[i])) {
MainActivity.mpButtonSumit.start(); // sound
// tToast("STRING VALUE= " + textInputRow1);
if (!"".equals(textInputRow1)) {
gramsEditTextInputParseRow1 = Integer.parseInt(textInputRow1);
resultIntProteinRow1 = (double) (gramsEditTextInputParseRow1
* proteinInfoRule3Row1);
resultIntProteinRow1 = (int) Math.round(resultIntProteinRow1); // ROUND
// UP
// VALUE
// MAKE CALCULATION CARBS
resultIntCarbsRow1 = (double) (gramsEditTextInputParseRow1 * carbsInfoRule3Row1);
resultIntCarbsRow1 = (int) Math.round(resultIntCarbsRow1); // ROUND
resultIntFatRow1 = (double) (gramsEditTextInputParseRow1 * fatInfoRule3Row1);
resultIntFatRow1 = (int) Math.round(resultIntFatRow1); // ROUND
resultIntCaloriesRow1 = (double) (gramsEditTextInputParseRow1
* caloriesInfoRule3Row1);
resultIntCaloriesRow1 = (int) Math.round(resultIntCaloriesRow1); //
textInputRow1ResultProtein = Integer.toString((int) resultIntProteinRow1);
textInputRow1ResultCarbs = Integer.toString((int) resultIntCarbsRow1);
textInputRow1ResultFat = Integer.toString((int) resultIntFatRow1);
textInputRow1ResultCalories = Integer.toString((int) resultIntCaloriesRow1);
// CONCATENATE INFORMATION IN ROW 1
concatenateInfoRow1 = textInputRow1ResultProtein + " - " + textInputRow1ResultCarbs
+ " - " + textInputRow1ResultFat + " - " + textInputRow1ResultCalories
;
// CREATE KEY ROW1
keyRow1 = currentDateString + "-" + "keyRow1";
sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);
// now get Editor
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putString(keyRow1, concatenateInfoRow1);
// commits your edits
editor.commit();
} // end if initial edittext is empty
// --------------------------------------------------------------------------
textViewProteinRow1.setText(textInputRow1ResultProtein);
textViewCarbsRow1.setText(textInputRow1ResultCarbs);
textViewFatRow1.setText(textInputRow1ResultFat);
textViewCaloriesRow1.setText(textInputRow1ResultCalories);
} // end if FRUITS
} // end for FRUITS
break;
} // END HAND SUBMMIT RED IMAGE BUTTON
else if (ct.closeMatch(Color.WHITE, touchColor, tolerance))
nextImage = R.drawable.background_food_tracker;
;
if (currentResource == nextImage) {
nextImage = R.drawable.background_food_tracker;
}
handledHere = true;
break;
default:
handledHere = false;
} // end switch
if (handledHere) {
if (nextImage > 0) {
imageView.setImageResource(nextImage);
imageView.setTag(nextImage);
}
}
return handledHere;
}// end
// Method
public int getHotspotColor(int hotspotId, int x, int y) {
ImageView img = (ImageView) findViewById(hotspotId);
if (img == null) {
// Log.d ("SubMain", "Hot spot image not found");
return 0;
} else {
img.setDrawingCacheEnabled(true);
Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
if (hotspots == null) {
// Log.d ("ImageAreasActivity", "Hot spot bitmap was not
// created");
return 0;
} else {
img.setDrawingCacheEnabled(false);
return hotspots.getPixel(x, y);
}
}
}// End Method
// ----------------------------------------------------------------------
public void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
// ------------------------------------------------------------------------------------------------------------------
public void onStart() {
super.onStart();
// GET INFORMATION BACK FROM SPINNER BASED ON POSITION STORED
sharedPrefGetInfo = PreferenceManager.getDefaultSharedPreferences(this);
int positionRow1 = sharedPrefGetInfo.getInt("ROW1", 0);
// tToast(String.valueOf(positionRow1)); //TESTING
if (positionRow1 >= 0) {
// LOAD SPINNER INFORMATION ROW1
spinnerFoodCategoryRow1.setSelection(positionRow1);
}
//---------------------------------------HERE IS THE PROBLEM SETTING THE CORRECT VALUE FOR SPINNER --------------------
//THE SPINNER 2 IS NOT BEING SET
Resources res = getResources();
oilsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoOils);
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == positionRow1) {
tToast("OILS TYPE TRUE");
int positionRow1Oils = sharedPrefGetInfo.getInt("ROW1-OILS", 0);
//THIS IS THE CORRECT POSITION FOR SPINNER 2
tToast("POSITION FOODNAME BACK = " + String.valueOf(positionRow1Oils));
// validation
if (positionRow1Oils >= 0) {
for (int n = 0; n < oilsFoodInformation.length; n++) {
spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
res.getStringArray(R.array.SpinnerArrayInfoOils));
spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
tToast("Iteration # = " + n);
// LOAD SPINNER INFORMATION ROW1 OILS
if (n == positionRow1Oils) {
tToast("SPINNER FOOD NAME IS SET");
spinnerFoodNameRow1.setSelection(positionRow1Oils); // NOT
// WORKING
}
}
} // end if
}
// -----------------------------------------------------------------------------------------------------------------------
currentDateString = DateFormat.getDateInstance().format(new Date());
keyRow1 = currentDateString + "-" + "keyRow1";
getBackInformationRow1 = sharedPrefGetInfo.getString(keyRow1, "");
// MAKE SURE THE ARRAY KEY IS NOT EMPTY
if (!getBackInformationRow1.equals("")) {
getBackInformationParseRow1 = getBackInformationRow1.split(" - ", 4);
textViewProteinRow1.setText(getBackInformationParseRow1[0]);
textViewCarbsRow1.setText(getBackInformationParseRow1[1]);
textViewFatRow1.setText(getBackInformationParseRow1[2]);
textViewCaloriesRow1.setText(getBackInformationParseRow1[3]);
}
}// end class

To fix my problem I just got the info stored (sharedPref) on onStart(); and set the spinner using the position (positionRow1Oils) gotten from it, on the method selection for spinner1 spinnerFoodNameRow1.setSelection(positionRow1Oils);
public void onStart() {
super.onStart();
positionRow1Oils = sharedPrefGetInfo.getInt("ROW1-OILS", 0);
}
public String getSelectedFoodCategoryRow1() {
Resources res = getResources();
String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();
sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);
//FOOD NAME OILS ROW1
if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 0)
{
//POPULATE INFORMATION FROM STRINGS XML TO FOOD NAME SPINNERS DEPENDING ON INFORMATION ON SELECTED ON FOOD CATEGORY SPINNER ROW1
spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, res.getStringArray(R.array.SpinnerArrayInfoOils));
spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
//PRESERVE SPINNER INFORMATION ROW1
int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
editor.putInt("ROW1", selectedPosition);
editor.commit();
*//SET SPINNER FOODNAME OILS WITH THE INFORMATION (POSITION) GOT FROM SHARERE PREFERENCE*
spinnerFoodNameRow1.setSelection(positionRow1Oils);
return selectedspinnerFoodCategoryRow1;
}
It seems that, when a spinner2 information is set based in spinner1 information, to preserve the information from spinner2 it should be set in spinner1 method and not on the onStart();
It hope it helps someone facing the same issue.

Related

Not finding why output to TextView is NaN

I've been trying for some days now to figure out why I am not getting a proper output from my app. No errors are showing up in logcat to explain why the output is "NaN" and not the value I'm attempting o calculate. Could someone show me the mistake(s) that I've made? It's a calculator app for my final year school project and I've tried to rectify the issue albeit without much success.
Here is the Main class for the app.
I've tried pretty much anything that has been suggested in various forums for similar issues.
public String educationStr, ethnicity, ldlStr, hdlStr, ageStr, tcStr, sysBPStr, diaBPStr;
public int married=0, education=0, educationSec=0, educationTert=0;
public int smoker=0, ethnicityChk=0;
public int highCholesterol=0;
public int atrialFibrillation=0;
public int familialCVD=0;
public int hypertension=0;
public int sex=0;
public int age=0;
public double tcVal = 0;
public double hdlVal=0;
public double ldlVal = 0;
public int sysBPval = 0;
public int diaBPval = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_calculator);
//spinner for sex choices
Spinner spinnerSex = findViewById(R.id.sexSelect);
ArrayAdapter<CharSequence> adapterSex = ArrayAdapter.createFromResource(this, R.array.SexChoices, simple_spinner_item);
adapterSex.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSex.setAdapter(adapterSex);
spinnerSex.setOnItemSelectedListener(this);
//spinner for marriage choices
Spinner spinnerMarried = findViewById(R.id.marriedSelect);
ArrayAdapter<CharSequence> adapterMarried = ArrayAdapter.createFromResource(this, R.array.YN, simple_spinner_item);
adapterMarried.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerMarried.setAdapter(adapterMarried);
spinnerMarried.setOnItemSelectedListener(this);
//spinner for Ethnicity
Spinner spinnerEthnicity = findViewById(R.id.ethnicitySelect);
ArrayAdapter<CharSequence> adapterEthnicity = ArrayAdapter.createFromResource(this, R.array.EthnicChoices, simple_spinner_item);
adapterEthnicity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerEthnicity.setAdapter(adapterEthnicity);
spinnerEthnicity.setOnItemSelectedListener(this);
//spinner for education
Spinner spinnerEducation = findViewById(R.id.EduLevelSpin);
ArrayAdapter<CharSequence> adapterEducation = ArrayAdapter.createFromResource(this, R.array.EduLevel, simple_spinner_item);
adapterEducation.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerEducation.setAdapter(adapterEducation);
spinnerEducation.setOnItemSelectedListener(this);
//spinner for smoking history
Spinner spinnerSmoker = findViewById(R.id.smokerSelect);
ArrayAdapter<CharSequence> adapterSmoker = ArrayAdapter.createFromResource(this, R.array.smoke, simple_spinner_item);
adapterSmoker.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSmoker.setAdapter(adapterSmoker);
spinnerSmoker.setOnItemSelectedListener(this);
//spinner for family health --> high cholesterol
Spinner spinnerHighCholesterol = findViewById(R.id.highCholesterolSelect);
ArrayAdapter<CharSequence> adapterHighCholesterol = ArrayAdapter.createFromResource(this, R.array.YN, simple_spinner_item);
adapterHighCholesterol.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerHighCholesterol.setAdapter(adapterHighCholesterol);
spinnerHighCholesterol.setOnItemSelectedListener(this);
//spinner for family health --> A Fib
Spinner spinnerAFib = findViewById(R.id.atrialFibrillationSelect);
ArrayAdapter<CharSequence> adapterAFib =
ArrayAdapter.createFromResource(this, R.array.YN, simple_spinner_item);
adapterAFib.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown
item);
spinnerAFib.setAdapter(adapterAFib);
spinnerAFib.setOnItemSelectedListener(this);
//spinner for family health --> Hypertension
Spinner spinnerHypertension = findViewById(R.id.HBPSpinSelect);
ArrayAdapter<CharSequence> adapterHypertension =
ArrayAdapter.createFromResource(this, R.array.YN,
simple_spinner_item);
adapterHypertension.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinnerHypertension.setAdapter(adapterHypertension);
spinnerHypertension.setOnItemSelectedListener(this);
//spinner for family health --> Hypertension
Spinner spinnerFamilialCVD = findViewById(R.id.familialCVDSpin);
ArrayAdapter<CharSequence> adapterFamilialCVD =
ArrayAdapter.createFromResource(this, R.array.YN,
simple_spinner_item);
adapterFamilialCVD.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinnerFamilialCVD.setAdapter(adapterFamilialCVD);
spinnerFamilialCVD.setOnItemSelectedListener(this);
//declaring button
final Button BtnSave = findViewById(R.id.btnSaveNsend);
BtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.ageEnter:
EditText enterAge = findViewById(R.id.ageEnter);
ageStr = enterAge.getText().toString();
age = Integer.valueOf(ageStr);
break;
case R.id.sysBPEnter:
EditText enterSys = findViewById(R.id.sysBPEnter);
sysBPStr = enterSys.getText().toString();
sysBPval = Integer.valueOf(sysBPStr);
break;
case R.id.diaBPEnter:
EditText enterDia = findViewById(R.id.diaBPEnter);
diaBPStr = enterDia.getText().toString();
diaBPval = Integer.valueOf(diaBPStr);
break;
case R.id.tcEnter:
EditText enterTC = findViewById(R.id.tcEnter);
tcStr = enterTC.getText().toString();
tcVal = Integer.valueOf(tcStr);
break;
case R.id.hdlEnter:
EditText enterHDL = findViewById(R.id.hdlEnter);
hdlStr = enterHDL.getText().toString();
hdlVal = Integer.valueOf(hdlStr);
break;
case R.id.ldlEnter:
EditText enterLDL = findViewById(R.id.ldlEnter);
ldlStr = enterLDL.getText().toString();
ldlVal = Integer.valueOf(ldlStr);
}
if (ethnicityChk == 1){
Intent RiskCalc1 = new
Intent(getApplicationContext(),displayLinRiskResult.class);
startActivity(RiskCalc1);
} else if (ethnicityChk == 2){
Intent RiskCalc2 = new
Intent(getApplicationContext(),displayDiscrimRiskResult.class);
startActivity(RiskCalc2);
}
}
});
}
#Override
public void onItemSelected(AdapterView<?>
adapterView, View view, int i, long l) {
switch(adapterView.getId()){
case R.id.sexSelect:
String sexStr = adapterView.getSelectedItem().toString();
if (sexStr.equalsIgnoreCase("female")){
sex = 1;
}
else if (sexStr.equalsIgnoreCase("male")){
sex = 0;
}
//Toast.makeText(adapterView.getContext(), sex,
Toast.LENGTH_SHORT).show();
break;
case R.id.marriedSelect:
String marriedStr = adapterView.getSelectedItem().toString();
if (marriedStr.equalsIgnoreCase("YES")){
married = 1;
}
else if (marriedStr.equalsIgnoreCase("NO")){
married = 0;
}
//Toast.makeText(adapterView.getContext(), married,
Toast.LENGTH_SHORT).show();
break;
case R.id.smokerSelect:
String smokerStr = adapterView.getSelectedItem().toString();
if (ethnicity.equalsIgnoreCase("Afro-Caribbean"))
{if (smokerStr.equalsIgnoreCase("Smoker")){
smoker = 1;
}
else if (smokerStr.equalsIgnoreCase("Non-smoker")){
smoker = 0;
} }
else if (ethnicity.equalsIgnoreCase("Mixed-Caribbean")){
{if (smokerStr.equalsIgnoreCase("Smoker")){
smoker = 0;
}
else if (smokerStr.equalsIgnoreCase("Ex-smoker")){
smoker = 1;
} }}
// Toast.makeText(adapterView.getContext(), smokerStr,
Toast.LENGTH_SHORT);
break;
case R.id.ethnicitySelect:
ethnicity = (String) adapterView.getSelectedItem();
if (ethnicity.equals("Afro-Caribbean")||
(ethnicity.equals("Indo-Caribbean"))){
ethnicityChk = 1;
}
else if (ethnicity.equals("Mixed-Caribbean")){
ethnicityChk = 2;
}
//Toast.makeText(adapterView.getContext(), ethnicityStr,
Toast.LENGTH_SHORT);
break;
case R.id.EduLevelSpin:
educationStr = (String) adapterView.getSelectedItem();
//Toast.makeText(adapterView.getContext(),education,
Toast.LENGTH_SHORT);
if (educationStr.equalsIgnoreCase("Secondary")){
educationSec = 1;
educationTert = 0;
education = 1;
}
else if (educationStr.equalsIgnoreCase("Tertiary")){
educationSec = 1;
educationTert = 1;
education = 1;
}
else {
education = 1;
educationSec = 0;
educationTert = 0;
}
break;
case R.id.highCholesterolSelect:
String highCholesterolStr = (String)
adapterView.getSelectedItem();
if (highCholesterolStr.equalsIgnoreCase("YES")){
highCholesterol = 1;
}
else if (highCholesterolStr.equalsIgnoreCase("NO")){
highCholesterol = 0;
}
//Toast.makeText(adapterView.getContext(),
highCholesterolStr,Toast.LENGTH_SHORT);
break;
case R.id.atrialFibrillationSelect:
String AfibStr = (String) adapterView.getSelectedItem();
if (AfibStr.equalsIgnoreCase("YES")){
atrialFibrillation = 1;
}
else if (AfibStr.equalsIgnoreCase("NO")){
atrialFibrillation = 0;
}
// Toast.makeText(adapterView.getContext(),
AfibStr,Toast.LENGTH_SHORT);
break;
case R.id.HBPSpinSelect:
String HBPstr = (String) adapterView.getSelectedItem();
if (HBPstr.equalsIgnoreCase("YES")){
hypertension = 1;
}
else if (HBPstr.equalsIgnoreCase("NO")){
hypertension = 0;
}
//Toast.makeText(adapterView.getContext(),
HBPstring,Toast.LENGTH_SHORT);
break;
case R.id.familialCVDSpin:
String famCVDStr = (String) adapterView.getSelectedItem();
if (famCVDStr.equalsIgnoreCase("YES")){
familialCVD = 1;
}
else if (famCVDStr.equalsIgnoreCase("NO")){
familialCVD = 0;
}
//Toast.makeText(adapterView.getContext(),
famCVDString,Toast.LENGTH_SHORT);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
Here is the class used to output the result:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_lin_risk);
TextView RiskViewLinRisk = findViewById(R.id.RiskViewLinRisk);
float LinRisk = (float) ((-16.13) + (0.119 * age) - (1.333 * sex)
+ (1.502 * married) + (2.619 * smoker) - (0.555 * (tcVal /
hdlVal)) + (0.026 *ldlVal) + (1.952 * highCholesterol) + (2.867
* atrialFibrillation) + (4.272 * hypertension) + (1.957 *
familialCVD));
String LinRiskStr = Float.toString(LinRisk);
RiskViewLinRisk.setText(LinRiskStr);
}
Just to give a bit more context than in the comments, double division in Java can return a NaN which stands for "not a number". This happens when you divide 0.0 by 0.0, but can also happen if you take the square root of a negative number.
Because Java implements the IEEE standard for NaN, it guarantees that NaN is never equal to itself. In fact, the only comparison that returns true is NaN != NaN. There's a very famous puzzle:
float x = //...
if (x != x)
System.out.println("Foo");
The question is "initialize x to a value which guarantees that Foo is printed". The answer is Float.NaN, because NaN is not equal to itself. Also, this is the only value that could work. All other values in Java would not solve this puzzle.
For this reason, a solution used lots of times to identify if a number is NaN is:
public boolean isNan(float x) {
return x != x;
}
(Since Java 8 a method exists in the standard lib to verify if a number is NaN)
You could use this to check the result of the division you're doing and avoid displaying NaN when you don't want to.
To display the values after you click on the button you have to run again the calculation and display it. I recommend extracting it into a method:
public float calculateLinRisk() {
return (float) ((-16.13) + (0.119 * age) - (1.333 * sex)
+ (1.502 * married) + (2.619 * smoker) - (0.555 * (tcVal /
hdlVal)) + (0.026 *ldlVal) + (1.952 * highCholesterol) + (2.867
* atrialFibrillation) + (4.272 * hypertension) + (1.957 *
familialCVD));
}
public void displayCurrentLinRisk() {
// This can also be a field in the main activity to
// avoid multiple calls to findViewById
TextView RiskViewLinRisk = findViewById(R.id.RiskViewLinRisk);
float LinRisk = calculateLinRisk()
String LinRiskStr = Float.toString(LinRisk);
RiskViewLinRisk.setText(LinRiskStr);
}
onCreate becomes:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_lin_risk);
displayCurrentLinRisk();
}
Then you can use this at the end of click listener
BtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ...
displayCurrentLinRisk();
}
}

Cart Count increment & decrement while clicking button

I populates cart items into the list using cursor adapter. My ListView item has
Price TextView
Product Name TextView
Count TextView
Increment Button
Decrement Buttton
When I click the increment / decrement button the value is incremented/ decremented in a certain condition of AFTER TOUCHING THE LISTVIEW ROW,otherwise the count is not changed.
In some case, if I click the 1st row increment button ,item count is incremented in 2nd row.
NOTE:
1. I am populating List using Cursor Adapter.
2. Using Increment & Decrement clicklistener in activity class.
Here is my code:
cartList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, View itemView, final int position, final long rowId) {
txt_cartProduct = (TextView) itemView.findViewById(R.id.cartProduct);
txt_cartQuantity = (TextView) itemView.findViewById(R.id.cartQuantity);
txt_cartPrice = (TextView) itemView.findViewById(R.id.cartPrice);
txt_cartPriceDum = (TextView) itemView.findViewById(R.id.cartPriceDum);
txt_cartCount = (TextView) itemView.findViewById(R.id.cartCount);
img_ivDecrease = (ImageView) itemView.findViewById(R.id.ivDecrease);
img_ivIncrease = (ImageView) itemView.findViewById(R.id.ivIncrease);
but_addTowish = (Button) itemView.findViewById(R.id.addTowish);
but_remove = (Button) itemView.findViewById(R.id.remove);
img_ivIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter++;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum += price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
netAmount = sum;
Log.e("Sum is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
int count_check = 1;
if (count_check >= position) {
count_check++;
} else if (count_check == 0) {
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
}
}
});
img_ivDecrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter--;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum -= price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
Log.e("Sum - is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
}
}
}
});
}
});
You can use setTag() and getTag() methods for saving the counter value in each list item.
Refer this answer for more details.

two array dimensional ArrayIndexOutOfBoundException and NullPointerException

i wrote a code for calculating some weights. they are integer weights.
and i need to save them in every time the button is clicked.
please help me. i cant see why the compiler gives me an error when i try to push the button for the second time. here is my complete code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the exception it throws:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
UPDATEEEEEEEE
i fixed the problem with arrayindexoutofboundexception by changing W[2][] to W[20][]. but in some clicks it gives me this error:
java.lang.NullPointerException
and it's not clear in which clicks. sometimes it's in the second click. or some times it's in fourth click. please help.
W[clicks] = W[clicks - 1];
in above line, you have get error because you have only define size of the array
int W[][] = new int[2][];
so it assigned W[0][] and W[1][] only
When click on second time variable clicks value is 2 then compiler gives ArrayIndexOutOfBoundException
EDITED.............................................................
you have got null value because of your bad logic and not proper way to build two dimensional array. Pls use debug tool to find the actual problem to implement logic and use two dimensional array like below example in java or android:
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row1 = new ArrayList<Integer>(1);
row1.add(2);
triangle.add(row1);
List<Integer> row2 = new ArrayList<Integer>(2);
row2.add(3);row2.add(4);
triangle.add(row2);
triangle.add(Arrays.asList(6,5,7));
triangle.add(Arrays.asList(4,1,8,3));
System.out.println("Size = "+ triangle.size());
for (int i=0; i<triangle.size();i++)
System.out.println(triangle.get(i));

My code throws ArrayIndexOutOfBoundException but i think it's ok

here is my code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.

Android: If/Else statement makes app crash

I'm trying to tell if an android int is null by using If/Else
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
res.setText(String.valueOf(f));
There are no any errors, but when I'm running the app its crashing when im pressing the button.
I'm also trying to use null instead of "":
if (minString.equals(null))
{
// Do Nothing
}
if (maxString.equals(null))
{
// Do Nothing
}
And i have a crash.
Please help me!!!
public boolean equals (Object object)
Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
So its returning error so if you want to check if its null then use == operator on the object.
if (maxString == null )
Use
int myMin = 0;
int myMax = 0;
if(min.getText().toString()!="")
myMin = Integer.parseInt(min.getText().toString());
if(max.getText().toString()!="")
myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
do if (maxString == null )
{
// do something
}
int variables can't be null
If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE)
So if you convert int to string again you cannot get null value.
check = input.getText().toString();
try {
if (!check.equals("null")) {
int max = Integer.parseInt(input.getText().toString());
int constant1 = 1;
int constant2 = 1;
int nextNumber = 0;
int count = 0;
String fibResult = "";
for (int i = 0; i <= max; i++) {
fibResult += "F" + count + "=" + nextNumber + "\n";
constant1 = constant2;
constant2 = nextNumber;
nextNumber = constant1 + constant2;
count++;
}
dspResults.setText("\n" + fibResult);
} else {
dspResults.setVisibility(View.VISIBLE);
dspResults.setText("Invalid");
dspResults.setText(Gravity.CENTER);
dspResults.setTextColor(Color.DKGRAY);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
{
if (minString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else if (maxString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else
res.setText(String.valueOf(f));
return true ;
}

Categories

Resources