主要练习一下获取网络数据和解析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. [ActionScript 3.0] PrintJob打印功能

    package { import flash.display.Bitmap; import flash.display.Sprite; import flash.events.MouseEvent; ...

  2. [AIR] 检测移动设备运动

    Accelerometer 类根据由设备的运动传感器检测的活动调度事件.此数据表示设备的位置或沿三维轴的移动.当设备移动时,传感器会检测到此移动并返回加速数据.Accelerometer 类提供了各种 ...

  3. P3879 [TJOI2010]阅读理解 题解

    P3879 [TJOI2010]阅读理解 题解 题目描述 英语老师留了N篇阅读理解作业,但是每篇英文短文都有很多生词需要查字典,为了节约时间,现在要做个统计,算一算某些生词都在哪几篇短文中出现过. 输 ...

  4. Android Fragment实现微信底部导航

    1.XML布局 (1)主界面 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout x ...

  5. [原创]SSH密钥访问Git仓库配置

    SSH密钥并非为了解决拉取git仓库代码时,需要频繁输入密码的问题. SSH是一种比较安全的协议,可以用来免去远程登录Linux等服务器时需要输入密码的繁琐过程. 命令: ssh user@serve ...

  6. 项目中git的使用

    通常一个项目的开发周期相对较长,为了便于对过程中的项目版本进行管理,以及方便多人合作进行开发,常需要使用到版本管理控制软件,本篇介绍常用的版本控制器git,记之共享. 一.git是什么?有何特点? 用 ...

  7. orange1

  8. js map 、filter 、forEach 、every、some 的用法

    1.map 首先map 就是将原数组 映射成 新的数组: 其次map 有返回值 2.filter 对数组中的每个元素都执行一次指定的函数(callback),并且创建一个新的数组,该数组元素是所有回调 ...

  9. 项目中遇到的bug、问题总结

    1. Cannot set property 'captcha' of undefined 在node项目中使用svg-captcha生成验证码报错 captcha的代码,这里有一个session.c ...

  10. 线程局部存储空间 pthread_key_t、__thread 即 ThreadLocal

    https://www.jianshu.com/p/495ea7ce649b?utm_source=oschina-app 该博客还未学习完  还有   pthread_key_t    Thread ...