分享 Retrofit+RxJava+MPAndroidChart 未来一周天气气温预测案例

本文主要是介绍分享 Retrofit+RxJava+MPAndroidChart 未来一周天气气温预测案例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

上周我写了一篇MPAndroidChart的使用技巧 ,得到了不少人的响应。至少自己写的文章还是有人去看,很是激励。毕竟我在学习Android开发的时候也是一直看着同行前辈们在技术社区上的干货输出,慢慢地进步起来。当在一些技术点上有了自己的一般见解,也应当回馈社区。

感概完了,现在还是言归正传吧。当掌握了一个技术点之后,怎样在项目中运用到这个技术点,还需要自己好好琢磨琢磨一下的。上次在MPAndroidChart的使用技巧案例中,数据都是自己写死的。现在就来看看MPAndroidChart怎样结合后台的传过来的数据展示图表吧。

在这次的案例中,我使用的是近段时间以来很潮很火的Retrofit+RxJava(这两种开发技术堪称一对CP啊!)来对后台进行网络请求。如果对Retrofit使用还不是很熟悉的话,可以看看之前我的写过一篇 Retrofit网络请求框架基础操作。而对于RxJava,我并未进行深入的研究,但可以看看一些大神写的博客,例如这位大头鬼Bruce。(PS:在案例中我对Retrofit请求时做了一些封装,在点击button前,未显示图表,点击button之后,才显示图表)

Talk is cheap,show you the code

  • 导入MPAndroidChart的jar包(这一步可以参考MPAndroidChart的使用技巧)

  • 添加依赖

    compile fileTree(dir: 'libs', include: ['*.jar'])testCompile 'junit:junit:4.12'compile 'com.android.support:appcompat-v7:23.3.0'compile 'com.squareup.okhttp3:okhttp:3.2.0'compile 'com.squareup.retrofit2:retrofit:2.0.1'compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'compile 'io.reactivex:rxandroid:1.1.0'compile 'io.reactivex:rxjava:1.1.0'compile 'com.orhanobut:logger:1.11'compile project(':JNChartLib')
  • 创建请求接口(使用的接口地址:http://apis.baidu.com/heweather/weather/free )
public interface NetRequest {@GET("/heweather/weather/free?/")Observable<WeatherInfo> getWeatherByRxJava(@Header("apiKey")String apiKey, @Query("city")String city);}
  • 创建网络接口服务的封装类(通过单例模式来获取网络请求接口的对象)
public class RetrofitWrapper {private static RetrofitWrapper instance;private Context mContext;private Retrofit retrofit;private RetrofitWrapper() {Gson gson = new Gson();//创建Retrofit对象retrofit = new Retrofit.Builder().baseUrl(Constant.BASE_URL)//配置转化库,默认是GSON.addConverterFactory(GsonConverterFactory.create(gson))//配置回调库,采用RxJava.addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();}public static RetrofitWrapper getInstance() {if (instance == null) {synchronized (RetrofitWrapper.class){if (instance==null){instance = new RetrofitWrapper();}}}return instance;}/*** 创建请求接口的对象* @param service* @param <T>* @return*/public <T> T create(final Class<T> service) {return retrofit.create(service);}}
public class WeatherInfoModel {private static  WeatherInfoModel weatherInfoModel;private NetRequest netRequest;public WeatherInfoModel(Context context) {netRequest = (NetRequest) RetrofitWrapper.getInstance().create(NetRequest.class);}public static WeatherInfoModel getInstance(Context context) {if (weatherInfoModel == null) {weatherInfoModel = new WeatherInfoModel(context);}return weatherInfoModel;}/*** 查询天气** @param weatherInfoReq* @return*/public Observable<WeatherInfo> queryWeatherByRxJava(WeatherInfoReq weatherInfoReq) {Observable<WeatherInfo> infoCall = netRequest.getWeatherByRxJava(weatherInfoReq.apiKey, weatherInfoReq.city);return infoCall;}
}
public class MainActivity extends Activity {private Button request;private LineChart chart;private WeatherInfoModel weatherInfoModel;private int i = 0;private ProgressDialog pd;private ArrayList<String> xValues = new ArrayList<>();private ArrayList<Entry> yValues2Max = new ArrayList<Entry>();private ArrayList<Entry> yValues2Min = new ArrayList<Entry>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);weatherInfoModel = WeatherInfoModel.getInstance(getApplicationContext());initViews();initParams();initEvent();}/**初始化请求参数*/private WeatherInfoReq initParams() {WeatherInfoReq weatherInfoReq = new WeatherInfoReq();weatherInfoReq.apiKey = Constant.API_KEY;weatherInfoReq.city = Constant.CITY;return weatherInfoReq;}/**初始化控件*/private void initViews() {request = (Button) this.findViewById(R.id.request);chart = (LineChart) this.findViewById(R.id.weatherChart);}private void initEvent() {final Gson gson = new Gson();request.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//创建访问的API请求weatherInfoModel.queryWeatherByRxJava(initParams()).subscribeOn(Schedulers.io())// 指定观察者在io线程(第一次指定观察者线程有效).doOnSubscribe(new Action0() {//在启动订阅前(发送事件前)执行的方法@Overridepublic void call() {pd = new ProgressDialog(MainActivity.this);pd.setMessage("请稍后...");pd.show();}}).flatMap(new Func1<WeatherInfo, Observable<WeatherResult>>() {@Overridepublic Observable<WeatherResult> call(WeatherInfo weatherInfo) {return Observable.from(weatherInfo.getHeWeatherDataList());}}).flatMap(new Func1<WeatherResult, Observable<DailyForecast>>() {@Overridepublic Observable<DailyForecast> call(WeatherResult weatherResult) {return Observable.from(weatherResult.getDaily_forecast());}}).observeOn(AndroidSchedulers.mainThread())//指定订阅者在主线程.subscribe(new Subscriber<DailyForecast>() {@Overridepublic void onCompleted() {pd.dismiss();chart.setDescription("广州气温预测");LineChartManager.setLineName("最高温度");LineChartManager.setLineName1("最低温度");LineChartManager.initDoubleLineChart(MainActivity.this, chart, xValues, yValues2Max, yValues2Min);}@Overridepublic void onError(Throwable e) {pd.dismiss();}@Overridepublic void onNext(DailyForecast dailyForecast) {int j = i++;xValues.add(dailyForecast.getDate());yValues2Max.add(new Entry(Float.valueOf(dailyForecast.getTmp().getMaxTem()), j));yValues2Min.add(new Entry(Float.valueOf(dailyForecast.getTmp().getMinTem()), j));}});}});}}

总结

这次的案例代码还是比较简单的,相信大家看起来应该容易明白。如果要说难点,应该就是RxJava的使用上,因为RxJava是响应式编程,这与我们之前编程的思想有点不同,但它的好处就是代码简洁,优雅,随意地变换线程,而且重要的是它的操作符真的非常牛逼,如果你深入去研究的话,都会对着电脑竖起你的大拇指。而这次的图表中,如果大家看了效果图之后,会发现这次y轴上和图表中的数据都带有单位符号,这是我重写了ValueFormatter和YAxisValueFormatter这两个类,具体的写法大家可以看看源码。本文没有贴出一些bean类和常量类,如需请看源码!最后,小弟不才,还望多多指教!

Retrofit-RxJava-MPAndroidChart-

效果图


点击前


点击后

AndroidRxJavaRetrofit

这篇关于分享 Retrofit+RxJava+MPAndroidChart 未来一周天气气温预测案例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1027032

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件