android使用Thread实现json数据的传递,并且使用ListView显示

   在android 4.0以后,不能在主线程中使用网路资源。所以对于使用json传递的数据,我们要用它直接生成Listview会报一个android.os.NetworkOnMainThreadException的异常,那么要如何处理这些网络资源呢?实际上有很多种方法来处理这些网络资源,这里介绍一种使用新线程(new Thread(){})的方式进行处理。

    这里我要实现通过接收JSON来生成ListView的操作。

一、建立Web Service

1.启动Java EE,建立一个Dynamic Web Project

选上自动创建xml文件。

2.新建一个Servlet,并在xml文件中配置。

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MyServer</display-name>
  <servlet>
    <display-name>MyServer</display-name>
    <servlet-name>MyServer</servlet-name>
    <servlet-class>org.zyh.server.xml.MyServer</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServer</servlet-name>
    <url-pattern>/MyServer</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


3.建立业务Bean,实现业务方法。    

MyService.java

package org.zyh.server.service;
import java.util.List;
public interface MyService {
    public List<News> getLastNews();
}


MyServiceBean.java

package org.zyh.server.impl;
import java.util.ArrayList;
import java.util.List;
import org.zyh.server.entity.News;
import org.zyh.server.service.MyService;
public class MyServerImpl implements MyService {
    @Override
    public List<News> getLastNews() {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        List<News> list = new ArrayList<>();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        list.add(new News(22,"二狗子",45));
        list.add(new News(23,"三胖子",46));
        list.add(new News(24,"狗剩子",47));
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        return list;
    }
}

这里就直接写一下虚拟的数据,就不链接数据库了。

4.实体类 Info.java

package org.zyh.server.entity;
public class Info {
                                                                                                                                                                                                                                                                                                                                                                                                             
    Integer id;
    String title;
    Integer age;
    public Info(Integer id, String title, Integer age) {
        this.id = id;
        this.title = title;
        this.age = age;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Integer getTimelenght() {
        return age;
    }
    public void setTimelenght(Integer age) {
        this.age = age;
    }
}


5. MyServlet.java

package org.zyh.server.xml;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.zyh.server.entity.Info;
import org.zyh.server.impl.MyServerImpl;
import org.zyh.server.service.MyService;
public class MyServlet extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
                                                                                                                                                                                                                                                                                                                         
    private MyService myService = new MyServerImpl();
                                                                                                                                                                                                                                                                                                                         
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        doPost(request,response);
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        List<Info> info = myService.getLastInfo();
                                                                                                                                                                                                                                                                                                                             
        StringBuilder json = new StringBuilder();
        json.append(‘[‘);
        for(Info i : info){
            json.append("{");
            json.append("id:").append(i.getId()).append(",");
            json.append("title:\"").append(i.getTitle()).append("\",");
            json.append("age:").append(i.getAge());
            json.append("},");
        }
        json.deleteCharAt(json.length()-1);
        json.append(‘]‘);
        request.setAttribute("json", json.toString());
        request.getRequestDispatcher("/WEB-INF/page/info.jsp").forward(request, response);
    }
                                                                                                                                                                                                                                                                                                                         
}


6.在WEB-INF下建立page/info.jsp

<%@ page language="java" contentType="text/plain; charset=utf-8"
    pageEncoding="utf-8"%>${json}

7.将工程run on server


二、在android上读取json数据,并生成listview。


1.建立工程 JSONToListView

布局文件

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView" />
</LinearLayout>


item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <TextView
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        />
    <TextView
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/age"
        />
</LinearLayout>


Info.java

package org.zyh.jsontolistvew;
public class Info {
    Integer id;
    String name;
    Integer age;
    public Info(){};
    public Info(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
                                                                                                                  
}


MyService.java

package org.zyh.jsontolistvew;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
public class InfoService {
    public static List<Info> getLastInfo() throws Exception{
                                                                                                                        
        String path = "http://10.10.1.81:8080/MyServer/MyServlet";
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == 200){
            InputStream input = conn.getInputStream();
            return JSONParse(input);
        }
        return null;
    }
    private static List<Info> JSONParse(InputStream input) throws Exception {
        List<Info> list = new ArrayList<Info> ();
        byte[] data = StreamTool.read(input);
        String stringInfo = new String(data);
        JSONArray jsonArray = new JSONArray(stringInfo);
        for(int i = 0;i<jsonArray.length();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Info info = new Info(jsonObject.getInt("id"),
                                 jsonObject.getString("title"),
                                 jsonObject.getInt("age"));
            list.add(info);
        }
        return list;
    }
}


StreamTool.java

package org.zyh.jsontolistvew;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
    public static byte[] read(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        if((len=inStream.read(buffer))!=1){
            outStream.write(buffer,0,len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}


MainActivity.java

package org.zyh.jsontolistvew;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
    protected static final int ADD_ADPATER = 1;
    private ListView listView ;
    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg){
            if(msg.what == ADD_ADPATER){
            SimpleAdapter adpater = (SimpleAdapter) msg.obj;
            listView.setAdapter(adpater);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
                                                                                     
        listView = (ListView) this.findViewById(R.id.listView);
                                                                                     
        new Thread(){
            public void run(){
                try{
                    List<Info> list = InfoService.getLastInfo();     
                    List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>();
                    for(Info info : list){
                        HashMap<String,Object> item = new HashMap<String,Object>();
                        item.put("id", info.getId());
                        item.put("name", info.getName());
                        item.put("age", info.getAge());
                        data.add(item);
                    }
                                                                                                 
                    SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data, R.layout.item, new String[]{"name","age"}, new int[]{R.id.name,R.id.age});
                    Message msg = new Message();
                    msg.what = ADD_ADPATER;
                    msg.obj = adapter;
                    handler.sendMessage(msg);
                                                                                                 
                }catch(Exception e){
                    e.getStackTrace();
                }
            }
        }.start();     
    }
}


最后别忘了在AnaroidManifest.xml中加入Internet权限<uses-permission andriod:name="android.permission.INTERNET">

效果如如下

android使用Thread实现json数据的传递,并且使用ListView显示,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。