我正在编写一个具有以下基本结构的 Android 应用程序:
MyActivity.java
- 将视图设置为 MyView
。
MyThread.java
- 包含 surfaceHolder
,调用 MyView 中的 update()
和 render()
函数。 java
MyView.java
- 使用 render()
函数绘制到画布,更新 MyPuzzle
类,处理触摸事件。
MyPuzzle.java
- 包含元素的ArrayList/Vector
。
我的问题是:
在 MyView
类中,在 render()
函数中,我循环遍历 ArrayList/Vector
中保存的内容code>MyPuzzle 类并将它们绘制到画布上。然而,尽管从 i=0; 循环,我偶尔会遇到 indexOutOfBounds
错误(可能每 10 次一次)。 i
在同一个 MyView
类中,在 onTouchEvent
函数中,我有从 MyView
中添加/删除项目的代码code>ArrayList/Vector 正在绘制。
我的索引越界错误是否可能是由于在 render()
函数循环遍历 ArrayList/Vector< 的同时处理 onTouchEvent
引起的/code> 并将元素绘制到屏幕上?
我尝试实现一个系统,其中 onTouchEvent
不会立即处理,而是添加到 ArrayList
队列中,并且仅在 render()
之前处理> 被调用。通过我所做的有限测试,这似乎已经解决了问题。这听起来正确吗?这让我有些抓狂。
感谢您提前提供的帮助,对于写得不好的问题表示歉意,我可以添加您可能需要的更多详细信息。
I'm writing an Android application with the following basic structure:
MyActivity.java
- sets view as MyView
.
MyThread.java
- contains surfaceHolder
, calls update()
and render()
functions in MyView.java
MyView.java
- draws to canvas using render()
function, updates MyPuzzle
class, handles touch events.
MyPuzzle.java
- contains an ArrayList/Vector
of elements.
My question is:
In the MyView
class, in the render()
function I loop through the contents of the ArrayList/Vector
held within the MyPuzzle
class and draw them to the canvas. However, I was occasionally getting indexOutOfBounds
errors (perhaps once every 10 times), despite looping from i=0; i<arraylist.size()...
In the same MyView
class, in the onTouchEvent
function, I have code which adds/removes items from the ArrayList/Vector
which is being drawn.
Are my index out of bounds errors likely caused by the onTouchEvent
s being processed at the same time as the render()
function is looping through the ArrayList/Vector
and drawing the elements to the screen?
I tried implementing a system whereby the onTouchEvent
s were not dealt with immediately, but were added to an ArrayList
queue, and only processed before render()
is called. This seems to have fixed the problem, with the limited testing I've done of it. Does this sound about right? It's been driving me somewhat mad.
Thanks for your help in advance, apologies for the badly written question, I can add any more detail you may require.
发布评论
评论(1)
IndexOutOfBounds 可能是迭代线程最初看到大小为 N 的列表并开始从 0 到 N 迭代的情况的直接结果。Thread-2 进入并从列表中删除,使其有效为 N-1,因此如果 Thread -1 尝试读取 list.get(N) 你会得到异常。
如果列表的深度不是很大,并且您没有删除和添加整个丢失的交换列表,请使用
CopyOnWriteArrayList
实现。否则,您将需要同步
列表的所有操作,例如包括迭代The IndexOutOfBounds is probably a direct result of a situation where the iterating thread will intially see the List at size N and starting iterating from 0 to N. Thread-2 Comes in and removes from the list making it effectively N-1, so if Thread-1 attempts to read at list.get(N) you get your exception.
If the depth of the list isn't very large and you are not removing and adding a whole lost swap the List implementation with
CopyOnWriteArrayList
. Otherwise you will need tosynchronize
on all actions of the list including the iterating for example