无报错,但是没内容 为什么
public class page extends Activity {
private ListView mListView;
private static String URL = "http://www.imooc.com/api/teacher?type=4&num=30";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_lise_view);
mListView = (ListView) findViewById(R.id.NewsList);
new NewsAsyncTask().execute(URL);
}
/*将URL对应的JSON格式转化为我们所封装的NewBean*/
private List<NewsBean> getJsonData(String url) {
List<NewsBean> newsBeanList = new ArrayList<>();
try {
String jsonString = readStream(new URL(url).openStream()); /*此句和URL.Connection().getInputStream()相同可以根据URL直接联网使用,返回值为InputStream*/
// Log.d("xys",jsonString);
JSONObject jsonObject;
NewsBean newsBean;
try {
jsonObject = new JSONObject(jsonString); //将json的格式的字符串转化为对象,我们要取出的就是这个对象的内容
JSONArray jsonArray = new JSONObject().getJSONArray("data"); //先取出data这个json数组
for (int i =0;i<jsonArray.length();i++){ //遍历整个数组,取出需要的内容
jsonObject = jsonArray.getJSONObject(i); //先把数组里的内容都取出来,然后把这些值传递给newsbean
newsBean = new NewsBean();
newsBean.newsIConUrl = jsonObject.getString("picSmall"); //获取json里的图片
newsBean.newstitle = jsonObject.getString("name");
newsBean.newscontent = jsonObject.getString("description");
newsBeanList.add(newsBean); //属性设置完后,就把封装好的newsBean塞到集合里,准备添加到适配器上
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return newsBeanList;
}
/*通过is 解析网页返回的数据*/
private String readStream(InputStream is){ //处理字节流的抽象类,这个是输入流
InputStreamReader isr; /*InputStreamReader 是字节流通向字符流的桥梁,它将字节流转换为字符流.
OutputStreamWriter是字符流通向字节流的桥梁,它将字符流转换为字节流.*/
String result = "";
try {
String line = "";
isr =new InputStreamReader(is,"utf-8"); //将字节流转换为字符流 这个只能逐行读取
BufferedReader br = new BufferedReader(isr); //将字符流以BufferedReader的形式读取出来
while ((line =br.readLine()) !=null){
result += line; /*BufferedReader BufferedWriterBufferedReader 由Reader类扩展而来,
提供通用的缓冲方式文本读取,readLine读取一个文本行,
从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
BufferedWriter 由Writer 类扩展而来,提供通用的缓冲方式文本写入, newLine使用平台自己的行分隔符*/
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/*实现了网络的异步访问*/
//NewsBean封装item,List存储无数个List,把List装载到Adapter里,通过Adapter和listView相连
class NewsAsyncTask extends AsyncTask <String,Void,List<NewsBean>>{
@Override
protected List<NewsBean> doInBackground(String... params) {
return getJsonData(params[0]); //请求的网址只有一个 params是一个数组
}
@Override
protected void onPostExecute(List<NewsBean> newsBean) {
super.onPostExecute(newsBean);
NewsAdapter adapter =new NewsAdapter(page.this,newsBean);
mListView.setAdapter(adapter);
}
}
}