当前位置: 首页 > news >正文

Android 使用kotlin Retrofit2 + Dagger2完成网络请求跟依赖注入组合使用

文章目录

    • (一)引入依赖
    • (二)基本概念
      • Dagger中的基本概念:
      • Retrofit介绍
    • (三)Dagger2 @Module 和 @Provides 和 @Component +@Inject
    • (四)Retrofit2 创建数据类Bean跟Service服务
    • (五)使用Retrofit跟Dagger2

(一)引入依赖

implementation 'com.google.dagger:dagger:2.21'
kapt 'com.google.dagger:dagger-compiler:2.21'
implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation("com.squareup.retrofit2:converter-gson:2.3.0")

注: dagger-compiler要使用kapt插件

plugins {id 'org.jetbrains.kotlin.kapt'
}

(二)基本概念

Dagger中的基本概念:

  • Provides提供依赖的方法撒谎给你添加的注解,provide方法需要包含在Module中
  • Module专门提供依赖,类似工厂模式
  • Component它是一个桥梁,一端是目标类,另一端是目标所依赖的实例,它也是注入器,负责把目标类所依赖类的实例注入到目标类中,同时它也管理Module。(先从Module中找依赖,再从Inject找构造函数)
  • Scope自定义注解,用于标示作用域,随意命名,对应即可
  • Inject是用来标注依赖和被依赖的构造函数

Retrofit介绍

Retrofit介绍:
它是一个RESTful的HTTP网络请求框架(基于OkHttp),它基于OkHttp,通过注解配置网络请求参数,能够支持多种数据的解析和序列化,如Gson、Json、XML、Protobuf
优点:

  • 功能强大,支持同步 & 异步、支持多种数据的解析 & 序列化格式、支持RxJava
  • 简洁易用:通过注解配置网络请求参数,采用大量设计模式简化使用
  • 可扩展性好:功能模块高度封装、解耦彻底

在这里插入图片描述

(三)Dagger2 @Module 和 @Provides 和 @Component +@Inject

定义Module类跟Component抽象接口

@Module
class NetworkModule {@Providesfun getRetrofit(): Retrofit? {return Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(BASE_URL).build()}companion object {const val BASE_URL = "http://api.k780.com/"}
}@Component(modules = [NetworkModule::class])
interface MyComponent {fun inject(regesiteActivity: RegesiteActivity)
}

在活动Activity中定义一个retrofit变量,标注@Inject注解表明这是需要被注入的变量,注意不要定义成val不可变类型

    @Injectlateinit var retrofit: Retrofit

然后在活动中进行注入,需要在View创建之后使用,DaggerMyComponent会在构建rebuild之后生成

DaggerMyComponent.create().inject(this)

在这里插入图片描述
如果依赖正确但是没有生成,检查下依赖是否正确,或者在gradle.properties中添加一行配置:

kapt.incremental.apt = false

(四)Retrofit2 创建数据类Bean跟Service服务

public interface Service {@GET("?app=weather.today&weaid=成都&appkey=46951&sign=b2f1992fc55dfd5ae70895f60ab3a86d&format=json")Call<FeatureBean> getFeatureBean();@GET("?")Call<FeatureBean> getFeature(@Query("app") String app, @Query("weaid") String city,@Query("appkey") String key, @Query("sign") String sign,@Query("format") String format);
}public class FeatureBean {private String success;private Result result;public void setSuccess(String success) {this.success = success;}public String getSuccess() {return success;}public void setResult(Result result) {this.result = result;}public Result getResult() {return result;}}public class Result {private String weaid;private String days;private String week;private String cityno;private String citynm;private String cityid;private String temperature;private String temperature_curr;private String humidity;private String aqi;private String weather;private String weather_curr;private String weather_icon;private String weather_icon1;private String wind;private String winp;private String temp_high;private String temp_low;private String temp_curr;private String humi_high;private String humi_low;private String weatid;private String weatid1;private String windid;private String winpid;private String weather_iconid;public void setWeaid(String weaid) {this.weaid = weaid;}public String getWeaid() {return weaid;}public void setWeek(String week) {this.week = week;}public String getWeek() {return week;}public String getDays() {return days;}public void setDays(String days) {this.days = days;}public void setHumidity(String humidity) {this.humidity = humidity;}public void setCityno(String cityno) {this.cityno = cityno;}public String getCityno() {return cityno;}public void setCitynm(String citynm) {this.citynm = citynm;}public String getCitynm() {return citynm;}public void setCityid(String cityid) {this.cityid = cityid;}public String getCityid() {return cityid;}public void setTemperature(String temperature) {this.temperature = temperature;}public String getTemperature() {return temperature;}public void setTemperature_curr(String temperature_curr) {this.temperature_curr = temperature_curr;}public String getTemperature_curr() {return temperature_curr;}public void setAqi(String aqi) {this.aqi = aqi;}public String getAqi() {return aqi;}public void setWeather(String weather) {this.weather = weather;}public String getWeather() {return weather;}public void setWeather_curr(String weather_curr) {this.weather_curr = weather_curr;}public String getWeather_curr() {return weather_curr;}public void setWeather_icon(String weather_icon) {this.weather_icon = weather_icon;}public String getWeather_icon() {return weather_icon;}public void setWeather_icon1(String weather_icon1) {this.weather_icon1 = weather_icon1;}public String getWeather_icon1() {return weather_icon1;}public void setWind(String wind) {this.wind = wind;}public String getWind() {return wind;}public void setWinp(String winp) {this.winp = winp;}public String getWinp() {return winp;}public void setTemp_high(String temp_high) {this.temp_high = temp_high;}public String getTemp_high() {return temp_high;}public void setTemp_low(String temp_low) {this.temp_low = temp_low;}public String getTemp_low() {return temp_low;}public void setTemp_curr(String temp_curr) {this.temp_curr = temp_curr;}public String getTemp_curr() {return temp_curr;}public void setHumi_high(String humi_high) {this.humi_high = humi_high;}public String getHumi_high() {return humi_high;}public void setHumi_low(String humi_low) {this.humi_low = humi_low;}public String getHumi_low() {return humi_low;}public void setWeatid(String weatid) {this.weatid = weatid;}public String getWeatid() {return weatid;}public void setWeatid1(String weatid1) {this.weatid1 = weatid1;}public String getWeatid1() {return weatid1;}public void setWindid(String windid) {this.windid = windid;}public String getWindid() {return windid;}public void setWinpid(String winpid) {this.winpid = winpid;}public String getWinpid() {return winpid;}public void setWeather_iconid(String weather_iconid) {this.weather_iconid = weather_iconid;}public String getWeather_iconid() {return weather_iconid;}@Overridepublic String toString() {return "Result{" +"weaid='" + weaid + '\'' +", days='" + days + '\'' +", week='" + week + '\'' +", cityno='" + cityno + '\'' +", citynm='" + citynm + '\'' +", cityid='" + cityid + '\'' +", temperature='" + temperature + '\'' +", temperature_curr='" + temperature_curr + '\'' +", humidity='" + humidity + '\'' +", aqi='" + aqi + '\'' +", weather='" + weather + '\'' +", weather_curr='" + weather_curr + '\'' +", weather_icon='" + weather_icon + '\'' +", weather_icon1='" + weather_icon1 + '\'' +", wind='" + wind + '\'' +", winp='" + winp + '\'' +", temp_high='" + temp_high + '\'' +", temp_low='" + temp_low + '\'' +", temp_curr='" + temp_curr + '\'' +", humi_high='" + humi_high + '\'' +", humi_low='" + humi_low + '\'' +", weatid='" + weatid + '\'' +", weatid1='" + weatid1 + '\'' +", windid='" + windid + '\'' +", winpid='" + winpid + '\'' +", weather_iconid='" + weather_iconid + '\'' +'}';}
}

(五)使用Retrofit跟Dagger2

没有注入的话需要先进行注入:

DaggerMyComponent.create().inject(this)
val callback  = retrofit.create(Service::class.java).getFeature("weather.today", "成都", "46951", "b2f1992fc55dfd5ae70895f60ab3a86d", "json")
val execute : Response<FeatureBean>? = callback?.execute()
val featureBean = execute?.body()
val result = featureBean?.result
println("返回结果:" + result?.toString())

注意:
(1)Unresolved reference: DaggerMyComponent
解决:在gradle.properties中添加

kapt.incremental.apt = false

(2)Kotlin 使用 Retrofit 报 Unresolved reference: GsonConverterFactory

原因是依赖有问题,converter-gson不适用kapt,修改成正确的依赖即可:

implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation("com.squareup.retrofit2:converter-gson:2.3.0")

(3)IllegalArgumentException: Unable to create converter for class com.example.weatherapp.network.FeatureBean for method Service.getFeature

出现这个问题的原因是因为缺少ConverterFactory,所以要addConverterFactory

Retrofit.Builder().addConverterFactory(GsonConverterFactory.create())//这一行.baseUrl(BASE_URL).build()

参考文档:
https://blog.csdn.net/rjgcszlc/article/details/78364689
https://zhuanlan.zhihu.com/p/595569731
https://www.jianshu.com/p/f79003a5e6ba
https://blog.csdn.net/lu202032/article/details/129217818

好了,到这就写完了,更新不易,还望老铁们点个追更

相关文章:

  • 对未知程序所创建的 PDF 文档的折叠书签层级全展开导致丢签的一种解决方法
  • Python疑难杂症--考试复习
  • c++学习----初识类和对象(上)
  • 1882java密室逃脱管理系统 Myeclipse开发mysql数据库web结构java编程计算机网页项目
  • 揭秘小程序商城的团购奇迹:独特模式引领盈利新纪元
  • Python代码:二十八、密码游戏
  • 搜狐视频专访神工坊创始人任虎:以先进计算技术为引擎,引领新一代CAE革新之路
  • IC开发——VCS基本用法
  • ImportError: cannot import name ‘packaging‘ from ‘pkg_resources‘‘
  • 从CSV到数据库(简易)
  • 深入URP之Shader篇16: UNITY_BRANCH和UNITY_FLATTEN
  • 前端面试题日常练-day43 【面试题】
  • LeetCode 每日一题 数学篇(2769.找出最大的可达成数字)
  • 掌握 NestJS 10.x:NestJS 结合 PostgreSQL 使用详解
  • RabbitMQ 如何保证消息不丢失
  • [ 一起学React系列 -- 8 ] React中的文件上传
  • 2017-08-04 前端日报
  • 4月23日世界读书日 网络营销论坛推荐《正在爆发的营销革命》
  • android百种动画侧滑库、步骤视图、TextView效果、社交、搜房、K线图等源码
  • EventListener原理
  • IE报vuex requires a Promise polyfill in this browser问题解决
  • Java多态
  • Linux编程学习笔记 | Linux多线程学习[2] - 线程的同步
  • nginx 负载服务器优化
  • vue-router 实现分析
  • 阿里中间件开源组件:Sentinel 0.2.0正式发布
  • 初识 beanstalkd
  • 对JS继承的一点思考
  • 番外篇1:在Windows环境下安装JDK
  • 观察者模式实现非直接耦合
  • 基于游标的分页接口实现
  • 记录:CentOS7.2配置LNMP环境记录
  • 开源中国专访:Chameleon原理首发,其它跨多端统一框架都是假的?
  • 数据结构java版之冒泡排序及优化
  • 王永庆:技术创新改变教育未来
  • 怎么将电脑中的声音录制成WAV格式
  • mysql面试题分组并合并列
  • ​Base64转换成图片,android studio build乱码,找不到okio.ByteString接腾讯人脸识别
  • # Apache SeaTunnel 究竟是什么?
  • #QT(QCharts绘制曲线)
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (蓝桥杯每日一题)平方末尾及补充(常用的字符串函数功能)
  • (十七)devops持续集成开发——使用jenkins流水线pipeline方式发布一个微服务项目
  • (原)记一次CentOS7 磁盘空间大小异常的解决过程
  • (转)http-server应用
  • *p=a是把a的值赋给p,p=a是把a的地址赋给p。
  • .gitignore
  • .MyFile@waifu.club.wis.mkp勒索病毒数据怎么处理|数据解密恢复
  • .NET Core SkiaSharp 替代 System.Drawing.Common 的一些用法
  • .NET Framework 服务实现监控可观测性最佳实践
  • .net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)
  • .NET 中使用 TaskCompletionSource 作为线程同步互斥或异步操作的事件
  • .NET(C#) Internals: as a developer, .net framework in my eyes
  • .NET下的多线程编程—1-线程机制概述
  • /etc/fstab 只读无法修改的解决办法