0

My question deals with the fundamentals of JAVA. I am creating an Android app and would like to access method parameters inside an anonymous thread that I create inside the method. Somehow, I keep getting null pointer exception. Here's how my code is looking like:

public void myMethod(final float x, final float y){
new Thread(new Runnable(){
float xx = x;
float yy = y;
@Override
public void run(){
//inside run method I create a for loop that uses the "x" and "y" parameters
//as "xx"  and "yy", respectively.
//keep getting null pointer exception on line where i attempt to do 
//calculations with x and y   
} 


}).start(); 

}

If anyone could please have a an answer it would be great. Should I make the method static? Perhaps, get rid of the final keyword?

thank you

i_o
  • 777
  • 9
  • 25
  • Can you please show a [mcve]? Ints don't cause NullPointerExceptions, uninitialized objects do – OneCricketeer Jun 11 '16 at 06:53
  • Could you share also the part of code where you're getting the null pointer? – Mick Mnemonic Jun 11 '16 at 06:53
  • inside the for loop i add this line: double e = Math.pow((newX-trans_linear_layout.getX()),2); This is where I get the null pointer exception. I don't think its my layout variable since this calls happens way after layout has taken place. It might be a problem of subtracting two floats. Perhaps I should turn them into double variables? @MickMnemonic – i_o Jun 11 '16 at 07:02
  • There's nothing in the code you posted that can throw a NPE, please post relevant code snippets, and the stack trace of the exception. – Egor Jun 11 '16 at 07:10
  • post some code inside `run()`. so people can figure out what making you cause NPE..!! – Janki Gadhiya Jun 11 '16 at 07:29
  • Okay everyone. After much re-running the app and testing it, I see that the problem lies with my layout variable this layout variable is moved around with an ObjectAnimator. Somehow, I cant get a hold of its x and y location on the screen. This layout was created in xml. I will recreate layout programmatically and am sure it will work fine. Somehow, xml layouts always give me some problems. – i_o Jun 11 '16 at 07:37

1 Answers1

0

If you're getting null pointer exception it means that you didn't initialize some object variable. Also NPE could be thrown when your app wants to get some value but calculations hasn't been finished. Try to make calculations in single thread mode or provide code of calculation.

Arthur
  • 769
  • 7
  • 17