OK this is driving me nuts. I was hoping to learn how to do this by today.
Here is what I have. This is a Multi choice ListView obviously.
You click the the Selection it selects, you unclick the selection it de selects.
It ALMOST works perfectly. There is only one problem. It only works when 1 item is already selected. If an item is selected, Items can be selected and de selected NP. But if nothing is selected, the last one stays selected. How to I fix that?
public void onItemClick(AdapterView<?> adapterView, View view, int Position, long l) {
int cntChoice = listview.getCount();
SparseBooleanArray sparseBooleanArray = listview.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if(sparseBooleanArray.get(i)) {
switch (Position) {
case 0:
if (listview.isItemChecked(0)) {
A = "";
A = "T";
} else if (!listview.isItemChecked(0)) {A = ""; A = "F";}
break;
case 1:
if (listview.isItemChecked(1)) {
B = "";
B = "T";
} else (listview.isItemChecked(1)) {B = ""; B = "F";}
break;
case 2:
if (listview.isItemChecked(2)) {
C = "";
C = "T";
} else (listview.isItemChecked(2)) {C = ""; C = "F";}
break;
}
Toast.makeText(Billing.this, "data" + A + ", " + B + ", " + C, Toast.LENGTH_LONG).show();
}
Related
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.
I am making an android app that asks for the users to select a country via spinner.
When the user opens the app first time, user selects a country from list.
Then when app opens second time, I want the same country to be selected. I don't want user to select the country every time the app is opened.
How to do that?
You can use SharedPreferences to store the selection the first time that the user selects a country, and then use SharedPreferences again for the app to remember the selection, when the user returns a second time.
To store the selection in a SharedPrefence:
SharedPreferences.Editor editor = getPreferences(0).edit();
int selectedPosition = yourSpinner.getSelectedItemPosition();
editor.putInt("spinnerSelection", selectedPosition);
editor.apply();
To load the selection onto the spinner when reusing the app:
SharedPreferences prefs = getPreferences(0);
yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
Hope this solves your issue :)
Try this one
String citySelected
final CharSequence[] items = {" abc ", " def ", " ghi ", " jkl ", " mno ",
" pqr ", " stu ",
" vwzyz "};
List<String> lanSelected = new ArrayList<>();
final boolean[] checkedItems = new boolean[]{false, false, false, false, false, false, false, false};
List<String> temp = new ArrayList<>();
for (int o = 0; o < items.length; o++) {
temp.add(items[o].toString());
}
final List<Integer> seletedItems = new ArrayList();
if (citySelected.equals("") || citySelected == null) {
} else
lanSelected = Arrays.asList(citySelected.split(","));
if (lanSelected.size() > 0) {
for (int p = 0; p < lanSelected.size(); p++) {
String x = lanSelected.get(p);
int xpos = temp.indexOf(x);
if (xpos != -1) {
checkedItems[xpos] = true;
seletedItems.add(xpos);
}
}
}
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(context);
}
// arraylist to keep the selected items
AlertDialog dialog = builder
.setTitle("city")
.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
seletedItems.add(indexSelected);
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array, remove it
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String city = "";
for (int i = 0; i < seletedItems.size(); i++) {
if (i == seletedItems.size() - 1) {
city = city + items[Integer.parseInt(seletedItems.get(i).toString())];
} else {
city = city + items[Integer.parseInt(seletedItems.get(i).toString())] + ",";
}
}
btn_city_todisplay.setText(city);
dialog.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on Cancel
}
}).create();
dialog.show();
Use spinner method to show selected item
spinner.setSelection(position);
Here position is the last selected position
You can use sharedPreference to store the country you have chosen, then search the map and find the position of country in your array, finally use setSelection(int position)to set the default country
I want to add data in ArrayList "arr" according to the checkedId of the radio group.I have 4 radio buttons "a0,a1,a2,a3". So if I chose a1,the array list should add the value of rb2. And after selecting a1 if I select a2 then the previous value in "arr" should get updated (not get added after the first one) and so on.Any help..
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i <= mcq.size(); i++) {
switch (checkedId) {
case R.id.a0:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb1.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a1:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb2.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a2:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb3.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a3:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb4.getText(), Toast.LENGTH_SHORT).show();
break;
}
arr.add(String.valueOf(checkedId));
Log.e("", String.valueOf(arr));
}
}
});
You can use https://developer.android.com/reference/android/util/SparseArray.html
SparaseArray<Boolean> array = new SparseArray();
array.put(checkedId, rb.isChecked());
Then you can get all the checked elements of the array like this:
for(int i = 0; i< sparseArray.size(); i++) {
int id = sparseArray.keyAt(i);
Boolean isChecked = sparseArray.get(id);
if(isChecked) {
log("Identifier " + id + " is checked");
}
}
I got ListView with simpleAdapter. If I click on some item in my List view it show me 2 diferent variables.
Some code:
// Listview Data
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(Invoice_numberArr.length);
Map<String, Object> m;
for(int i = 0; i<Invoice_numberArr.length; i++){
int str = Integer.parseInt(Invoice_numberArr[i]);
int str2 = Integer.parseInt(InvoiceNumberForDetails);
if(str == str2){
m = new HashMap<String, Object>();
m.put(ATT_INU, Invoice_numberArr[i]);
m.put(ATT_ANU, Article_numberArr[i]);
m.put(ATT_AMO, AmountArr[i]);
m.put(ATT_PRE, PriceArr[i]);
m.put(ATT_TPR, Total_priceArr[i]);
m.put(ATT_SDE, Sale_designationArr[i]);
data.add(m);
}
}
String[] from = {ATT_INU, ATT_ANU, ATT_AMO, ATT_PRE, ATT_TPR, ATT_SDE};
int[] till = {R.id.txtInvoice_number, R.id.txtArticle_number, R.id.txtAmount, R.id.txtPrice, R.id.txtTotalPrice, R.id.txtSale_designation};
//activities elements
invoices_list_details_view = (ListView)findViewById(R.id.invoices_list_details_view);
invoicesDetailsSAdapter = new SimpleAdapter(InvoicesDetails.this, data, R.layout.invoices_list_item_details_view, from , till);
invoices_list_details_view.setAdapter(invoicesDetailsSAdapter);
Utility Utility = new Utility();
Utility.setListViewHeightBasedOnChildren(invoices_list_details_view);
//if item clicked
invoices_list_details_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String positions = parent.getAdapter().getItem(position).toString();
//int positions = parent.getAdapter().;
parent.getAdapter();
int indexPos = -1; // if doesnt exist
for (int i = 0; i < Invoice_numberArr.length; i++) {
if (positions.contains("article_numbers="+Article_numberArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"amounts="+AmountArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"prices="+PriceArr[i]+", "+"total_prices="+Total_priceArr[i])) {
indexPos = i;
break;
} else if (positions.contains("prices="+PriceArr[i]+", "+"article_numbers="+Article_numberArr[i]+", "+"amounts="+AmountArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"total_prices="+Total_priceArr[i])){
indexPos = i;
break;
}
}
//some int to transfer it to position class
int integerr = indexPos;
Intent invoices_details_position = new Intent(InvoicesDetails.this, InvoicesDetailsPosition.class);
invoices_details_position.putExtra("saleDesignationForPosition", Sale_designationArr[indexPos]);
invoices_details_position.putExtra("articleNumberForPosition", Article_numberArr[indexPos]);
invoices_details_position.putExtra("sequenceNumberForPosition", Sequence_numberArr[indexPos]);
invoices_details_position.putExtra("amountForPosition", AmountArr[indexPos]);
invoices_details_position.putExtra("warehouseForPosition", WarehouseArr[indexPos]);
invoices_details_position.putExtra("containerDescriptionForPosition", Container_descriptionArr[indexPos]);
invoices_details_position.putExtra("priceForPosition", PriceArr[indexPos]);
invoices_details_position.putExtra("discountForPosition", DiscountArr[indexPos]);
invoices_details_position.putExtra("totalPriceForPosition", Total_priceArr[indexPos]);
startActivity(invoices_details_position);
}
});
So if clicked on my item from ListView under android 4.3 till 5.0 varible
String positions = parent.getAdapter().getItem(position).toString();
shows me
string " {prices=10.8, article_numbers=0736, amounts=1, sale_designations=Pfirsichlikör, invoice_numbers=1, total_prices=10.8} "
And if I clicked under Android version 5.1 its shows me
string " {article_numbers=0736, sale_designations=Pfirsichlikör, amounts=1, invoice_numbers=1, prices=10.8, total_prices=10.8} "
Because that I need to check it twice with that
for (int i = 0; i < Invoice_numberArr.length; i++) {
if (positions.contains("article_numbers="+Article_numberArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"amounts="+AmountArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"prices="+PriceArr[i]+", "+"total_prices="+Total_priceArr[i])) {
indexPos = i;
break;
} else if (positions.contains("prices="+PriceArr[i]+", "+"article_numbers="+Article_numberArr[i]+", "+"amounts="+AmountArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"total_prices="+Total_priceArr[i])){
indexPos = i;
break;
}
}
So my question now why does it changes depending on Android version ?
Thx for help.
Thank #Mike M. LinkedHashMap s instead HashMap s works for all Android
I have a dynamic listview with one text and one checkbox per line.when i click a button.,i need to get all checked item names & Unchecked item names separately as arraylilst.How could i do that.Examples are much better..
I used..
SparseBooleanArray checked = mainlw.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i) == true) {
Planet tag = (Planet) mainlw.getItemAtPosition(checked.keyAt(i));
String selectedName=tag.getName();
Toast.makeText(getApplicationContext(), selectedName, Toast.LENGTH_SHORT).show();
}
}
Try this out and implement this logic according to your requirement.
int cntChoice = myList.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i) == true)
{
checked += myList.getItemAtPosition(i).toString() + "\n";
}
else if(sparseBooleanArray.get(i) == false)
{
unchecked+= myList.getItemAtPosition(i).toString() + "\n";
}
}
use CHOICE_MODE_MULTIPLE in your ListView and use getCheckedItemPositions() to get the checked ones.
So Onclick of button u can do this,From this you will get the items that are checked:-
#Override
public void onClick(View v)
{
System.out.println("check"+getListView().getCheckItemIds().length);
for (int i = 0; i < getListView().getCheckItemIds().length; i++)
{
System.out.println(getListView().getAdapter().getItem((int)getListView().getCheckItemIds()[i]).toString());
}
}