主要练习一下获取网络数据和解析xml

MainActivity.java

package com.example.weatherreport;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView; import com.example.weatherreport.contants.ApiContants;
import com.example.weatherreport.domain.Weather;
import com.example.weatherreport.net.HttpListener;
import com.example.weatherreport.net.HttpUtil; public class MainActivity extends Activity {
private GridView gv_airs;
private TextView tv_city;
private TextView tv_number;
private TextView tv_rain;
private TextView tv_cloth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gv_airs = (GridView) findViewById(R.id.gv_airs);
tv_city=(TextView) findViewById(R.id.tv_city);
tv_number=(TextView) findViewById(R.id.tv_number);
tv_rain=(TextView) findViewById(R.id.tv_rain);
tv_cloth=(TextView) findViewById(R.id.tv_cloth);
setViewData();
makeGridView();
} /**
* 设置界面数据
*/
private void setViewData() {
String city = null;
try {
city = URLEncoder.encode("北京", "gb2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpUtil.get(ApiContants.WEATHER_URL+"?city="+city+"&password=DJOYnieT8234jlsK&day=0", new HttpListener() {
@Override
public void onSuccess(String result) {
Weather weather=(Weather) HttpUtil.xml2object(result);
setViewWeather(weather); } @Override
public void onError(String result) {
System.out.println(result);
}
}); } protected void setViewWeather(Weather weather) {
tv_city.setText(weather.getCity());
tv_number.setText(weather.getHot());
tv_rain.setText(weather.getRain());
tv_cloth.setText(weather.getCloth());
System.out.println(weather.toString());
} /**
* 组装GridView
*/
private void makeGridView() {
List<Map<String, String>> data = new ArrayList<>();
Map<String, String> item = null;
item = new HashMap<>();
item.put("title", "83");
item.put("desc", "湿度(%)");
data.add(item); item = new HashMap<>();
item.put("title", "11.3");
item.put("desc", "可见度(km)");
data.add(item); item = new HashMap<>();
item.put("title", "2级");
item.put("desc", "东南风");
data.add(item); item = new HashMap<>();
item.put("title", "最弱");
item.put("desc", "紫外线");
data.add(item); item = new HashMap<>();
item.put("title", "1005.5");
item.put("desc", "气压(mb)");
data.add(item); item = new HashMap<>();
item.put("title", "22.4");
item.put("desc", "体感");
data.add(item); SimpleAdapter adapter = new SimpleAdapter(this, data,
R.layout.main_grid_item, new String[] { "title", "desc" },
new int[] { R.id.tv_title, R.id.tv_desc });
gv_airs.setAdapter(adapter);
}
}

HttpUtil.java

package com.example.weatherreport.net;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL; import org.xmlpull.v1.XmlPullParser; import android.os.Handler;
import android.os.Message;
import android.util.Xml; import com.example.weatherreport.domain.Weather; public class HttpUtil {
public static final int SUCCESS = 1;
public static final int ERROR = 2; /**
* 获取get数据
*
* @param apiUrl
*/
public static void get(final String apiUrl, final HttpListener listener) {
final Handler handler = new HttpHandler(listener);
new Thread(new Runnable() { @Override
public void run() {
Message msg = new Message();
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000); int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
String result = readInputStream(is);
msg.what = SUCCESS;
msg.obj = result;
handler.sendMessage(msg); } else {
listener.onError(String.valueOf(code));
}
} catch (Exception e) {
e.printStackTrace();
msg.what = ERROR;
msg.obj = "网络异常";
handler.sendMessage(msg);
}
}
}).start(); } /**
* 读取输入流
*
* @param is
* @return
*/
public static String readInputStream(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
try {
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
byte[] res = baos.toByteArray();
return new String(res);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 解析xml
*
* @return
*/
public static Object xml2object(String xmlString) {
Weather weather = new Weather();
try {
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(new StringReader(xmlString));
int event = pullParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
String tagName = pullParser.getName();
if (tagName.equals("Weather") || tagName.equals("Profiles")) {
} else {
String tagValue = pullParser.nextText();
System.out.println(tagName + ":" + tagValue);
if (tagName.equals("status1")) {
weather.setRain(tagValue);
}
if (tagName.equals("tgd1")) {
weather.setHot(tagValue);
}
if (tagName.equals("chy_l")) {
weather.setCloth(tagValue);
}
if (tagName.equals("city")) {
weather.setCity(tagValue);
}
}
break;
case XmlPullParser.END_TAG:
default:
break;
}
event = pullParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return weather;
} }
/**
*
* 位于主线程的Handler
* @author taoshihan
*
*/
class HttpHandler extends Handler {
private HttpListener listener;
public HttpHandler(HttpListener listener) {
this.listener=listener;
} @Override
public void handleMessage(Message msg) {
int flag=msg.what;
String res=(String)msg.obj;
if (flag==HttpUtil.SUCCESS) {
listener.onSuccess(res);
}else{
listener.onError(res);
}
}
}

HttpListener.java

package com.example.weatherreport.net;

public interface HttpListener {
public void onSuccess(String result);
public void onError(String result);
}

[android] 天气app布局练习(四)的更多相关文章

  1. [android] 天气app布局练习(二)

    主要练习一下GridView MainActivity.java package com.example.weatherreport; import java.util.ArrayList; impo ...

  2. [android] 天气app布局练习(三)

    主要练习LinearLayout和layout_weight属性 <RelativeLayout xmlns:android="http://schemas.android.com/a ...

  3. [android] 天气app布局练习

    主要练习一下RelativeLayout和LinearLayout <RelativeLayout xmlns:android="http://schemas.android.com/ ...

  4. 制作一个功能丰富的Android天气App

    简易天气是一个基于和风天气数据采用MD设计的Android天气App.目前的版本采用传统的MVC模式构建.通过丰富多彩的页面为用户提供日常所需的天气资讯. 项目说明 项目放在github上面 地址是: ...

  5. [Android]天气App 2 项目搭建

       对于天气App,为了简化一些功能,暂时模仿MUUI系统提供的那个App.    本项目需要引入本人经常使用的一个工具库DroidTool,这个是本人根据工作中,收集到一些工具类,下载地址.    ...

  6. [Android]天气App 3 网络数据的请求和Json解析

      Android客户端开发,不仅仅是在Android端开发,还需要有相应的后台服务支持,否则的话,客户端的数据就只能放到本地自己做处理.我认为的原生态的App就是对应服务端的Client.他能像浏览 ...

  7. [Android]天气App 1

    闲赋在家,无事可做就想着做点东西,于是乎把玩手机,我最常用的就是看天气,基本上我每天起来第一件事就是看天气,哈哈,用别人的这么爽,为什么不自己整一个关于天气的应用呢,墨迹天气.小米系统自带的天气.ya ...

  8. DB天气app冲刺第四天

    今天卡壳了 做得很慢.. 明天继续 换一种思路试一下吧..

  9. Android学习系列(5)--App布局初探之简单模型

    人类科技的进步源自探索,探索来自于发现本原,当然App布局没这么先进,本文也只是一个归类总结.这篇文章是Android开发人员的必备知识,是我特别为大家整理和总结的,不求完美,但是有用. Androi ...

随机推荐

  1. Tiled结合Unity实现瓦片地图——Tiled2Unity篇

    本系列文章由Aimar_Johnny编写,欢迎转载,转载请标明出处,谢谢. http://blog.csdn.net/lzhq1982/article/details/75356478 前段时间应公司 ...

  2. Django-03视图层

    5.1 视图函数 一个视图函数,简称视图,是一个简单的Python 函数,它接受Web请求并且返回Web响应.响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片 ...

  3. javascript显示年月日时间代码显示电脑时间

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. [ActionScript 3.0] 翻牌效果,运用语法rotationY,PerspectiveProjection

    package { import com.tweener.transitions.Tweener; import flash.display.Bitmap; import flash.display. ...

  5. javap -- Java 类文件解析器

    参考文档 http://blog.chinaunix.net/uid-692788-id-2681132.html http://docs.oracle.com/javase/7/docs/techn ...

  6. map集合根据value找key,默认取第一个key

    private static String getKey(Map<String,String> map,String value){ String key=""; fo ...

  7. nginx高性能WEB服务器系列之九--nginx运维故障日常解决方案

    nginx系列友情链接:nginx高性能WEB服务器系列之一简介及安装https://www.cnblogs.com/maxtgood/p/9597596.htmlnginx高性能WEB服务器系列之二 ...

  8. dw cs6设置字体样式

    1 编辑->首选参数->字体 改代码试图的字体和大小.点确定即可.

  9. 863公司 linux软测题

    1.浏览目录命令 2.浏览文件命令 3.目录操作命令 4.文件操作命令 5.进程管理命令

  10. Regini命令的使用和参数讲解

    Regini程序操作系统自带的,从XP开始就有,主要是用于修改注册表及注册表权限.我们就从这两方面介绍regini的用法.Regini必须要指定操作脚本,也就是,提前将你要操作的内容写在一个文本文件中 ...