android - 从 ArrayList 中删除项目,ArrayIndexOutOfBounds 异常

标签 android exception thread-safety arraylist

我目前有一个数组列表,在其中添加“blossom”对象(从屏幕顶部掉落)。当花朵和屏幕底部的盒子发生碰撞时,我想从 ArrayList 中删除花朵。但是,按照我现在的做法(在flower类中),我得到了 ArrayIndexOutOfBounds 异常。有人能看到我哪里出错了吗?我知道这与我的线程有关,我只是不知道将该方法放在哪里。 (这是在我的 Blossom 类的“hit”方法中执行的)。

板 View

    public BoardView(Context context){
    super(context);

    scorePaint.setColor(Color.BLACK);
    scorePaint.setTextSize(12);
    scorePaint.setTypeface(Typeface.MONOSPACE);


    //surfaceHolder provides canvas that we draw on
    getHolder().addCallback(this);

    // controls drawings
    thread = new BoardThread(getHolder(),this, blossomArrayList, box_x, box_y, 
            boxWidth, boxHeight);

    timer = new Thread(){
        public void run(){
            //makes sure the player still has 3 lives left
            while(game == false){
                uiCallback.sendEmptyMessage(0);
                try {
                    Thread.sleep(2000); // wait two seconds before drawing the next flower
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } //sleep for 2 seconds
            }
        }
    };
    timer.start();

    //intercepts touch events
    setFocusable(true);

}

@Override

public void onDraw(Canvas canvas){
    canvas.drawColor(Color.WHITE);
    score = "SCORE: " + currentScore;

    //note: pay attention to order you draw things
    //don't change order or else blossoms will fall
    //on top of box, not "into" it.

    //display the scoreboard
    canvas.drawText(score,240,420,scorePaint);
    // uses a synchronized method to prevent concurrent modification
    DrawBlossoms(canvas);
    canvas.drawBitmap(box, box_x, box_y, null);

}

@Override
public boolean onTouchEvent(MotionEvent event){
    //handles movement of box
    if(event.getAction() == MotionEvent.ACTION_DOWN){
        if(event.getX() > box_x & event.getY() > box_y & 
                event.getX() < box_x + boxWidth & event.getY() < box_y + boxHeight)
        {
            mode = true;
        }
    }

    if(event.getAction() == MotionEvent.ACTION_MOVE) {
        if(event.getX() > box_x & event.getY() > box_y & 
                event.getX() < box_x + boxWidth & event.getY() < box_y + boxHeight)
        {
            mode = true;
        }
        if(mode == true){
            box_x = (int)event.getX();
        }   

    }

    if(event.getAction() == MotionEvent.ACTION_UP){
        mode = false;
    }

    invalidate();
    return true;
}

@Override
public void surfaceChanged(SurfaceHolder holder, 
        int format, int width, int height ){
    Log.v(TAG, "Surface Changed");
    //somehow these don't seem to be working
}

@Override
public void surfaceCreated(SurfaceHolder holder){
    thread.startRunning(true);
    thread.start();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder){
    Log.v(TAG, "Surface Destroyed");
    //somehow these don't seem to be working
    thread.startRunning(false);
    thread.stop();
    timer.interrupt();
    timer.stop();
}

private Handler uiCallback = new Handler(){
    public synchronized void handleMessage(Message msg){
        //add a new blossom to the blossom ArrayList!!
        blossomArrayList.add(new Blossom( 
            (BitmapFactory.decodeResource
                    (getResources(), R.drawable.blossom))));
        blossomNum++;

        //remove neccesary blossoms from list
        Log.v(TAG, "Number of Blossoms =" + blossomNum);
    }
};

private synchronized void DrawBlossoms(Canvas c)
{
    Canvas canvas = c;
    for(Blossom blossom: blossomArrayList)   // getting errors here
    {
            blossom.Draw(canvas);
            blossom.hit(box_x,box_y, box_x + boxWidth, box_y + boxHeight, blossomArrayList);

    }
}

}

开花类

public Blossom(Bitmap bitmap)
{
    blossom = bitmap;
    blossomWidth = blossom.getWidth();
    blossomHeight = blossom.getHeight();
    blossom_x = generator.nextInt(320-blossom.getWidth());
    blossomRect = new RectF(blossom_x,blossom_y, blossom_x + blossomWidth, blossom_y + blossomHeight);
}

public Bitmap getBitmap()
{
    return blossom;
}

public Boolean hit(int boxLeft, int boxTop, int boxRight,int boxBottom, ArrayList<Blossom> blossomArrayList)
{
    if(remove == true)
    {
        Log.v(TAG, "Remove = true");
        blossomArrayList.remove(removeInt);
        remove = false;
    }
    if(blossom_x > boxLeft & blossom_y > boxTop
            & blossom_x + blossom.getWidth() < boxRight
            & blossom_y + blossom.getHeight() < boxBottom)
    {
        Log.v(TAG, "Collision Detected");
        remove = true;
        removeInt = blossomArrayList.indexOf(blossom);

        return true;
    }
    else
    {
        return false;
    }
}

public float getBlossomX()
{
    return blossom_x;
}

public float getBlossomY()
{
    return blossom_y;
}

public float getBlossomWidth()
{
    return blossomWidth;
}

public float getBlossomHeight()
{
    return blossomHeight;
}

public void Draw(Canvas canvas)
{
    //draws the flower falling
    if (hit == false)
    {
        canvas.drawBitmap(blossom, blossom_x,
            blossom_y = blossom_y+5 , null);
    }

}

public void UpdatePosition()
{
    blossomRect.set(blossom_x, blossom_y, blossom_x + 25, blossom_y + 25);
}

}

板线程

    public BoardThread(SurfaceHolder holder, BoardView boardView2, 
        ArrayList<Blossom> blossomArrayList1,
        int box_x, int box_y, int boxW, int boxH) {

    surfaceHolder = holder;
    boardView=boardView2;

    blossomArrayList = blossomArrayList1;
    boxX = box_x;
    boxY = box_y;
    boxW = boxWidth;
    boxH = boxHeight;
}

public void startRunning(boolean run) {

    mrun=run;
}

@Override
public void run() {

    super.run();
     Canvas canvas;
     while (mrun) {
        canvas=null;
         try {
             canvas = surfaceHolder.lockCanvas(null);
              synchronized (surfaceHolder) {
                 //update position
                 Position(blossomArrayList, boxX, boxY, boxWidth, boxHeight);
                 // draw flowers
                 boardView.onDraw(canvas);   // and getting errors here - concurrent 
             }
         } finally {
                 if (canvas != null) {
                 surfaceHolder.unlockCanvasAndPost(canvas);
             }
         }
     }
  }

private synchronized void Position(ArrayList<Blossom> blossomArrayList, int box_x, int box_y, 
        int boxWidth, int boxHeight)
{
    for(Blossom blossom: blossomArrayList)
    {
        blossom.UpdatePosition();
    }
}

}

最佳答案

问题是,您提供一个整数作为参数来删除方法,同时该方法将其视为 arrayList 的索引。

ArrayList提供了两种方法:

public E remove(int index)
public boolean remove(Object o)

你能做的是:
1) 创建一个字符串类型的arrayList。
2)将你的int转换为字符串并将其用作-

blossomArrayList.remove(String.valueOf(removeInt));


希望它有帮助..

关于android - 从 ArrayList 中删除项目,ArrayIndexOutOfBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5792917/

相关文章:

android - 字符串 webview 中的 html 标签 <div>

从 Playstore 与 Launcher 行为的 Android 打开应用程序

c - 线程在等待变量更改时陷入无限循环

c++ - boost::scoped_lock 不适用于局部静态变量?

android - 想在设备离线时将数据存储在本地数据库中,在线时从数据库中获取数据并发送到服务器

C++ 自定义异常

Android 构建失败的应用程序 :dexDebug error

java - 获取表示异常来源的 Method 对象

c++ - 以下单例实现线程安全吗?

android - 如何从源代码授予对特定应用程序的 root 访问权限而不是对 ROM 进行 root 访问?