The error:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
at WeekView.getMoreEvents(WeekView.java:614)
In a class that extends View, I get a list of the id in this way:
public void setElencoIdOperatori(int[] id_nome_op){
this.id_nome_op = id_nome_op;
}
Then, with this method, I must compare id_nome_op with eventRect.event.getIdOperatore(). When are the same, I want to add the event to the array eventRects. Thanks for your help
private void getMoreEvents(Calendar day){
// Get more events if the month is changed.
if(mEventRects ==null)
mEventRects =newArrayList<EventRect>();
if(mMonthChangeListener ==null&&!isInEditMode())
thrownewIllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if(mRefreshEvents){
mEventRects.clear();
mFetchedMonths =newint[3];
}
...
// Get events of this month.
if(mFetchedMonths[1]<1||mFetchedMonths[1]!= day.get(Calendar.MONTH)+1||mRefreshEvents){
if(!containsValue(lastFetchedMonth,day.get(Calendar.MONTH)+1)&&!isInEditMode()){
List<WeekViewEvent> events =mMonthChangeListener.onMonthChange(day.get(Calendar.YEAR),day.get(Calendar.MONTH)+1);
sortEvents(events);
for(WeekViewEventevent: events){
cacheEvent(event);
}
}
mFetchedMonths[1]= day.get(Calendar.MONTH)+1;
}
...
// Prepare to calculate positions of each events.
ArrayList<EventRect> tempEvents =newArrayList<EventRect>(mEventRects);
mEventRects =newArrayList<EventRect>();
for(intj =1;j <=id_nome_op.length;){
ArrayList<EventRect> eventRects =newArrayList<EventRect>();
for(EventRect eventRect : tempEvents){
if(eventRect.event.getIdOperatore() == id_nome_op[j])
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
j++;
}
}
It's a bit hard understanding your code, but I think you might have a problem here:
for(int j =1;j <=id_nome_op.length;) {
ArrayList<EventRect> eventRects =newArrayList<EventRect>();
for(EventRect eventRect : tempEvents){
if(eventRect.event.getIdOperatore() == id_nome_op[j])
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
j++;
}
When you access id_nome_op[j].
Try changing the loop to:
j < id_nome_op.length
As #Mike M pointed out, you also need initalizing your outer loop to 0, as you want to get all the items in your array:
for(int j = 0; j < id_nome_op.length;)
Related
I have a function that 'crafts' products using two String parameters.
This is working fine when I put in hard coded strings like 'Wheel' & 'Car'.
But it makes my application crash if I try to put in the exact same strings but then provided by an intent.
I already tried to give in variable into the intent instead of a hard coded string. That did not work either.
Here is some part of the code. EDIT: Error log now included
productLeft = getIntent().getStringExtra("PRODUCT LEFT");
productRight = getIntent().getStringExtra("PRODUCT RIGHT");
public void craft(String product1, String product2) {
String[][] Products = factory.getProductList();
int i = 0;
while (finalProduct == "") {
int j;
for(j = 0; j < 3; j++){
if (product1 == Products[i][0] || product2 == Products[i][0]) {
if (product1 == Products[i][1] || product2 == Products[i][1]){
finalProduct = Products[i][2];
}
}
i++;
}
}
}
Problem is with the array index obviously. The array has only four elements and you are fetching index 4, probably in for loop with i variable. But then again I also do not see the role of j in that loop, can't tell without other parts of code.
I have a list of users, and I want to hide every user with admin role when show it in recycleview. Tried to use for method, but the app ended up crash. here is the code that I tried to use
public void setUserList(List<UserModel> userList) {
this.userList = userList;
//userList.remove(0);
for(int i=0;i<=userList.size();i++)
{
if(userList.get(i).getRole().equals("admin")) {
userList.remove(i);
}
}
//userList.removeIf(userModel -> userModel.getRole().matches("admin"));
notifyDataSetChanged();
}
For now, because the user with role admin always located at first index of array, I use userList.remove(0); but if any of you have better approach, I really apreciate it. Thank you.
Edit:
Get the answer, need to use access iterator directly.
Use Iterator
int position = 0;
Iterator<User> iter = list.iterator();
while (iter.hasNext()) {
if(iter.next().getRole().equals("admin")){
iter.remove()
}
position++
}
and in adapter
adapter.notifyItemRemoved(position)
Normal for loop should be used on collections for read only
You also need to update the Adapter. Use something like this:
for (int i = userList.size() - 1; i <= userList.size(); ++i) {
if(userList.get(i).getRole().equals("admin"))
userList.remove(i);
adapter.notifyItemRemoved(i)
}
if you getting error like this
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at beginner.HelloWorldApp.main(HelloWorldApp.java:18)
Then you can use an iterator to remove element by this way
for(Iterator<Model> iter = userList.iterator(); iter.hasNext(); ){
Model student = iter.next();
if(student.getName().equalsIgnoreCase("admin"){
iter.remove();
}
}
adapter.notifydatasetchange();
I am trying to create dynamic buttons. When clicking a button it should go to the specified url assigned to the text of the button.
For testing, first I tried to get that ID, if it is equal it prints the value of i. But whenever I clicked any one button, instead of telling that particular i value, it enters into whole loop, and prints all the values of i starting from 1 to 19 (the number of buttons that are dynamically created)
And after printing all values from 1 to 19, the program is getting force closed saying Null pointer exception.
I even tried by placing the handler code outside onCreate(), but I'm still getting the same error.
for ( i = 0; i <itemList.getTitle().size()-1; i++) {
title[i] = new TextView(this);
title[i].setTextColor( -16711936 );
title[i].setTextSize(18);
title[i].setText("Title = "+itemList.getTitle().get(i));
description[i] = new TextView(this);
description[i].setTextColor(-16776961);
description[i].setText("Description = "+itemList.getDescription().get(i)+"......");
more[i]=new Button(this);
more[i].setText(itemList.getLink().get(i));
layout.addView(title[i]);
System.out.println("Title view is set");
layout.addView(description[i]);
//System.out.println("Description view is set");
layout.addView(more[i]);
more[i].setOnClickListener(listener);
}
private OnClickListener listener=new OnClickListener(){
public void onClick(View arg) {
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
//System.out.println("Vlaue of I in onclick"+i);
//Uri uri=Uri.parse(itemList.getLink().get(i));
//startActivity(new Intent(Intent.ACTION_VIEW,uri));
//Toast.makeText(getApplicationContext(), "This button is clicked"+i+more[i].getText()+itemList.getLink().get(i),Toast.LENGTH_LONG).show();
}
}
You can use setTag() and getTag() method of View to identify different button.
for (i = 0; i < itemList.getTitle().size()-1; i++) {
...
more[i].setTag(i); // Use index of itemList as the tag
}
In onClick:
int index = (Integer)arg.getTag();
you can also set the id of button
more[i].setid(i);
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
As you can see here, i is still in your for loop.
Put the System.out.println("Value of i onclick is"+i); outside of your for loop and it should work
PS: format your code, it's easier to read that way and you'll notice small mistakes like these more easily
I think this will help you..
set button tag also dynamic like
more[i].setId(i);
and also changed condition like
if (more[i].getId() == i) {
index = i;
}
hope this will help you...
I like to make a game, but I get trouble with collecting points.
The purpose is to increase/decrease character point (charhop +1 or -1) whenever object 'face' is collided with injekBox, but the point just increase or decrease once then it return to the previous value.
The log also still print the value even if the object stop
I want to make the point change once if the 'face' collided with certain box, and will change again after collided with another box
char1.setHops(0);
public void onUpdate(final float pSecondsElapsed) {
if (char1.isJump()){
int rockPoint = char1.getPoints();
int maxBox = listBox.size();
int charHop = char1.getHops();
for (int j = 0; j < maxBox ; j++){
if (j == rockPoint){
j++;
}
Box injekBox = listBox.get(j);
if(injekBox.getRectangle().collidesWith(face)){
if(char1.isTurn()){
charHop++;
if (charHop == (maxBox - 1)){
char1.setTurn(false);
}
} else {
charHop--;
}
Log.i(this.toString(),"charHop: "+charHop);
injekBox.getRectangle().setColor(1, 0, 0);
} else {
injekBox.getRectangle().setColor(1, 1, 1);
}
}
}
}
Sorry for bad writing...
Thank you for attention :)
The scope of charHop is only within onUpdate. Once you leave that method, the contents of that variable is gone. You need the counterpart to char1.getHops()--something like char1.setHops(charHop);.
I have one simple_list_item_multiple_choice listview in my layout and i am trying to remove all the selected items from it. I know how to delete it but i am having two major problems while deleting the items :-
My program isn't deleting more than 2 items like if i selected 4 items then only 2 will be deleted and sometime its even deleting the wrong items.
When i debug my code i found Array IndexOutOfBoundException in my code and as far as i know there is no exception like this in my code and its all because of deleting the wrong or less items.
here is my code:-
public void onClick(View view)
{
SparseBooleanArray checkedPositions = new SparseBooleanArray();
checkedPositions.clear();
checkedPositions = lv.getCheckedItemPositions();
int size = checkedPositions.size();
if(size != 0)
{
try
{
for(int i = 0; i < size; i++)
{
if(checkedPositions.valueAt(i))
{
list.remove(checkedPositions.keyAt(i));
notes.notifyDataSetChanged();
lv.setItemChecked(i,false);
}
}}catch (IndexOutOfBoundsException ie)
{}
}
else{}
}
I caught the exception only for debugging purpose. Thanks in advance but please help because i am stuck at this part since last two days.
Each time you remove an item from the array at the lower lever, the total count is being reduced by 1. If you had 4 items to remove [ 0, 1, 2, 3], and you remove items starting with item 0, you have [0, 1, 2], then you remove item at 1, and you have [0, 1], if you try to remove item at index 2 which does not exist you will get an error. Try count down instead of up like this
for(int i = size; i > 0; --i)
{
if(checkedPositions.valueAt(i))
{
list.remove(checkedPositions.keyAt(i));
notes.notifyDataSetChanged();
lv.setItemChecked(i,false);
}
}
for(int i = size-1 ; i >= 0; i--)
{
if(checkedPositions.valueAt(i))
{
list.remove(checkedPositions.keyAt(i));
//lv.setItemChecked(checkedPositions.keyAt(i),false);
}
}
notes.notifyDataSetChanged();
From the look of it, you should change this
for(int i = 0; i <= size; i++)
to
for(int i = 0; i < size; i++)