在Android开发中常常使用到ListView控件,每个Item含有不同的标题和内容,有的甚至包含图片
类似如下样式:
那么如何将不同的文字与图片加载到listview中呢,我们可以使用JSON。
ListView每一个Item项包含一个ImageView和两个TextView控件。创建一个NewBean类包含:ImageUrl,title,content
属性。
有一个已知的url地址:String url="http://www.imooc.com/api/teacher?type=4&num=30";
<span style="font-size:18px;">该地址含有各种不同信息内容,具体可以自己查看。</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">//将字节流转化为字符流 </span>
<span style="font-size:18px;">private String readString(InputStream is){//传入InputStream字节流
InputStreamReader isr;
String result="";
try {
String line="";
isr=new InputStreamReader(is,"utf-8");//将字节流转化为字符流
BufferedReader br=new BufferedReader(isr);//将字符流以buffer性质读取出来
while((line=br.readLine())!=null){
result+=line;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}</span>
再通过JSON获取数据,将数据返回到List集合中:
private List<NewBean> getJsonData(String url){
List<NewBean> mlist=new ArrayList<>();
try {
/**
* new URL(url).openStream()此句功能与url.openConnection.getInputStream()相同
* 可根据URL直接联网获取数据,简单粗暴,返回值为InputStream类型
*/
String readStream=readStream(new URL(url).openStream());//获取地址中的信息
Log.d("xyz",readStream);
JSONObject jsonObject;
NewBean newBean;
jsonObject=new JSONObject(readStream);//将地址中的信息加载到jsonObject中
JSONArray jsonArray=jsonObject.getJSONArray("data");//获取name为“data”的信息
for(int i=0;i<jsonArray.length();i++){
jsonObject=jsonArray.getJSONObject(i);//获取单条信息
newBean=new NewBean();
newBean.imageurl=jsonObject.getString("picSmall");//加载name为“picSmall”的信息
newBean.title=jsonObject.getString("name");
newBean.content=jsonObject.getString("description");
mlist.add(newBean);//将信息加载到list列表中
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return mlist;
}