Android中获取SQL Server中的数据

1、创建一般处理程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;

 

namespace service
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class MobileService : IHttpHandler
    {
       
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);
            //创建一个根节点(一级)
            XmlElement root = doc.CreateElement("First");
            doc.AppendChild(root);
            //创建节点(二级)
            XmlNode node = doc.CreateElement("Seconde");
            //创建节点(三级)
            XmlElement element1 = doc.CreateElement("Third1");
            element1.SetAttribute("Name", name);
            element1.SetAttribute("ID", "665");
            element1.InnerText = "Sam Comment";
            node.AppendChild(element1);

            XmlElement element2 = doc.CreateElement("Third2");
            element2.SetAttribute("Name", "Round");
            element2.SetAttribute("ID", "678");
            element2.InnerText = "Round Comment";
            node.AppendChild(element2);

            root.AppendChild(node);

            context.Response.Write(doc.InnerXml);
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}

2、Java程序

package cn.itcast.service;

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 org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import cn.itcast.domain.Video;
import cn.itcast.utils.StreamTool;

public class VideoService {
 /**
  * 从服务器获取最新的视频资讯
  * @return
  * @throws Throwable
  */
 public static List<Video> getLastJSONVideos() throws Throwable{
  ArrayList<Video> videos = new ArrayList<Video>();
  String path = "http://192.168.1.10:8080/videoweb/video/list.do?format=json";
  URL url = new URL(path);
  HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  conn.setConnectTimeout(5*1000);
  conn.setRequestMethod("GET");
  InputStream inStream = conn.getInputStream(); 
  byte[] data = StreamTool.readInputStream(inStream);
  String json = new String(data);
  JSONArray array = new JSONArray(json);
  for(int i = 0 ; i < array.length() ; i++){
   JSONObject item = array.getJSONObject(i);
   Video video = new Video(item.getInt("id"), item.getString("title"), item.getInt("timelength"));
   videos.add(video);
  }
  return videos;
 }
 /**
  * 从服务器获取最新的视频资讯
  * @return
  * @throws Throwable
  */
 public static List<Video> getLastVideos() throws Throwable{
  String path = "http://192.168.1.10:8080/videoweb/video/list.do";
  URL url = new URL(path);
  HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  conn.setConnectTimeout(5*1000);
  conn.setRequestMethod("GET");
  InputStream inStream = conn.getInputStream();  
  return parseXML(inStream);
 }

 private static List<Video> parseXML(InputStream inStream) throws Exception{
  Video video = null;
  List<Video> videos = null;
  XmlPullParser pullParser = Xml.newPullParser();
  pullParser.setInput(inStream, "UTF-8");
  int event = pullParser.getEventType();//触发第一个事件
  while(event!=XmlPullParser.END_DOCUMENT){
   switch (event) {
   case XmlPullParser.START_DOCUMENT:
    videos = new ArrayList<Video>();
    break;
   case XmlPullParser.START_TAG:
    if("video".equals(pullParser.getName())){
     int id = new Integer(pullParser.getAttributeValue(0));
     video = new Video();
     video.setId(id);
    }
    if(video!=null){
     if("title".equals(pullParser.getName())){
      video.setTitle(pullParser.nextText());
     }
     if("timelength".equals(pullParser.getName())){
      video.setTimelength(new Integer(pullParser.nextText()));
     }
    }
    break;
    
   case XmlPullParser.END_TAG:
    if("video".equals(pullParser.getName())){
     videos.add(video);
     video = null;
    }
    break;
   }
   event = pullParser.next();
  }
  return videos;
 }
}

3、

package cn.itcast.domain;
/**
 * 视频资讯
 */
public class Video {
 private Integer id;
 private String title;
 private Integer timelength;
 
 public Video(){}
 
 public Video(Integer id, String title, Integer timelength) {
  this.id = id;
  this.title = title;
  this.timelength = timelength;
 }
 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 getTimelength() {
  return timelength;
 }
 public void setTimelength(Integer timelength) {
  this.timelength = timelength;
 }

 @Override
 public String toString() {
  return "Video [id=" + id + ", timelength=" + timelength + ", title="
    + title + "]";
 }
 
}

4、

package cn.itcast.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {
 /**
  * 从输入流中读取数据
  * @param inStream
  * @return
  * @throws Exception
  */
 public static byte[] readInputStream(InputStream inStream) throws Exception{
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while( (len = inStream.read(buffer)) !=-1 ){
   outStream.write(buffer, 0, len);
  }
  byte[] data = outStream.toByteArray();//网页的二进制数据
  outStream.close();
  inStream.close();
  return data;
 }
}

5、

package cn.itcast.videonews;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.itcast.domain.Video;
import cn.itcast.service.VideoService;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        try {
   List<Video> videos = VideoService.getLastJSONVideos();//获取最新视频资讯
   ListView listView = (ListView)this.findViewById(R.id.listView);
   List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
   for(Video video : videos){
    HashMap<String, Object> item = new HashMap<String, Object>();
    item.put("title", video.getTitle());
    item.put("timelength", "时长:"+video.getTimelength());
    item.put("id", video.getId());
    data.add(item);
   }
   SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
     new String[]{"title","timelength"}, new int[]{R.id.title, R.id.timelength});
   listView.setAdapter(adapter);
  } catch (Throwable e) {
   Log.e(TAG, e.toString());
   Toast.makeText(this, R.string.error, 1).show();
  }
    }
}

6、

package cn.itcast.videonews;

import java.util.List;

import cn.itcast.domain.Video;
import cn.itcast.service.VideoService;
import android.test.AndroidTestCase;
import android.util.Log;

public class VideoServiceTest extends AndroidTestCase {
 private static final String TAG = "VideoServiceTest";
 
 public void testGetLastVideos() throws Throwable{
  List<Video> videos = VideoService.getLastVideos();
  for(Video video : videos){
   Log.i(TAG, video.toString());
  }
 }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值