尝试从互联网上获取的JSON字符串的ArrayList更新列表视图。
public void updateListView(ArrayList<String> crimes) {
ArrayAdapter<String> crimeAdapter = new ArrayAdapter<String>(
this.getActivity(),
R.layout.listview_dbresults,
R.id.listview_opendata,
crimes);
View rootView = inflater.inflate(R.layout.activity_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.dbResults);
listView.setAdapter(crimeAdapter);
}
@Override
protected ArrayList<String> doInBackground(String[]... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
try {
URL url = new URL("JSON_LINK");
Log.d("app", "url");
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
ArrayList<String> crimes = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
crimes.add(line);
}
Log.d("app", "I've read all lines");
return crimes;
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
protected void onPostExecute(ArrayList<String> crimes)
{
if (crimes.size() == 0 || crimes == null) {
// Stream was empty. No point in parsing.
return;
}
DataFetcher dataFetcher = new DataFetcher();
dataFetcher.updateListView(crimes);
}
doInBackground从互联网URL获取JSON,然后将其传递给onPostExecute,然后从DataFetcher类(单独的类)调用该方法以更新该类中已有的现有列表视图。
java.lang.NullPointerException:尝试调用虚方法 &#39; java.lang.Object android.content.Context.getSystemService(java.lang.String)&#39;在空对象引用上 在我的updateListView()方法中发生,其中ArrayAdapter被实例化。