Chinaunix首页 | 论坛 | 博客
  • 博客访问: 79963
  • 博文数量: 13
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 247
  • 用 户 组: 普通用户
  • 注册时间: 2014-01-02 18:05
文章分类
文章存档

2014年(13)

分类: Android平台

2014-03-06 17:06:56

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

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

一、建立Web Service

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

wKioL1MXDPjxkWA1AAM77Zu3ZiI767.jpgwKiom1MXDUGCAHOkAAFDyKUUBHA753.jpg

选上自动创建xml文件。

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

web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    


  MyServer
 
    MyServer
    MyServer
    org.zyh.server.xml.MyServer
 

 
    MyServer
    /MyServer
 

 
    index.html
    index.htm
    index.jsp
 




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

MyService.java
1
2
3
4
5
    
package org.zyh.server.service;
import java.util.List;
public interface MyService {
    public List getLastNews();
}


MyServiceBean.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    
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 getLastNews() {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
        List 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    
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 = 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
1
2
    
<%@ 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
1
2
3
4
5
6
7
8
9
10
11
12
    

    xmlns:tools=""
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
            android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView" />



item.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    

    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
            android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        />
            android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/age"
        />



Info.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    
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 getLastInfo() throws Exception{
                                                                                                                         
        String path = "";
        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 JSONParse(InputStream input) throws Exception {
        List list = new ArrayList ();
        byte[] data = StreamTool.read(input);
        String stringInfo = new String(data);
        JSONArray jsonArray = new JSONArray(stringInfo);
        for(int i = 0;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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    
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 list = InfoService.getLastInfo();    
                    List> data = new ArrayList>();
                    for(Info info : list){
                        HashMap item = new HashMap();
                        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权限

效果如如下

wKioL1MYHJugIrdjAAEBmfDjykw748.jpg
阅读(4965) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~