My code throws ArrayIndexOutOfBoundException but i think it's ok - android

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.

Related

Getting incorrect id for child item click

I am getting incorrect id for child item click.
Fragment Class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View itemView = inflater.inflate(R.layout.fragment_checklist_groups_description, container, false);
fragmentManager = getActivity().getSupportFragmentManager();
mLinearListView = (LinearLayout) itemView.findViewById(R.id.linear_ListView);
//=========================================================================
for (int i = 0; i < 2; i++) {
V_ChecklistParentItemModel v_checklistParentItemModel = new V_ChecklistParentItemModel();
v_checklistParentItemModel.setParentGroupID("" + (i + 1));
v_checklistParentItemModel.setParentGroupName("Group Name " + i);
if (i == 0) {
v_checklistParentItemModel.setHasSubGroup(false);
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int j = 0; j < 3; j++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (j + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (j + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistParentItemModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
} else {
v_checklistParentItemModel.setHasSubGroup(true);
ArrayList<V_ChecklistSubGroupModel> tempV_checklistSubGroupModelArrayList = new ArrayList<>();
for (int j = 0; j < 2; j++) {
V_ChecklistSubGroupModel v_checklistSubGroupModel = new V_ChecklistSubGroupModel();
v_checklistSubGroupModel.setSubGroupID("" + (j + 1));
if (j == 0) {
v_checklistSubGroupModel.setSubGroupName("Sub Group Name 2a");
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int k = 0; k < 2; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistSubGroupModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
} else {
v_checklistSubGroupModel.setSubGroupName("Sub Group Name 2b");
ArrayList<V_ChecklistChildItemModel> tempV_checklistChildItemModelArrayList = new ArrayList<>();
for (int k = 0; k < 3; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
tempV_checklistChildItemModelArrayList.add(v_checklistChildItemModel);
}
v_checklistSubGroupModel.setV_checklistChildItemModelArrayList(tempV_checklistChildItemModelArrayList);
}
tempV_checklistSubGroupModelArrayList.add(v_checklistSubGroupModel);
}
v_checklistParentItemModel.setV_checklistSubGroupModelArrayList(tempV_checklistSubGroupModelArrayList);
}
v_checklistParentItemModelArrayList.add(v_checklistParentItemModel);
}
//=========================================================================
//Adds data into first row
for (int i = 0; i < v_checklistParentItemModelArrayList.size(); i++) {
Log.v("I : ", " " + i);
LayoutInflater listInflater = null;
listInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = listInflater.inflate(R.layout.custom_cardview_checklist_groups_description_main_parent_item, null);
final TextView mProductName = (TextView) mLinearView.findViewById(R.id.textViewName);
final RelativeLayout mImageArrowFirst = (RelativeLayout) mLinearView.findViewById(R.id.rlFirstArrow);
final LinearLayout mLinearScrollSecond = (LinearLayout) mLinearView.findViewById(R.id.linear_scroll);
//checkes if menu is already opened or not
if (isFirstViewClick == false) {
mLinearScrollSecond.setVisibility(View.GONE);
mImageArrowFirst.setBackgroundResource(R.drawable.next_disable_icon);
} else {
mLinearScrollSecond.setVisibility(View.VISIBLE);
mImageArrowFirst.setBackgroundResource(R.drawable.arw_down);
}
//Handles onclick effect on list item
mImageArrowFirst.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isFirstViewClick == false) {
isFirstViewClick = true;
mImageArrowFirst.setBackgroundResource(R.drawable.arw_down);
mLinearScrollSecond.setVisibility(View.VISIBLE);
} else {
isFirstViewClick = false;
mImageArrowFirst.setBackgroundResource(R.drawable.next_disable_icon);
mLinearScrollSecond.setVisibility(View.GONE);
}
return false;
}
});
final String name = v_checklistParentItemModelArrayList.get(i).getParentGroupName();
mProductName.setText(name);
if (v_checklistParentItemModelArrayList.get(i).isHasSubGroup()) {
//Adds data into second row
for (int j = 0; j < v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().size(); j++) {
Log.v("J : ", " " + j);
LayoutInflater inflater2 = null;
inflater2 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView2 = inflater2.inflate(R.layout.custom_cardview_checklist_groups_description_child_parent_item, null);
TextView mSubItemName = (TextView) mLinearView2.findViewById(R.id.textViewTitle);
final RelativeLayout mLinearSecondArrow = (RelativeLayout) mLinearView2.findViewById(R.id.linearSecond);
final RelativeLayout mImageArrowSecond = (RelativeLayout) mLinearView2.findViewById(R.id.rlSecondArrow);
final LinearLayout mLinearScrollThird = (LinearLayout) mLinearView2.findViewById(R.id.linear_scroll_third);
final LinearLayout linearLayoutMain = (LinearLayout) mLinearView2.findViewById(R.id.llMain);
if (i == 0) {
mLinearSecondArrow.setBackgroundColor(getResources().getColor(R.color.main_parent));
mImageArrowSecond.setVisibility(View.GONE);
linearLayoutMain.setPadding(20, 0, 0, 0);
} else {
mLinearSecondArrow.setBackgroundColor(getResources().getColor(R.color.child_parent));
mImageArrowSecond.setVisibility(View.VISIBLE);
if (i == 1) {
linearLayoutMain.setPadding(20, 8, 0, 0);
} else {
linearLayoutMain.setPadding(15, 8, 0, 0);
}
}
//checkes if menu is already opened or not
if (isSecondViewClick == false) {
mLinearScrollThird.setVisibility(View.GONE);
mImageArrowSecond.setBackgroundResource(R.drawable.next_disable_icon);
} else {
mLinearScrollThird.setVisibility(View.VISIBLE);
mImageArrowSecond.setBackgroundResource(R.drawable.arw_down);
}
//Handles onclick effect on list item
if (i == 0) {
final int finalI1 = i;
final int finalJ1 = j;
mLinearSecondArrow.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI1).getParentGroupName());
bundle.putInt("itemCount", 3);
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
pageNumber = 0;
bundle.putInt("pageNumber", pageNumber);
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.sd_project_list_screen_name));
return false;
}
});
} else {
mImageArrowSecond.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isSecondViewClick == false) {
isSecondViewClick = true;
mImageArrowSecond.setBackgroundResource(R.drawable.arw_down);
mLinearScrollThird.setVisibility(View.VISIBLE);
} else {
isSecondViewClick = false;
mImageArrowSecond.setBackgroundResource(R.drawable.next_disable_icon);
mLinearScrollThird.setVisibility(View.GONE);
}
return false;
}
});
}
final String catName = v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getSubGroupName();
mSubItemName.setText(catName);
//Adds items in subcategories
for (int k = 0; k < v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getV_checklistChildItemModelArrayList().size(); k++) {
Log.v("K : ", " " + k);
LayoutInflater inflater3 = null;
inflater3 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView3 = inflater3.inflate(R.layout.custom_cardview_checklist_groups_description_child_item, null);
TextView mItemName = (TextView) mLinearView3.findViewById(R.id.textViewItemName);
final String itemName = v_checklistParentItemModelArrayList.get(i).getV_checklistSubGroupModelArrayList().get(j).getV_checklistChildItemModelArrayList().get(k).getChildItemQuestionName();
mItemName.setText(itemName);
mLinearScrollThird.addView(mLinearView3);
final int finalI = i;
final int finalJ = j;
final int finalK = k;
mLinearScrollThird.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI).getParentGroupName());
bundle.putInt("itemCount", v_checklistParentItemModelArrayList.get(finalI).getV_checklistSubGroupModelArrayList().get(finalJ).getV_checklistChildItemModelArrayList().size());
// bundle.putSerializable("questionData", group2bQuestionList);
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
pageNumber = finalI + finalJ + finalK + 1;
bundle.putInt("pageNumber", pageNumber);
Log.v("====ugugugu==", "===ijhbjhbjh===");
Toast.makeText(getActivity(), "Page No. " + v_checklistParentItemModelArrayList.get(finalI).getV_checklistSubGroupModelArrayList().get(finalJ).getV_checklistChildItemModelArrayList().get(finalK).getChildQuestionID(), Toast.LENGTH_LONG).show();
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.check_list_groups_question_screen_name));
return false;
}
});
}
mLinearScrollSecond.addView(mLinearView2);
}
mLinearListView.addView(mLinearView);
} else {
//Adds items in subcategories
for (int k = 0; k < v_checklistParentItemModelArrayList.get(i).getV_checklistChildItemModelArrayList().size(); k++) {
Log.v("K : ", " " + k);
LayoutInflater inflater3 = null;
inflater3 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView3 = inflater3.inflate(R.layout.custom_cardview_checklist_groups_description_child_item, null);
final LinearLayout mLinearScrollThird = (LinearLayout) mLinearView3.findViewById(R.id.linear_scroll_third);
TextView mItemName = (TextView) mLinearView3.findViewById(R.id.textViewItemName);
final String itemName = v_checklistParentItemModelArrayList.get(i).getV_checklistChildItemModelArrayList().get(k).getChildItemQuestionName();
mItemName.setText(itemName);
final int finalI = i;
final int finalK = k;
mLinearScrollThird.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Bundle bundle = new Bundle();
bundle.putString("groupName", v_checklistParentItemModelArrayList.get(finalI).getParentGroupName());
bundle.putInt("itemCount", v_checklistParentItemModelArrayList.get(finalI).getV_checklistChildItemModelArrayList().size());
bundle.putSerializable("alldata", checklist_groupNamePojoArrayList);
bundle.putInt("pageNumber", 1);
Toast.makeText(getActivity(), "Page No. " + v_checklistParentItemModelArrayList.get(finalI).getV_checklistChildItemModelArrayList().get(finalK).getChildQuestionID(), Toast.LENGTH_LONG).show();
ChecklistGroupsQuestionsMainDialogFragment checklistGroupsQuestionsMainDialogFragment = new ChecklistGroupsQuestionsMainDialogFragment();
checklistGroupsQuestionsMainDialogFragment.setArguments(bundle);
checklistGroupsQuestionsMainDialogFragment.setTargetFragment(current, 101);
checklistGroupsQuestionsMainDialogFragment.show(fragmentManager, getResources().getString(R.string.check_list_groups_question_screen_name));
return false;
}
});
mLinearScrollSecond.addView(mLinearView3);
}
mLinearListView.addView(mLinearView);
}
}
//==============================================================================
return itemView;
}
I have assigned Child Question ID using setChildQuestionID(). For Group Name 0, I get 0, 1, 2 on each child click. However, for Group Name 1, I get 4 for Sub Group Name 2a & 7 for Sub Group Name 2b for each of there child item click. Ideally, it should return whatever I set for them.
Do you mean that you want to get 0, 1, 2 for child clicks in group name 1? As far as I can tell, you're going to have to re-set the value of index to 0 to get that. At least, assuming you've defined index = 0 somewhere outside your outermost for-loop (I can't see where in your code you've set the value of index). Right now in Group 0, you have:
for (int k = 0; k < 2; k++) {
V_ChecklistChildItemModel v_checklistChildItemModel = new V_ChecklistChildItemModel();
v_checklistChildItemModel.setChildItemQuestionID("" + (k + 1));
v_checklistChildItemModel.setChildItemQuestionName("Description of Question " + (k + 1));
v_checklistChildItemModel.setChildQuestionID("" + index);
index++;
If index was 0 to start with, the value of index is now greater than 0. You don't set it back to 0, so when you get to the next cycle through your top-level for loop, the value of index is already > 0. If you want to start over at index = 0 in Group 1, you'll have to set the value of index back to 0.
In other words, you are returning exactly what you set for the questionIDs, but I think you're setting a number that you didn't want to set.

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));

The method notifyDataSetChanged() not working in custom Listview

I custom listview with adapter extend BaseAdapter.
In method getView I have a button Add, and I set listener to it
item.btnAddBasket.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showChooseSize(products.get(pos), pos);
DialogFragmentCustom.setPosition(pos);
}
});
And I have two method, which are call when I press button Add.
public void showChooseSize(ProductInfo productInfo, int pos) {
ArrayList<Stock> stocks = new ArrayList<Stock>();
stocks.addAll(productInfo.getStock());
ArrayList<String> colors = new ArrayList<String>();
ArrayList<String> sizes = new ArrayList<String>();
if (stocks != null && stocks.size() > 0) {
for (int i = 0; i < stocks.size() - 1; i++) {
colors.add(stocks.get(i).getColorName());
sizes.add(stocks.get(i).getSize());
}
}
if (sizes != null && sizes.size() > 0) {
HashSet<String> hs_size = new HashSet<String>(); // remove elements
// duplicate
hs_size.addAll(sizes);
sizes.clear();
sizes.addAll(hs_size);
if (sizes.size() == 1) {
size = sizes.get(0);
} else {
for (int j = 0; j < sizes.size() - 1; j++) {
size = size + sizes.get(j) + ", ";
}
size = size + sizes.get(sizes.size() - 1);
}
a_sizes = null;
if (size.split(",") != null) {
a_sizes = size.split(",");
}
if (a_sizes == null) {
a_sizes[0] = "This product do not have size";
}
if (a_sizes != null && a_sizes.length > 0) {
Config.isWishList = true;
((Activity) context).setTheme(R.style.ActionSheetStyleIOS7);
ActionSheetChooseSize.setProductInfo(productInfo);
ActionSheetChooseSize.createBuilder(context, ((FragmentActivity) context).getSupportFragmentManager()).setOtherButtonTitles(a_sizes)
.setCancelableOnTouchOutside(true).setListener(this).show();
isShowChooseSize = true;
} else {
addToBag(productInfo, pos);
}
}
Method add product into Bag when press button Add, it inside my adapter
public void addToBag(ProductInfo productInfo, int pos) {
// Config.productSaleInfos.add(products.get(pos));
Config.productSaleInfos.add(productInfo);
Config.numProductSale = Config.productSaleInfos.size();
Config.numProductWishlist = Config.numProductWishlist - 1 < 0 ? Config.numProductWishlist - 1 : 0;
//SlideMenuFragment.setNumWish(Config.numProductWishlist + "");
new DeletionItemWishlist(context).execute(products.get(pos));
products.remove(pos);
notifyDataSetChanged();
float sumaryPrice = 0;
for (int i = 0; i < products.size(); i++) {
String price = products.get(i).getSalePrice();
int index = price.indexOf(",");
if (index > -1) {
price = price.replace(",", "");
}
float p = Functions.getFloatFromString(price);
sumaryPrice = sumaryPrice + p;
}
basket.setText(Config.numProductSale + "");
subtotal.setText(Html.fromHtml("<b>Subtotal: </b>" + "<font color=\"#FF7F00\">" + sumaryPrice + " ฿</font>"));
Functions.showLog(context, "add bag success!");
}
But notifyDataSetChanged(); is not working in my code. Can you help me please?

Android array error

This is my code:
public ArrayList generare_diferente(){
int rezultat;
ArrayList<String> termeni= new ArrayList<String>();
int termA=parseInt(String.valueOf(randomBetween(1, 20)));
int termB=parseInt(String.valueOf(randomBetween(1, 20)));
if(termA<termB){
int aux; aux=termA; termA=termB; termB=aux;
rezultat=termA-termB;
String diff = termA + "-" + termB;
termeni.add(String.valueOf(rezultat));
termeni.add(diff);
Log.v("termeeeeni", String.valueOf(termeni));
}
return termeni;
}
public void generare_3_diferente() {
ArrayList<String> scaderea1 = new ArrayList<String>();
ArrayList<String> scaderea2 = new ArrayList<String>();
ArrayList<String> scaderea3 = new ArrayList<String>();
int raspuns_corect;
int[] raspunsuri = new int[]{0, 0, 0, 0};
int i = 0;
do {
scaderea1 = generare_diferente();
scaderea2 = generare_diferente();
scaderea3 = generare_diferente();
Button scadere1 = (Button) findViewById(R.id.scadere1);
Button scadere2 = (Button) findViewById(R.id.scadere2);
Button scadere3 = (Button) findViewById(R.id.scadere3);
scadere1.setText((CharSequence) scaderea1.get(1));
scadere2.setText((CharSequence) scaderea2.get(1));
scadere3.setText((CharSequence) scaderea3.get(1));
}
while (scaderea1.get(0) == scaderea2.get(0) || scaderea2.get(0) == scaderea3.get(0) || scaderea3.get(0) == scaderea1.get(0));
raspunsuri[1]= Integer.parseInt(scaderea1.get(0));
raspunsuri[2]= Integer.parseInt(scaderea2.get(0));
raspunsuri[3]= Integer.parseInt(scaderea3.get(0));
pozitia_corecta = parseInt(String.valueOf(randomBetween(1, 3)));
raspuns_corect = raspunsuri[pozitia_corecta];
TextView rezultat = (TextView) findViewById(R.id.Rezultat);
rezultat.setText(raspuns_corect);
}
I'm getting this error:
java.lang.RuntimeException: Unable to start activity : java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.pinguin.MyActivity.generare_3_diferente(MyActivity.java:93)
at .onCreate(MyActivity.java:24)
I don't understand why, the array should not have the size 0.
thank you!
your code seems wrong. because in generare_diferente() if termA<termB or equal you return empty array and then in generare_3_diferente() you try to read data from empty list.
first you should handle this issue.then I think your random number are not generate so termA and termB both is zero or anything and if statement are not true.
change code like this
public ArrayList generare_diferente(){
int rezultat;
ArrayList<String> termeni= new ArrayList<String>();
int termA=random.nextInt(max - min + 1) + min ;
int termB=random.nextInt(max - min + 1) + min ;
if(termA<termB){
int aux; aux=termA; termA=termB; termB=aux;
rezultat=termA-termB;
String diff = termA + "-" + termB;
termeni.add(String.valueOf(rezultat));
termeni.add(diff);
Log.v("termeeeeni", String.valueOf(termeni));
}
return termeni.clone();
}
public void generare_3_diferente() {
ArrayList<String> scaderea1 = new ArrayList<String>();
ArrayList<String> scaderea2 = new ArrayList<String>();
ArrayList<String> scaderea3 = new ArrayList<String>();
int raspuns_corect;
int[] raspunsuri = new int[]{0, 0, 0, 0};
int i = 0;
do {
scaderea1 = generare_diferente();
scaderea2 = generare_diferente();
scaderea3 = generare_diferente();
Button scadere1 = (Button) findViewById(R.id.scadere1);
Button scadere2 = (Button) findViewById(R.id.scadere2);
Button scadere3 = (Button) findViewById(R.id.scadere3);
if(scaderea1.size()>0 && scaderea2.size()>0 && scaderea3.size()>0){
scadere1.setText((CharSequence) scaderea1.get(1));
scadere2.setText((CharSequence) scaderea2.get(1));
scadere3.setText((CharSequence) scaderea3.get(1));
}else{
scadere1.setText("something");
scadere2.setText("something");
scadere3.setText("something");
break;
}
}
while (scaderea1.get(0) == scaderea2.get(0) || scaderea2.get(0) == scaderea3.get(0) || scaderea3.get(0) == scaderea1.get(0));
if(scaderea1.size()>0 && scaderea2.size()>0 && scaderea3.size()>0){
raspunsuri[1]= Integer.parseInt(scaderea1.get(0));
raspunsuri[2]= Integer.parseInt(scaderea2.get(0));
raspunsuri[3]= Integer.parseInt(scaderea3.get(0));
}else{
raspunsuri[1]= Integer.parseInt("0");
raspunsuri[2]= Integer.parseInt("0");
raspunsuri[3]= Integer.parseInt("0");
}
pozitia_corecta = parseInt(String.valueOf(randomBetween(1, 3)));
raspuns_corect = raspunsuri[pozitia_corecta];
TextView rezultat = (TextView) findViewById(R.id.Rezultat);
rezultat.setText(raspuns_corect);
}

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