[android] 天气app布局练习(四)
主要练习一下获取网络数据和解析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布局练习(四)的更多相关文章
- [android] 天气app布局练习(二)
主要练习一下GridView MainActivity.java package com.example.weatherreport; import java.util.ArrayList; impo ...
- [android] 天气app布局练习(三)
主要练习LinearLayout和layout_weight属性 <RelativeLayout xmlns:android="http://schemas.android.com/a ...
- [android] 天气app布局练习
主要练习一下RelativeLayout和LinearLayout <RelativeLayout xmlns:android="http://schemas.android.com/ ...
- 制作一个功能丰富的Android天气App
简易天气是一个基于和风天气数据采用MD设计的Android天气App.目前的版本采用传统的MVC模式构建.通过丰富多彩的页面为用户提供日常所需的天气资讯. 项目说明 项目放在github上面 地址是: ...
- [Android]天气App 2 项目搭建
对于天气App,为了简化一些功能,暂时模仿MUUI系统提供的那个App. 本项目需要引入本人经常使用的一个工具库DroidTool,这个是本人根据工作中,收集到一些工具类,下载地址. ...
- [Android]天气App 3 网络数据的请求和Json解析
Android客户端开发,不仅仅是在Android端开发,还需要有相应的后台服务支持,否则的话,客户端的数据就只能放到本地自己做处理.我认为的原生态的App就是对应服务端的Client.他能像浏览 ...
- [Android]天气App 1
闲赋在家,无事可做就想着做点东西,于是乎把玩手机,我最常用的就是看天气,基本上我每天起来第一件事就是看天气,哈哈,用别人的这么爽,为什么不自己整一个关于天气的应用呢,墨迹天气.小米系统自带的天气.ya ...
- DB天气app冲刺第四天
今天卡壳了 做得很慢.. 明天继续 换一种思路试一下吧..
- Android学习系列(5)--App布局初探之简单模型
人类科技的进步源自探索,探索来自于发现本原,当然App布局没这么先进,本文也只是一个归类总结.这篇文章是Android开发人员的必备知识,是我特别为大家整理和总结的,不求完美,但是有用. Androi ...
随机推荐
- libz.dylib框架怎么导入
1.General下 2.点击+号在弹出的对话框选择addother 3.在弹出的对话框中输入"cmd"+"shift"+"g" 输入/us ...
- POJ 1330 Nearest Common Ancestors(lca)
POJ 1330 Nearest Common Ancestors A rooted tree is a well-known data structure in computer science a ...
- 重置root密码
一. ubuntu忘记密码解决方法 1. 开机按shift 2. 选择高级选项,进入后选择恢复模式(不要按回车),按e进入编辑模式 3. 修改linux命令中的recovery nomodest 为 ...
- Angular 2 中的 ViewChild 和 ViewChildren
https://segmentfault.com/a/1190000008695459 ViewChild ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素.视图查询在 ngAfter ...
- 976 AlvinZH想回家(背包DP大作战T)
976 AlvinZH想回家 思路 如果在第i小时有一些飞机延误,那么一架飞机的c值越大,这一小时产生的损失也越大.而使这一小时产生的损失尽可能的小并不会导致接下来时间产生的损失增大.因此应当每一小时 ...
- supervisor使用小记
最近使用supervisor部署爬虫,百度了很多,磕磕绊绊自己也算是用起来了,以下是整理的使用情况. 第一步: 下载安装supervisor 使用的ubuntu16.04,直接 sudo apt-ge ...
- python函数超时情况应对总结
最近处理一个线程中的函数超时问题. 函数里面有一个地方可能会卡死,我们需要去判断这个是不是卡死了,并做出相应的应对方案. 最开始想的是在函数上增加一个装饰器,使其在超时时抛出异常,然后在其他地方捕获这 ...
- (转)Go语言核心36讲之Go语言入门基础知识
- Quartz .net 禁止并行触发
DisallowConcurrentExecution 禁用同步执行防止一个job 同一时间执行多次. [DisallowConcurrentExecution] public class Order ...
- 《The Python Standard Library》——http模块阅读笔记3
http.cookies — HTTP state management http.cookies模块定义了一系列类来抽象cookies这个概念,一个HTTP状态管理机制.该模块支持string-on ...