我想了解JSON解析。我想从URL获取数据并在ListView中显示数据,但是我收到错误:
不幸的是应用程序停止了
如何解决此错误?我的代码中有错误吗?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONTask().execute("14.140.200.186/Hospital/get_city.php");
}
public class JSONTask extends AsyncTask<String,String, List<CityModel>>{
@Override
protected void onPostExecute( List<CityModel> result) {
super.onPostExecute(result);
CityAdapter adapter=new CityAdapter(getApplicationContext(),R.layout.row,result);
lvCity = (ListView) findViewById(R.id.lvCity);
lvCity.setAdapter(adapter);
}
public class CityAdapter extends ArrayAdapter{
private List<CityModel> cityModelList;
private int resource;
private LayoutInflater inflater;
public CityAdapter(Context context, int resource, List<CityModel> objects) {
super(context, resource, objects);
cityModelList=objects;
this.resource=resource;
inflater= (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null)
convertView=inflater.inflate(resource,null);
TextView cityname;
cityname= (TextView)convertView.findViewById(R.id.cityname);
cityname.setText(cityModelList.get(position).getCity_name());
return convertView;
}
}
@Override
protected List<CityModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson=buffer.toString();
JSONObject parentObject=new JSONObject(finalJson);
JSONArray parentArray=parentObject.getJSONArray("Cities");
List<CityModel>cityModelList=new ArrayList<>();
for (int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
CityModel cityModel=new CityModel();
cityModel.setCity_name(finalObject.getString("city_name"));
cityModelList.add(cityModel);
}
return cityModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
;
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}