Reputation: 71
In standard java this code works fine. But I think it shouldn't.
class Data{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
class Test{
private Data mData;
public void back(){
mData=new Data();
mData.setName("You");
}
public void go(){
Thread mThread = new Thread(){
public void run(){
System.out.println(mData.getName());
}
};
mThread.start();
}
}
But when doing a similar thing in Android, it throws a NullPointerException.
private void writeApp(){
Thread mThread = new Thread(){
public void run(){
Log.d(TAG,modelData.getAppName());
}
};
mThread.start();
}
//Edit
public void appOpens(String appPackageName) throws NameNotFoundException{
modelData = new ModelData();
modelData.setOpen(true);
modelData.setAppPackageName(appPackageName);
modelData.setOpenTime(getTimeMil());
setAppNameAndAppVersion();
}
private void writeApp(){
Log.d(TAG+1,modelData.getAppName());//works fine
Thread mThread = new Thread(){
public void run(){
Log.d(TAG+2,modelData.getAppName());//doenst works throws NullPointerException
}
};
mThread.start();
}
appOpens(String appPackageName)
calling fist.
Log.d(TAG+1,modelData.getAppName())
doesn't throw NullPointerException , but Log.d(TAG+2,modelData.getAppName())
throws i believe it is proper behavior , cuz i don't share instance to thread.It is only reachable from main thread.But in standard java second thread accesses my main thread , how could it be?
Upvotes: 1
Views: 134
Reputation: 40256
Can you assign modelData to a final local field?
private void writeApp(){
final ModelData data = modelData;
Log.d(TAG+1,data.getAppName());//works fine
Thread mThread = new Thread(){
public void run(){
Log.d(TAG+2,data.getAppName());//doenst works throws NullPointerException
}
};
mThread.start();
}
If //works fine
still works then //doesnt work
will now work.
Upvotes: 1
Reputation: 46856
Are you ever instantiating the Data object?
To me it looks like your problem is just that modelData is probably null, and you trying to call .getAppName()
on it which would throw a null pointer if modelData is null.
I would not expect it to work correctly on "plain" java if you don't instantiate your Data object either, but it is certainly possible there are some differences that could cause it to work on one, and not the other.
Upvotes: 1