运行此代码时获取NullPointer异常:
public class MainActivity extends AppCompatActivity {
TextView textView;
String JSONstr;
String title;
JSONObject weatherInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
weatherThread weather = new weatherThread();
weather.execute();
Log.d("LOL1","TESTING");
try {
weatherInfo=new JSONObject(JSONstr);
title=weatherInfo.getJSONObject("query").getString("created");
} catch (JSONException e) {
e.printStackTrace();
}
}
public class weatherThread extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
URL url;
URLConnection urlConnection;
InputStream inputStream;
BufferedReader bufferedReader;
try {
url=new URL("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%2208852%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
urlConnection = url.openConnection();
inputStream = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
JSONstr=bufferedReader.readLine();
bufferedReader.close();
Log.d("TEST",JSONstr);
} catch (IOException e) {Log.d("ERROR",e.toString());}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
这是JSONObject的链接
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%2208852%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
我试着查看其他帖子,但他们的代码完全不同于我的。 try catch语句出现错误。
提前谢谢
编辑:为什么你把它标记为关于&#34;什么是空指针异常&#34;的问题的副本。这个问题是为什么它会在特定情况下出现。