导致问题的代码在我的应用的MainActivity中。在onCreate方法中,有一个Thread运行一个名为uploadImage()的方法。然后返回一个Map并在uploadImage(Map实例)中设置。在线程之后, public Map uploadedImage为null。 (它会在声明的行上抛出NullPointerExeption)。有人知道为什么uploadImage在Thread之外被认为是null吗?谢谢!
...
public Map uploadedImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//only perform if there is a network connection
if(isNetworkAvailable()) {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
//try to upload image
uploadedImage = uploadImage();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
TextView txtURL = (TextView) findViewById(R.id.textView);
String url = uploadedImage.toString(); //NULLPOINTEREXEPTION HERE
txtURL.setText(url);
}
}
...
答案 0 :(得分:3)
然后uploadedImage
为null
。此外,您应该从此调用
String url = uploadedImage.toString();
显然要求uploadedImage
初始化,而不是null
;
if(isNetworkAvailable()) {
try {
//try to upload image
uploadedImage = uploadImage();
TextView txtURL = (TextView) findViewById(R.id.textView);
String url = (uploadedImage != null) ?
uploadedImage.toString() : "null";
txtURL.setText(url);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
方法uploadImage()的代码在哪里?检查那里发生了什么以及为什么它会返回null?
答案 2 :(得分:0)
我使用了ASyncTask并将Map放在String" url"在onPostExecute覆盖方法中。 上述人员说任务没有完成执行是正确的。谢谢大家的帮助。