1

In my Android app I have an event handler that gets called from another thread. When the handler is called some of my private fields are null so I get a NullPointerException because I'm trying to access a method from a null object. I cannot see why they would be null as I instantiate the fields earlier and I don't set the fields anywhere else.

Can this have something to do with cross threading? The fields are set in one thread but accessed by another thread..? No, right? They shouldn't be null.. I'm going crazy here, but it's probably a tiny mistake that I just can't spot right now.

I guess it's hard to answer when you don't have the code, but I can't post my whole solution here. Maybe someone can point me in the right direction for what to look for..?

Ben Adams
  • 564
  • 1
  • 4
  • 18
  • 3
    To get better help faster, provide an [SSCCE](http://sscce.org). – aioobe May 31 '12 at 22:09
  • 2
    Are you sure it's another `Thread`? It's not an `Activity`? In any case, if you are referencing fields that are `null`, you should check whether your object is null, or if those fields are null. – Codeman May 31 '12 at 22:15
  • Are these Android system events, like MotionEvent? If so, then they are on the event thread for your app. What is the other thread? You'll probably need to provide some amount of code--not the whole solution, but maybe the relevant part of the activity along with whatever that other thread is. – Steve Blackwell May 31 '12 at 22:25
  • @Pheonixblade9 The object is created as a private field in my activity class and then accessed by another thread using a getter in my activity. Can that be a problem? – Ben Adams Jun 01 '12 at 08:34
  • That can absolutely be a problem. You need to make sure you are using `runOnUIThread(new Runnable(){});` if you are accessing resources tied to the UI thread from another thread. – Codeman Jun 01 '12 at 15:49

1 Answers1

0

I finally found the solution. I found out that Android is starting my activity twice. So apparently in one activity the state of the object was fine, but in the other I had fields that were null.

When the orientation of the device changes, Android apparently stops the activity and starts another one. I found the solution here and here

And thanks for your help guys, even though there wasn't much for you to go by..

Community
  • 1
  • 1
Ben Adams
  • 564
  • 1
  • 4
  • 18