public class MainActivity extends Activity {

    protected static final int WHAT_REQUEST_SUCCESS = 1;
    protected static final int WHAT_REQUEST_ERROR = 2;
    private ListView lv_main;
    private LinearLayout ll_main_loading;
    private List<ShopInfo> data;
    private ShopInfoAdapter adapter;
    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case WHAT_REQUEST_SUCCESS:
                ll_main_loading.setVisibility(View.GONE);
                //显示列表
                lv_main.setAdapter(adapter);
                break;
            case WHAT_REQUEST_ERROR:
                ll_main_loading.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, "加载数据失败", Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv_main = (ListView) findViewById(R.id.lv_main);
        ll_main_loading = (LinearLayout) findViewById(R.id.ll_main_loading);
        adapter = new ShopInfoAdapter();

        //1. 主线程, 显示提示视图
        ll_main_loading.setVisibility(View.VISIBLE);
        //2. 分线程, 联网请求
        //启动分线程请求服务器动态加载数据并显示
        new Thread(){
            public void run() {
                //联网请求得到jsonString
                try {
                    String jsonString = requestJson();
                    //解析成List<ShopInfo>
                    data = new Gson().fromJson(jsonString, new TypeToken<List<ShopInfo>>(){}.getType());
                    //3. 主线程, 更新界面
                    handler.sendEmptyMessage(WHAT_REQUEST_SUCCESS);//发请求成功的消息
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(WHAT_REQUEST_ERROR);//发送请求失败的消息
                }
            }
        }.start();

    }

    /**
     * 联网请求得到jsonString
     * @return
     * @throws Exception
     */
    private String requestJson() throws Exception {
        String result = null;
        String path = "http://192.168.10.165:8080/L05_Web/ShopInfoListServlet";
        //1. 得到连接对象
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //2. 设置
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        //连接
        connection.connect();
        //发请求并读取服务器返回的数据
        int responseCode = connection.getResponseCode();
        if(responseCode==200) {
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            connection.disconnect();

            result = baos.toString();
        } else {
            //也可以抛出运行时异常
        }
        return result;
    }

    class ShopInfoAdapter extends BaseAdapter {

        private ImageLoader imageLoader;

        public ShopInfoAdapter() {
            imageLoader = new ImageLoader(MainActivity.this, R.drawable.loading, R.drawable.error);
        }
        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView==null) {
                convertView = View.inflate(MainActivity.this, R.layout.item_main, null);
            }
            //得到当前行的数据对象
            ShopInfo shopInfo = data.get(position);
            //得到当前行的子View
            TextView nameTV = (TextView) convertView.findViewById(R.id.tv_item_name);
            TextView priceTV = (TextView) convertView.findViewById(R.id.tv_item_price);
            ImageView imageView = (ImageView) convertView.findViewById(R.id.iv_item_icon);
            //设置数据
            nameTV.setText(shopInfo.getName());
            priceTV.setText(shopInfo.getPrice()+"元");
            String imagePath = shopInfo.getImagePath();
            //根据图片路径启动分线程动态请求服务加载图片并显示
            imageLoader.loadImage(imagePath, imageView);
            return convertView;
        }

    }
}
 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/lv_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

    <LinearLayout
        android:id="@+id/ll_main_loading"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:visibility="gone">

        <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="正在加载中..." />

    </LinearLayout>

</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/iv_item_icon"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@drawable/ic_launcher"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center_vertical"
        android:layout_marginLeft="10dp">

        <TextView
            android:id="@+id/tv_item_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="名称"
            android:textSize="18sp"/>

        <TextView
            android:id="@+id/tv_item_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="内容"
            android:textSize="18sp"/>

    </LinearLayout>
</LinearLayout>

远程请求json数据,list中显示的更多相关文章

  1. AJAX跨域请求json数据的实现方法

    这篇文章介绍了AJAX跨域请求json数据的实现方法,有需要的朋友可以参考一下 我们都知道,AJAX的一大限制是不允许跨域请求. 不过通过使用JSONP来实现.JSONP是一种通过脚本标记注入的方式, ...

  2. bootstrap通过ajax请求JSON数据后填充到模态框

    1.   JSP页面中准备模态框 <!-- 详细信息模态框(Modal) --> <div> <div class="modal fade" id=& ...

  3. 关于使用Ajax请求json数据,@RequestMapping返回中文乱码的几种解决办法

    一.问题描述: 使用ajax请求json数据的时候,无论如何返回的响应编码都是ISO-8859-1类型,因为统一都是utf-8编码,导致出现返回结果中文乱码情况. $.ajax({ type:&quo ...

  4. EHlib在数据单元中显示字段值为图形。

    -[定制网格数据单元]  在数据单元中显示字段值为图形.  TDBGridEh allows to show bitmaps from TImageList component depending o ...

  5. react之fetch请求json数据

    Fetch下载 npm install whatwg-fetch -S Fetch请求json数据 json文件要放在public内部才能被检索到

  6. ajax 请求json数据中json对象的构造获取问题

    前端的界面中,我想通过ajax来调用写好的json数据,并调用add(data)方法进行解析,请求如下: json数据如下: { “type”:"qqq", "lat&q ...

  7. ajax请求json数据跨域问题(转)

    一.后台代理技术 由服务器端向跨域下的网站发出请求,再将请求结果返回给前端,成功避免同源策略的限制. 具体操作如下: 1.在localhost:81/a.html中,向同源下的某个代理程序发出请求 $ ...

  8. Struts2 Action接收POST请求JSON数据及其实现解析

    一.认识JSON JSON是一种轻量级.基于文本.与语言无关的数据交换格式,可以用文本格式的形式来存储或表示结构化的数据. 二.POST请求与Content-Type: application/jso ...

  9. Android开发——获得Json数据,并显示图片

    流程介绍 使用okhttp网络框架进行get请求,获得json数据 //一个封装好的工具类的静态方法 public static void sendOkHttpRequest(final String ...

随机推荐

  1. hdu 5443(线段树水)

    The Water Problem Time Limit: 1500/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Othe ...

  2. AC日记——拍照 洛谷 P3410

    题目描述 小B有n个下属,现小B要带着一些下属让别人拍照. 有m个人,每个人都愿意付给小B一定钱让n个人中的一些人进行合影.如果这一些人没带齐那么就不能拍照,小B也不会得到钱. 注意:带下属不是白带的 ...

  3. VUE之命令行报错:Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead 解决办法

    Failed to compile. ./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-5992 ...

  4. Codeforces Round #317 [AimFund Thanks-Round] (Div. 2) Minimization dp

    原题链接:http://codeforces.com/contest/572/problem/D 题意 给你个数组A和n,k,问你排列A后,下面的最小值是多少. 题解 先排个序,要填充像1,1+k,1 ...

  5. VC2012编译protobuf出错处理

    近来要学习protobuf的协议生成.须要从网上下载它的代码,从这个SVN地址下载: 个.因此编译提示上面的出错.仅仅须要把std;;tuple里的个数定义为10个就可以.,因此不支持5个以上的參数输 ...

  6. Vue beforeRouteEnter 的next执行时机

    背景 今天在用vue实现界面的时候,想在beforeRouteEnter钩子函数中去获取数据,然后通过next方法设置到跳转页面的实例中,结果发现数据一直没办法在界面渲染的时候赋值,苦思不得其解,遂g ...

  7. d3js 画布 概念

    HTML 5 提供两种强有力的“画布”:SVG 和 Canvas. SVG 有如下特点: SVG 绘制的是矢量图,因此对图像进行放大不会失真. 基于 XML,可以为每个元素添加 JavaScript ...

  8. 三行代码实现.NET MVC统计显示页面的执行时间 超简单的实现方法 分析页面执行效率

    三行代码实现.NET MVC统计显示页面的执行时间 超简单的实现方法 分析页面执行效率    博客页脚处添加了页面执行时间统计显示,如下图所示,也可以直接查看网页页脚处. 实现方法非常简单,只需三行代 ...

  9. [转]si设置

    好吧,我有代码格式的强迫症,代码不整齐,我看的都头疼,之前一直喜欢用SourceStyler C++的,但是这个在win7下貌似不能使用,只能转向astyle了. http://www.cnblogs ...

  10. hdoj 5094 Maze 【BFS + 状态压缩】 【好多坑】

    Maze Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 100000/100000 K (Java/Others) Total Sub ...