Android项目中AsyncTask数组创建空指针异常求助
解决AsyncTask数组空指针异常的问题
兄弟,我一眼就发现你遇到的问题根源了:你声明了Task[] myTasks = new Task[10];这个数组,但数组里的每个Task元素都没有被实例化,全是null值。当你调用myTasks[sInt].execute()时,自然会抛出“Attempt to invoke virtual method on null reference”的空指针异常。
另外还有个隐藏的坑:你用了全局的weather和n变量来传递数据,多个Task实例会共享这些变量,很容易导致数据覆盖,显示错误的天气信息。下面是具体的修复方案:
1. 先实例化数组中的Task对象
在调用execute()之前,要确保数组对应的位置已经创建了Task实例。修改你的loadTask方法:
private void loadTask(int sInt, String city){ // 先检查并实例化Task对象 if(myTasks[sInt] == null){ myTasks[sInt] = new Task(sInt); // 这里把索引sInt传给Task,避免用全局n } myTasks[sInt].execute(new String[]{city + "&APPID="+ WeatherApiNumber + "&units=metric"}); }
2. 让每个Task持有自己的索引,避免全局变量冲突
修改你的Task内部类,让它接收并保存对应的索引值,不再依赖全局的n和weather:
private class Task extends AsyncTask<String, Void, Weather>{ private int taskIndex; // 每个Task自己的索引,对应要更新的TextView位置 // 构造方法接收索引 public Task(int index){ this.taskIndex = index; } @Override protected Weather doInBackground(String... params) { String data = ((new WeatherClient()).getWeatherData(params[0])); // 这里直接返回解析后的Weather,不要用全局变量 return Parser.getWeather(data); } @Override protected void onPostExecute(Weather weather) { super.onPostExecute(weather); // 把当前Task的索引和解析后的Weather传进去 cityData(taskIndex, weather); } }
3. 修改cityData方法,使用传入的Weather对象
原来的cityData依赖全局weather变量,现在改成接收参数:
public void cityData(int n, Weather weather){ city[n].setText(weather.place.getCity()); time[n].setText(Integer.toString(weather.place.getTimeZone())); temperature[n].setText(Double.toString(weather.temp.getTemp()).substring(0,2)); }
为什么单个Task没问题?
因为你单个Task是直接实例化的:Task task1 = new Task();,它不是null,所以调用task1.execute()不会报错。但数组里的元素默认都是null,必须手动创建每个Task实例才能使用。
这样修改后,不仅解决了空指针问题,还避免了多个Task之间的数据干扰,每个Task都会独立处理自己的天气数据并更新对应的TextView。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

