Android中Json数据解析,Thread+Handler ,SimpleAdapter使用小案例

1.本代码中的数据是由服务器提供。Json数据解析请参考 http://blog.csdn.net/suren__123/article/details/6938547 。

布局文件十分简单,主要用于小测试,就一份listview控件。

代码如下:

package com.sb.sbbimproject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class PendingItemsNewActivity extends Activity {
	protected static final String TAG ="PendingItemsNewActivity";
	private String path="http://192.168.31.201:81/JK_Ser/api/Workflow/GetWorkflowList?ProjectId=2";
    private   final  List<Map<String, String>> lst = new ArrayList<Map<String, String>>();  
    private  ListView  lv_newpending;
	private SimpleAdapter   adapter;
	private    Handler   handler=new Handler(){

		public void handleMessage(Message msg) {
			switch(msg.what){
			
			case 1:
		Log.i(TAG, "解析成功");
		
		Log.i(TAG, lst.toString());	
		
   	     adapter.notifyDataSetChanged();
 
				break;
				
			case 2:
		    Log.i(TAG, "解析失败请检查网络");
			break;
			}
		}
		
	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.waite_progress_new);
		lv_newpending=(ListView) findViewById(R.id.lv_newpending);	
		adapter=new  SimpleAdapter(this, lst, android.R.layout.simple_expandable_list_item_1, new String[]{"Name"}, new int[]{android.R.id.text1});
		lv_newpending.setAdapter(adapter);

		try {
			getJSONObject(path);
		
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
	}
	

	/**
	 * 解析json数据
	 * @param path
	 * @return
	 * @throws Exception
	
	 */
	    public  void getJSONObject( final String path) throws Exception {  
	    	
	   
	    	
	    	 new Thread(){
	    		 
	    		public void run() {
	    			
	    			Message msg=Message.obtain();
	    			
	    	        try {
						Map<String, String> map = null;  
						URL url = new URL(path);  
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.  
						conn.setConnectTimeout(10 * 1000);   // 单位是毫秒,设置超时时间为5秒  
						conn.setRequestMethod("GET");        
						
						// HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET  
						if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败  
						    InputStream is = conn.getInputStream(); // 获取输入流  
						    byte[] data = readStream(is);   // 把输入流转换成字符数组  
						    String json = new String(data);// 把字符数组转换成字符串  
		    
		    
	        //数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}  
	        JSONObject jsonObject=new JSONObject(json);     //返回的数据形式是一个Object类型,所以可以直接转换成一个Object  
	        Boolean success=jsonObject.getBoolean("success");  
	        Log.i(TAG,  " | success:" + success);   //测试数据  
	          
	        JSONArray jsonArray = jsonObject.getJSONArray("data");//里面有一个数组数据,可以用getJSONArray获取数组  
	        for (int i = 0; i < jsonArray.length(); i++) {  
						JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象
						
						String ID=item.getString("ID");  // 获取对象对应的值  
						String Name = item.getString("Name");  

						map = new HashMap<String, String>(); // 存放到MAP里面  
						map.put("ID", ID);  
						map.put("Name", Name);  
						lst.add(map);  
						
						msg.what=1;
						
					
	        }
						
 		}
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						msg.what=2;	
					} catch (ProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    	        finally{
	    	        
	    	        handler.sendMessage(msg);
	    	      
	    	        
	    	           
	    	        }
	    	 }	    	 
	    	 
	    	 }.start();
	    	 
	    	 
	    	
	    	 
	}	 	    
	 /** 
     * 把输入流转换成字符数组 
     * @param inputStream   输入流 
     * @return  字符数组 
     * @throws Exception 
     */  
    public static byte[] readStream(InputStream inputStream) throws Exception {  
        ByteArrayOutputStream bout = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while ((len = inputStream.read(buffer)) != -1) {  
            bout.write(buffer, 0, len);  
        }  
        bout.close();  
        inputStream.close();   
       return bout.toByteArray();  
    }  
    
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	
    	super.onResume();
    }
}
说明: UI只能在主线程中进行进行修改有两种方式,一种是在Handler中进行修改,另外一种如下:

 MainActivity.this.runOnUiThread(new Runnable(){

		@Override
		public void run() {
								
		//	tv.setText(json);
																	
	}});


在向浏览器发送请求的时候,有时候会需要输入参数的情况,下面的代码,和上面的代码有些类似,只不过添加了两个参数:name和pwd.  如果想写一个登陆功能可参考

http://blog.csdn.net/redarmy_chen/article/details/26860769 。

 /**
     * 获取用户的uid
     * @param path
     */
    
    public void   getData( final String path){
    	
    	 new Thread(){
    		 
	    		public void run() {
	    			
	    			Message msg=Message.obtain();
	    			
	    			try {
						URL url = new URL(path);  
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据. 						
						conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒  	
						 conn.setDoOutput(true);      //设置可以写如数据
						  conn.setDoInput(true);   //设置可以读出数据
						conn.setRequestMethod("POST");
						  // 传递的数据  
			            String Data = "name=" + URLEncoder.encode("admin", "UTF-8")  
			                    + "&pwd=" + URLEncoder.encode("123", "UTF-8");  
			            
			          //获取输出流  
			            OutputStream os = conn.getOutputStream();  
			            os.write(Data.getBytes());  
			            os.flush();  
			            		
						if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败  
						    InputStream is = conn.getInputStream(); // 获取输入流  
						    byte[] data = readStream(is);   // 把输入流转换成字符数组  
		//				    String json = new String(data);// 把字符数组转换成字符串  
						    json=new String(data);
						    
							msg.what=1;
							
							
							 MainActivity.this.runOnUiThread(new Runnable(){

								@Override
								public void run() {
								
									tv.setText(json);
																	
								}});
							
						}
						
						
						
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						msg.what=2;	
						e.printStackTrace();
					} catch (ProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
	    			  finally{
	  	    	        
	  	    	        handler.sendMessage(msg);
	  	    	           
	  	    	        }	    			
	    		}
    	 }.start();
    	
说明:readStream参照上面代码即可。在此使用runOnUiThread 进行UI更新。





       

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值