Cart Count increment & decrement while clicking button - android

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.

Related

Spinner Value is not preserved for 2nd spinner onStart

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.

Using AlertDialog.Builder to build custom AlertDialog class

I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.

Cart item Count increment/decrement & Sum of cart price

I need to increment / decrement of cart product.Valuse are increased / decreased.But from here I need to get Total sum of my all cart product. Got some calculation mistakes.So please help me to fix it.
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;
}
}
}
});
}
});

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.

Displaying an array of values to buttons

I have an array of 12 values and I want to display it one after the other. Initially on application run I am displaying 6 values. On the button click I want to display the other 6 values one by one.
prevbutton-> value1 value2 value3 value4 value5 value6 -> nextbutton
So on next button click it should be like this.
prevbutton-> value2 value3 value4 value5 value6 value7 -> nextbutton
This should be continued up to the 12 values, and the reverse should happen in case of prevbutton.
I have used this code but it's not working:
public void onClick(View v) {
switch (v.getId()) {
case R.id.radionextstn:
forwardtune();
break;
}
}
public void forwardtune(){
Button[] buttons = new Button[5];
buttons[0] = (Button)findViewById(R.id.radiostation1);
buttons[1] = (Button)findViewById(R.id.radiostation2);
buttons[2] = (Button)findViewById(R.id.radiostation3);
buttons[3] = (Button)findViewById(R.id.radiostation4);
buttons[4] = (Button)findViewById(R.id.radiostation5);
buttons[5] = (Button)findViewById(R.id.radiostation6);
if(currentlyDisplayingFromPosition + 6 >= arraySize)
return;
for(int i=0; i<arraySize; i++) {
buttons[i].setText("");
}
for(int i=currentlyDisplayingFromPosition; i<=currentlyDisplayingFromPosition+6; i++){
if (frequency[i] == 0.0)
buttons[i].setText("");
else
buttons[i].setText("" + frequency[0]);
}
}
I am displaying the first 6 values like this:
public void autoTune() {
Log.i("autotune", " called");
if (frequency[0] == 0.0)
station1.setText(""); // station1 is a button
else
station1.setText("" + frequency[0]); // station1 is a button
if (frequency[1] == 0.0)
station2.setText(""); // station2 is a button
else
station2.setText("" + frequency[1]); // station2 is a button
if (frequency[2] == 0.0)
station3.setText(""); // station3 is a button
else
station3.setText("" + frequency[2]); // station3 is a button
if (frequency[3] == 0.0)
station4.setText(""); // station4 is a button
else
station4.setText("" + frequency[3]); // station4 is a button
if (frequency[4] == 0.0)
station5.setText(""); // station5 is a button
else
station5.setText("" + frequency[4]); // station5 is a button
if (frequency[5] == 0.0)
station6.setText(""); // station6 is a button
else
station6.setText("" + frequency[5]); // station6 is a button
}
#Override
protected Boolean doInBackground(Context... params) {
// TODO Auto-generated method stub
Log.i("in autotune", " before freq length");
int[] freq = { 911, 943, 947, 932, 901, 964, 843, 835, 946,904,908,873 };
freqCounter = 0;
Log.i("in autotune", "after freq length : " + freq.length);
frequency = new double[freq.length];
Log.i("in autotune", "after frequency length : " + frequency.length);
for (int k = 0; k < freq.length; k++) {
Log.i("In Radio.java", "Freq : " + freq[k]);
frequency[k] = freq[k];
frequency[k] = frequency[k] / 10;
if (frequency[k] == 0.0)
break;
freqCounter++;
Log.i("In Radio.java", "Frequency : " + frequency[k]);
}
}
first error I see, you declare an array of 5 button and try to put 6 buttons :
Button[] buttons = new Button[5];
you should do:
Button[] buttons = new Button[6];
solution :
if(currentlyDisplayingFromPosition + 6 >= arraySize)
return;
for(int i=0; i<6; i++){
buttons[i].setText("" + frequency[currentlyDisplayingFromPosition+i]);
}
Modify it as per your need.
Button[] btns = new Button[8];
List<String> pages = new ArrayList<String>();
int mStart = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog_activiy);
btns[0] = (Button) findViewById(R.id.pr);
btns[1] = (Button) findViewById(R.id.b1);
btns[2] = (Button) findViewById(R.id.b2);
btns[3] = (Button) findViewById(R.id.b3);
btns[4] = (Button) findViewById(R.id.b4);
btns[5] = (Button) findViewById(R.id.b5);
btns[6] = (Button) findViewById(R.id.b6);
btns[7] = (Button) findViewById(R.id.nt);
btns[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rearrangeBy(-1);
}
});
btns[btns.length - 1].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rearrangeBy(1);
}
});
// setup listeners
for (int i = 1; i < btns.length - 1; i++) {
btns[i].setOnClickListener(mClickListener);
}
for (int i = 0; i < 12; i++) {
pages.add((i + 1) + "");
}
setUpButtons();
}
final View.OnClickListener mClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DialogActiviy.this, v.getTag() + "",
Toast.LENGTH_SHORT).show();
}
};
private void rearrangeBy(int by) {
mStart += by;
setUpButtons();
}
private void setUpButtons() {
// setup previous button
btns[0].setEnabled(!(mStart == 1));
// setup next button
int end = pages.size() - btns.length + 2 + 1;
btns[btns.length - 1].setEnabled(!(mStart == end));
// setup intermediate buttons
for (int i = 1; i < btns.length - 1; i++) {
String text = (mStart + i - 1) + "";
btns[i].setText(text);
btns[i].setTag(text);
}
}

Categories

Resources