主要练习一下获取网络数据和解析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. bzoj1050旅行

    题目链接 其实没有辣么难, 暴力枚举最小边是哪条边,然后每次跑一边最小生成树, 当$s,t$刚好联通时最后加的边的权值就是当前的最大边最小的情况 然后判断一下,更新答案就好 /************ ...

  2. luogu5282 【模板】快速阶乘算法

    由于巨佬 shadowice1984 卡时限,本代码已经 T 请不要粘上去交 退役之后再写一个常数小的多项式取模吧 一句话题意:NP问题,求N!%P 吐槽:出题人太毒瘤...必须写任意模数NTT,而且 ...

  3. css 移动端图片等比显示处理

    第一次写博文,心情有点小小的激动~~~~~ 刚开始做移动端项目的时候遇到了一些优化的问题,比如,打开网页在2g或者3g的情况下加载网页,刚开始渲染的时候,遇到图片文件未请求,图片的高度会为0,当然,如 ...

  4. CSS3 文本溢出问题

    一.单行: 效果: 实现这各效果必须要加上: text-overflow: ellipsis; /*文本溢出*/ overflow: hidden; /*配合使用:溢出隐藏*/ white-space ...

  5. (STM32F4) Timer Compare mode 操作

    Timer 比較模式(compare) 具體會用在哪種狀況目前還沒有這種經驗,但Compare有配置功能pin想必有應用會用到這個模式 從Function Block來看比較模式比基本Timer多了比 ...

  6. springcloud(二)-最简单的实战

    技术储备 Spring cloud并不是面向零基础开发人员,它有一定的学习曲线. 语言基础:spring cloud是一个基于Java语言的工具套件,所以学习它需要一定的Java基础.当然,sprin ...

  7. c#中的引用类型和值类型

    一,c#中的值类型和引用类型 众所周知在c#中有两种基本类型,它们分别是值类型和引用类型:而每种类型都可以细分为如下类型: 什么是值类型和引用类型 什么是值类型: 进一步研究文档,你会发现所有的结构都 ...

  8. java实现图片文字识别的两种方法

    一.使用tesseract-ocr 1.    https://github.com/tesseract-ocr/tesseract/wiki上下载安装包安装和简体中文训练文件 window64位安装 ...

  9. 问题诊断神器arthas

    https://github.com/alibaba/arthas 镜像地址 https://gitee.com/arthas/arthas OGNL https://commons.apache.o ...

  10. vue html页面打印功能vue-print

    vue项目中,HTML页面打印功能.在项目中,有时需要打印页面的表格, 在网上找了一个打印组件vue-print-nb 使用方式 安装 npm install vue-print-nb --save ...