我正在编写一个Android应用程序,我使用Aysnctask来使用openWeatherAPI获取当前天气。但它在这一行给了我一个NullPointerException:
results[0]=t;
这是我写的Aysnctask类:
private class GetWeather extends AsyncTask<String[], Void, String[]>{
@Override
protected String[] doInBackground(String... params) {
// TODO Auto-generated method stub
try {
params[0]=currentLatitude;
params[1]=currentLongitude;
String Url1="http://api.openweathermap.org/data/2.5/weather?lat="+currentLatitude+"&lon="+currentLongitude;
s1=getJson(Url1);
//Toast.makeText(getApplicationContext(), "the ss = "+s1, Toast.LENGTH_LONG).show();
Log.d("yes","yes");
if(s1!=null){
JSONObject jObj1 = new JSONObject(s1);
Log.d("jsonOOO","jsonOOO");
Tem= jObj1.getJSONObject("main").getDouble("temp");
Log.d("temmm","temmm="+String.valueOf(Tem));
pressure=jObj1.getJSONObject("main").getDouble("pressure");
humm=jObj1.getJSONObject("main").getDouble("humidity");
wind=jObj1.getJSONObject("wind").getDouble("speed");
desc=jObj1.getJSONObject("weather").getDouble("description");
double tem_c=Tem-273.15;
Log.d("tem11","tem11="+String.valueOf(tem_c));
String t=Double.toString(tem_c);
String t=String.valueOf(tem_c);
Log.d("tem22","tem22="+t);
results[0]=t;
Log.d("results[0]=","results[0]"+results[0]);
results[1]=String.valueOf(pressure);
results[2]=String.valueOf(humm);
results[3]=String.valueOf(wind);
results[4]=String.valueOf(desc);
}
} catch (Exception e) {
// TODO: handle exception
}
return results;
}//do in background
@Override
protected void onPostExecute(String[] results) {
temp.setText(results[0]+"°C");
hum.setText(results[1]+ "%");
press.setText(results[2]+ " hPa");
windSpeed.setText(results[3]+ " mps");
condDescr.setText(results[4]);
}
}
temp,pressure等的值不为null。我试图在logCat中打印它们并打印出来。
答案 0 :(得分:1)
需要声明和初始化results
数组(可能是doInBackground(String)
方法中的局部变量):
String[] results = new String[5];
答案 1 :(得分:0)
在调用之前,似乎没有初始化String []结果。 因此导致NullPointerException。
答案 2 :(得分:0)
你必须像这样初始化你的字符串数组:String[] results = new String[5];
答案 3 :(得分:0)
results
必须为null。空检查并初始化如下:
Log.d("tem22","tem22="+t);
if (results == null ) { //null-check
results = new String[5]; //initialize
}
results[0]=t;
Log.d("results[0]=","results[0]"+results[0]);
results[1]=String.valueOf(pressure);
results[2]=String.valueOf(humm);
results[3]=String.valueOf(wind);
results[4]=String.valueOf(desc);
为避免此类异常,最好配置IDE以警告您可能存在空取消引用
(例如在Eclipse中 - &gt;首选项 - &gt; Java - &gt;编译器 - &gt;错误 - &gt;警告 - &gt;空分析)