开发者

NullPointerException from "synchronized"

I do get a NullPointerException from a synchronized method in the codesnip below. mElements is an arrayList of Enemies looking like this:

public ArrayList<Enemies> mElements = new ArrayList<Enemies>(); 

The weird part is that I do another sychronized earlier in the code on the same arrayList without a problem. When I debug the program, I can see that the arrayList is not null, it has one Element that is added to it. I can't follow the debug any more then this since synchronized is not my code. I hope I can get a hint from someone here. Please ask for any more details if needed.

public void animate(long elapsedTime) {
    synchronized (mElements) {
        for (Enemies enemies : mElements) {
            enemies.animate(elapsedTime);
        }
}

Here is some of the stack trace:

04-15 17:31:26.897: INFO/ActivityManager(60): Displayed activity twod.game/.twod.StartGame: 15025 ms (total 15025 ms)
04-15 17:31:32.112: WARN/dalvikvm(386): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
04-15 17:31:32.177: ERROR/AndroidRuntime(386): FATAL EXCEPTION: Thread-9
04-15 17:31:32.177: ERROR/AndroidRuntime(386): java.lang.NullPointerException
04-15 17:31:32.177: ERROR/AndroidRuntime(386):     at twod.game.twod.Panel.animate(Panel.java:81)
04-15 17:31:32.177: ERROR/AndroidRuntime(386):     at twod.game.twod.ViewThread.run(ViewThread.java:31)
04-15 17:31:32.203: WARN/ActivityManager(60):   Force finishing activity twod.game/.twod.StartGame
04-15 17:31:3开发者_运维技巧2.417: DEBUG/dalvikvm(60): GC_FOR_MALLOC freed 7573 objects / 446304 bytes in 104ms
04-15 17:31:42.267: WARN/ActivityManager(60): Launch timeout has expired, giving up wake lock!
04-15 17:31:42.267: WARN/ActivityManager(60): Activity idle timeout for HistoryRecord{440028c8 twod.game/.twod.game}
04-15 17:31:52.287: WARN/ActivityManager(60): Activity destroy timeout for HistoryRecord{4403f608 twod.game/.twod.StartGame}


I'd say it's not a synchronized problem then, but rather you may have null elements inside your ArrayList (ArrayList permits null elements). Try printing out enemies each time before you do anything to it.

Null elements will not be skipped over when you iterate an ArrayList. Here's a simple example to show that in action:

import java.util.ArrayList;
import java.util.List;

public class NullTest {
  public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("foo");
    list.add(null);
    list.add("bar");

    System.out.println("Begin");
    for (String val : list) {
      System.out.println("Value: " + val);
      try {
        // Try to use the value
        val.toString();
        System.out.println("No NPE");
      } catch (NullPointerException npe) {
        System.out.println("NPE Caught");
      }
    }
    System.out.println("End");
  }
}


Try using CopyOnWriteArrayList instead of ArrayList

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜