我继续获得空指针异常错误。我浏览了我的代码,我不确定为什么会遇到此错误。当我补充程序
时,我会填充错误读取NULL指针异常:尝试在null对象引用上调用虚拟方法int Java.lang.string.length()。预先感谢。
EditText enterCity;
TextView weatherView;
public void onClick (View view) {
downloadAPIInfo task = new downloadAPIInfo();
String APIKEY = "b4fabae83c89c469d7a458a230b7a267";
String website = "http://api.openweathermap.org/data/2.5/weather?q=";
String url = website + enterCity.getText().toString() + APIKEY;
task.execute(url);
Log.i("User Entry", enterCity.getText().toString());
}
public class downloadAPIInfo extends AsyncTask<String, Void, String> {
URL url;
HttpURLConnection httpURLConnection = null;
String result = "";
@Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int data = reader.read();
while(data != -1) {
char one = (char) data;
result += one;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Onpostexecute interacts with the UI
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject object = new JSONObject(result);
String weatherInfo = object.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i = 0; i < array.length(); i++ ) {
JSONObject jsonPart = array.getJSONObject(i);
Log.i("main", jsonPart.getString("main"));
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != "") {
message+= main + ":" + description + "rn";
}
}
if(message != "") {
weatherView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Log.i("WebsiteContent", result);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterCity = (EditText) findViewById(R.id.cityeditText);
weatherView = (TextView) findViewById(R.id.weathertextView);
}
}
名为'array'的jsonArray在您的onpostexecute mehtod中为null。您的WeatherInfo字符串很可能为空。
我建议您发布完整的stacktrace,以提供更好的解释。