网上在线获取天气数据
2018-01-15 10:09
363 查看
package com.animee.test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Administrator on 2018/1/13. */ public class HttpUtils { public static String getStringContent(String path){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); InputStream is = conn.getInputStream(); byte[]buf = new byte[1024]; int hasRead = 0; while((hasRead = is.read(buf))!=-1){ baos.write(buf,0,hasRead); } } catch (IOException e) { e.printStackTrace(); } return baos.toString(); } }
package com.animee.test; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.util.ArrayList; import java.util.List; /** * 完成 * 需要注意的: * 1.关于xml解析,并没有固定的规范,在判断时大家要按照便签的名称进行分析,然后依次解析 * 2.关于解析类的封装,没有json数据类型的gsonformat的封装方式,但是大家要根据界面的需要进行封装数据, * 看界面需要什么,就把什么添加到解析类当中。 * 3.步骤 : * 1.布局---》找到控件 * 2.写解析生成的bean类,作为数据源 * 3.写数据源(空的),写适配器 * 4.设置适配器 * 5.网络请求数据 * 6,开始解析 * 7.把解析后的数据,添加到原有的数据源当中 * 8.通知适配器更新数据。 * * */ public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager vp; // 接口 public String bjUrl = "http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=xml&ak=mXBIDrvTOwwmYaTtN03Lo0j2"; public String syUrl = "http://api.map.baidu.com/telematics/v3/weather?location=%E6%B2%88%E9%98%B3&output=xml&ak=mXBIDrvTOwwmYaTtN03Lo0j2"; public String hzUrl = "http://api.map.baidu.com/telematics/v3/weather?location=%E4%B8%8A%E6%B5%B7&output=xml&ak=mXBIDrvTOwwmYaTtN03Lo0j2"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { tabLayout = (TabLayout) findViewById(R.id.tablayout); vp = (ViewPager) findViewById(R.id.vp); initPager(); } private void initPager() { List<Fragment>fragments = new ArrayList<>(); String url[] = {bjUrl,syUrl,hzUrl}; List<String>titleList = new ArrayList<>(); titleList.add("北京"); titleList.add("沈阳"); titleList.add("杭州"); for (int i = 0; i < 3; i++) { Fragment frag = new WeatherFragment(); Bundle bundle = new Bundle(); bundle.putString("url",url[i]); frag.setArguments(bundle); fragments.add(frag); } VPAdapter adapter = new VPAdapter(getSupportFragmentManager(), fragments, titleList); vp.setAdapter(adapter); // 使TabLayout和ViewPager产生关联 tabLayout.setupWithViewPager(vp); } }
package com.animee.test; import android.util.Log; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2018/1/13. */ public class ParseXML { public static String TAG = "ParseXML"; public static WeatherBean readXML(String content){ WeatherBean bean = new WeatherBean(); List<WeatherBean.WeatherDate> weatherList = new ArrayList<>(); List<WeatherBean.Zhishu> zhishuList = new ArrayList<>(); bean.setWeather_dateList(weatherList); bean.setZhishuList(zhishuList); // 开始解析 try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser pullParser = factory.newPullParser(); ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes()); pullParser.setInput(bais,"utf-8"); int code = pullParser.getEventType(); WeatherBean.WeatherDate weatherDate = null; WeatherBean.Zhishu zhishu = null; while (code != XmlPullParser.END_DOCUMENT) { String name = pullParser.getName(); Log.i(TAG, "readXML: ==name==="+name); switch (code) { case XmlPullParser.START_TAG: if (name.equals("date")) { Log.i(TAG, "readXML: ==date=创建对象了="); weatherDate = new WeatherBean.WeatherDate(); weatherDate.setDate(pullParser.nextText()); }else if (name.equals("dayPictureUrl")) { weatherDate.setDayPictureUrl(pullParser.nextText()); }else if (name.equals("nightPictureUrl")) { weatherDate.setNightPictureUrl(pullParser.nextText()); }else if (name.equals("weather")) { weatherDate.setWeather(pullParser.nextText()); }else if (name.equals("wind")) { weatherDate.setWind(pullParser.nextText()); }else if (name.equals("temperature")) { weatherDate.setTemperature(pullParser.nextText()); weatherList.add(weatherDate); }else if (name.equals("title")) { zhishu = new WeatherBean.Zhishu(); zhishu.setTitle(pullParser.nextText()); }else if (name.equals("zs")) { zhishu.setZs(pullParser.nextText()); }else if (name.equals("tipt")) { zhishu.setTipt(pullParser.nextText()); }else if (name.equals("des")){ zhishu.setDes(pullParser.nextText()); zhishuList.add(zhishu); } break; case XmlPullParser.END_TAG: if (name.equals("temperature")) { Log.i(TAG, "readXML: ==添加到集合了=="); //没执行到? 没找到原因,但是换一种写法 // weatherList.add(weatherDate); }else if (name.equals("des")) { // zhishuList.add(zhishu); } break; } code = pullParser.next(); } } catch (XmlPullParserException e) { Log.i(TAG, "readXML: ====XmlPullParserException==="); e.printStackTrace(); } catch (IOException e) { Log.i(TAG, "readXML: =====IOException====="); e.printStackTrace(); } Log.i(TAG, "readXML: ===="+bean); return bean; } }
package com.animee.test; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.List; /** * Created by Administrator on 2018/1/13. */ public class VPAdapter extends FragmentPagerAdapter{ private List<Fragment>mDatas; private List<String>mTitleList; public VPAdapter(FragmentManager fm,List<Fragment>mDatas,List<String>mTitleList) { super(fm); this.mDatas = mDatas; this.mTitleList = mTitleList; } @Override public Fragment getItem(int position) { return mDatas.get(position); } @Override public int getCount() { return mDatas.size(); } @Override public CharSequence getPageTitle(int position) { return mTitleList.get(position); } }
package 4000 com.animee.test; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by Administrator on 2018/1/13. */ public class WeatherAdapter extends BaseAdapter{ private Context context; private List<WeatherBean.WeatherDate>mDatas; public WeatherAdapter(Context context, List<WeatherBean.WeatherDate> mDatas) { this.context = context; this.mDatas = mDatas; } @Override public int getCount() { return mDatas.size(); } @Override public Object getItem(int position) { return mDatas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { WeatherViewHolder holder = null; if (convertView==null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_sp,null); holder = new WeatherViewHolder(convertView); convertView.setTag(holder); }else{ holder = (WeatherViewHolder) convertView.getTag(); } WeatherBean.WeatherDate weatherDate = mDatas.get(position); holder.wenduTv.setText("温度:"+weatherDate.getTemperature()); holder.dateTv.setText(weatherDate.getDate()); holder.windTv.setText(weatherDate.getWind()); holder.weaherTv.setText("白天情况:"+weatherDate.getWeather()); Picasso.with(context).load(weatherDate.getDayPictureUrl()).into(holder.dayIv); Picasso.with(context).load(weatherDate.getNightPictureUrl()).into(holder.nightTv); return convertView; } class WeatherViewHolder{ TextView dateTv,wenduTv,windTv,weaherTv; ImageView dayIv,nightTv; public WeatherViewHolder(View view){ dateTv = (TextView) view.findViewById(R.id.sp_tv_date); wenduTv = (TextView) view.findViewById(R.id.sp_tv_wendu); windTv = (TextView) view.findViewById(R.id.sp_tv_fengxiang); weaherTv = (TextView) view.findViewById(R.id.sp_tv_day); dayIv = (ImageView) view.findViewById(R.id.sp_img_bt); nightTv = (ImageView) view.findViewById(R.id.sp_img_night); } } }
package com.animee.test; import java.util.List; /** * Created by Administrator on 2018/1/13. */ public class WeatherBean { private List<WeatherDate>weather_dateList; private List<Zhishu>zhishuList; public WeatherBean() { } public List<WeatherDate> getWeather_dateList() { return weather_dateList; } public void setWeather_dateList(List<WeatherDate> weather_dateList) { this.weather_dateList = weather_dateList; } public List<Zhishu> getZhishuList() { return zhishuList; } public void setZhishuList(List<Zhishu> zhishuList) { this.zhishuList = zhishuList; } @Override public String toString() { return "WeatherBean{" + "weather_dateList=" + weather_dateList + ", zhishuList=" + zhishuList + '}'; } public WeatherBean(List<WeatherDate> weather_dateList, List<Zhishu> zhishuList) { this.weather_dateList = weather_dateList; this.zhishuList = zhishuList; } public static class Zhishu{ private String title; private String zs; private String tipt; private String des; @Override public String toString() { return "Zhishu{" + "title='" + title + '\'' + ", zs='" + zs + '\'' + ", tipt='" + tipt + '\'' + ", des='" + des + '\'' + '}'; } public String getTitle() { return title; } public String getZs() { return zs; } public String getTipt() { return tipt; } public String getDes() { return des; } public Zhishu() { } public void setTitle(String title) { this.title = title; } public void setZs(String zs) { this.zs = zs; } public void setTipt(String tipt) { this.tipt = tipt; } public void setDes(String des) { this.des = des; } public Zhishu(String title, String zs, String tipt, String des) { this.title = title; this.zs = zs; this.tipt = tipt; this.des = des; } } public static class WeatherDate{ private String date; private String dayPictureUrl; private String nightPictureUrl; private String weather; private String wind; private String temperature; @Override public String toString() { return "WeatherDate{" + "date='" + date + '\'' + ", dayPictureUrl='" + dayPictureUrl + '\'' + ", nightPictureUrl='" + nightPictureUrl + '\'' + ", weather='" + weather + '\'' + ", wind='" + wind + '\'' + ", temperature='" + temperature + '\'' + '}'; } public WeatherDate() { } public WeatherDate(String date, String dayPictureUrl, String nightPictureUrl, String weather, String wind, String temperature) { this.date = date; this.dayPictureUrl = dayPictureUrl; this.nightPictureUrl = nightPictureUrl; this.weather = weather; this.wind = wind; this.temperature = temperature; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getDayPictureUrl() { return dayPictureUrl; } public void setDayPictureUrl(String dayPictureUrl) { this.dayPictureUrl = dayPictureUrl; } public String getNightPictureUrl() { return nightPictureUrl; } public void setNightPictureUrl(String nightPictureUrl) { this.nightPictureUrl = nightPictureUrl; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } public String getWind() { return wind; } public void setWind(String wind) { this.wind = wind; } public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } } }
package com.animee.test; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.Spinner; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class WeatherFragment extends Fragment { private String url; private ListView lv; private Spinner sp; private List<WeatherBean.WeatherDate> weatherList; private List<WeatherBean.Zhishu> zhishuList; private ZhishuAdapter zhishuAdapter; private WeatherAdapter weatherAdapter; private String TAG = "WeatherFragment"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_weather, container, false); Bundle bundle = getArguments(); url = bundle.getString("url"); initView(view); return view; } private void initView(View view) { lv = (ListView)view.findViewById(R.id.fragment_lv); View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.header_layout,null); lv.addHeaderView(headerView); sp = (Spinner) headerView.findViewById(R.id.header_sp); // 数据源: weatherList = new ArrayList<>(); zhishuList = new ArrayList<>(); zhishuAdapter = new ZhishuAdapter(getActivity(),zhishuList); lv.setAdapter(zhishuAdapter); weatherAdapter = new WeatherAdapter(getActivity(),weatherList); sp.setAdapter(weatherAdapter); loadData(url); } private void loadData(String url) { new AsyncTask<String,Void,String>(){ @Override protected String doInBackground(String... params) { String content = HttpUtils.getStringContent(params[0]); return content; } @Override protected void onPostExecute(String s) { // 判断数据,解析数据 if (s!=null&&!s.isEmpty()) { WeatherBean bean = ParseXML.readXML(s); Log.i(TAG, "onPostExecute:Weather_dateList().size =="+bean.getWeather_dateList().size()); weatherList.addAll(bean.getWeather_dateList()); weatherAdapter.notifyDataSetChanged(); Log.i(TAG, "onPostExecute: ZhishuList().size====="+bean.getZhishuList().size()); zhishuList.addAll(bean.getZhishuList()); zhishuAdapter.notifyDataSetChanged(); } } }.execute(url); } }
package com.animee.test; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; /** * Created by Administrator on 2018/1/13. */ public class ZhishuAdapter extends BaseAdapter { private Context context; private List<WeatherBean.Zhishu>mDatas; public ZhishuAdapter(Context context, List<WeatherBean.Zhishu> mDatas) { this.context = context; this.mDatas = mDatas; } @Override public int getCount() { return mDatas.size(); } @Override public Object getItem(int position) { return mDatas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ZhiShuViewHolder holder = null; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_lv,null); holder = new ZhiShuViewHolder(convertView); convertView.setTag(holder); }else{ holder = (ZhiShuViewHolder) convertView.getTag(); } WeatherBean.Zhishu zhishu = mDatas.get(position); holder.titletTv.setText(zhishu.getTitle()); holder.tiptTv.setText(zhishu.getTipt()); holder.zsTv.setText(zhishu.getZs()); holder.detailTv.setText(zhishu.getDes()); return convertView; } class ZhiShuViewHolder{ TextView titletTv,zsTv,tiptTv,detailTv; public ZhiShuViewHolder(View view){ titletTv = (TextView) view.findViewById(R.id.lv_tv1); zsTv = (TextView) view.findViewById(R.id.lv_tv3); tiptTv = (TextView) view.findViewById(R.id.lv_tv2); detailTv = (TextView) view.findViewById(R.id.lv_tv4); } } }
//布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.animee.test.MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
app:tabSelectedTextColor="@color/colorAccent"
app:tabIndicatorColor="@color/colorAccent"
app:tabIndicatorHeight="5dp">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.animee.test.WeatherFragment"> <!-- TODO: Update blank fragment layout --> <ListView android:id="@+id/fragment_lv" android:layout_width="match_parent" android:layout_height="match_parent" android:divider="@color/colorPrimary" android:dividerHeight="1dp" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp"> <TextView android:id="@+id/header_tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="近期天气情况:" android:textColor="@color/colorPrimary" android:textSize="20sp"/> <Spinner android:id="@+id/header_sp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/header_tv2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="今日指数分析:" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:textColor="@color/colorPrimary" android:textSize="20sp"/> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <TextView android:id="@+id/lv_tv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="穿衣" android:textSize="20sp" android:textColor="@color/colorAccent"/> <TextView android:id="@+id/lv_tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/lv_tv1" android:layout_marginTop="10dp" android:text="穿衣指数" /> <TextView android:id="@+id/lv_tv3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/lv_tv2" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/lv_tv2" android:layout_toRightOf="@+id/lv_tv2" android:text="冷" /> <TextView android:id="@+id/lv_tv4" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/lv_tv2" android:te 9f40 xtColor="@color/colorPrimary" android:padding="10dp" android:background="#eee" android:layout_margin="10dp" android:text="天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。" /> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#eee" android:padding="20dp"> <TextView android:id="@+id/sp_tv_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:textSize="18sp" android:text="周五 01月12日 (实时:-3℃)" /> <TextView android:id="@+id/sp_tv_day" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/sp_tv_date" android:layout_marginTop="10dp" android:text="白天情况:晴" /> <TextView android:id="@+id/sp_tv_fengxiang" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/sp_tv_day" android:layout_marginTop="10dp" android:text="西南风3-4级" /> <TextView android:id="@+id/sp_tv_wendu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/sp_tv_fengxiang" android:layout_marginLeft="30dp" android:layout_marginStart="30dp" android:layout_toEndOf="@+id/sp_tv_day" android:layout_toRightOf="@+id/sp_tv_day" android:text="温度:3 ~ -8℃" /> <ImageView android:id="@+id/sp_img_bt" android:layout_width="40dp" android:layout_height="30dp" android:layout_alignBottom="@+id/sp_tv_day" app:srcCompat="@android:drawable/btn_dialog" android:layout_alignLeft="@+id/sp_tv_wendu" android:layout_alignStart="@+id/sp_tv_wendu" /> <TextView android:id="@+id/sp_tv_night" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/sp_tv_fengxiang" android:text="夜间情况:" android:layout_marginTop="10dp"/> <ImageView android:id="@+id/sp_img_night" android:layout_width="40dp" android:layout_height="30dp" android:layout_alignBottom="@+id/sp_tv_night" android:layout_alignStart="@+id/sp_img_bt" android:layout_alignLeft="@+id/sp_img_bt" android:layout_marginTop="10dp" app:srcCompat="@android:drawable/btn_dialog" /> <ImageView android:layout_width="match_parent" android:layout_height="2dp" android:layout_below="@+id/sp_img_night" android:background="@color/colorPrimary" android:layout_marginTop="10dp"/> </RelativeLayout>
相关文章推荐
- 从中国天气网上获取天气数据并解析
- 获取天气数据
- android天气查询(二)之网络json数据的获取
- android天气查询(二)之网络json数据的获取
- Qt:通过IP获取当前地理位置天气数据
- 获取历史天气数据,数据挖掘必备
- 在线云评测系统日志(十):获取输入文件的评测数据进行程序评测
- Quartz Scheduler定时获取天气数据
- android获取全国城市数据和天气,工程结构及代码十分规范
- 点击按钮获取listview网上数据
- win8 网上获取数据
- Swift - 使用OpenWeatherMap获取天气的实时数据、预测数据
- 通过api使用HttpURLConnection 获取返回天气数据。
- wp7天气预报源代码(二获取谷歌天气数据)公布源代码下载地址
- Android中sqlite之从网上获取数据更新UI
- Python下的数据处理和机器学习,对数据在线及本地获取、解析、预处理和训练、预测、交叉验证、可视化
- 城市天气数据获取接口
- [置顶] Android网络与数据存储03-在线请求天气API,并解析其中的json数据予以显示
- Quartz Scheduler定时获取天气数据
- Android中获取网络天气数据