今天带大家看一下如何从网络中获取json数据信息!
首先看一下最终的效果图
json文件:
实现效果:
要实现这个小程序,首先要看一下我们的实现步骤:
- 1、创建一个ListView控件 使用4 个步骤显示基本数据
- 2、在initData方法中 使用HttpUrlConnetion把地址中的Json字符串请求回来
- 3、把Json字符串解析成NewsData数据类型
- 4、在Adapter中的getView方法中 把NewsData中的标题和描述 先显示在控件
- 5、因为NewsData中还保存了每一个条目的 图片地址
- 6、getView方法中使用网络请求把每一个图片请求回来
- 7、图片回来后,使用OnUIThread方法把图片资源加载在ImageView控件上
OK,下面来看一下它是如何实现的:
构成:
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.weekone.MainActivity" >
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
list_item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
>