分享 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

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr