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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/20918.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

探索Java反射:解密动态性与灵活性

前言 Java反射是一项强大而灵活的技术&#xff0c;它使得程序能够在运行时获取类的信息、调用类的方法、访问类的字段等。本篇博客将深入探讨Java反射的原理、应用场景以及使用技巧&#xff0c;带你解密Java反射的奥秘。 什么是Java反射&#xff1f; 在传统的Java编程中&…

LabVIEW调用国产硬件DLL的稳定性问题及解决方案

在LabVIEW中调用国内公司提供的硬件DLL时&#xff0c;尽管可以运行&#xff0c;但常出现不稳定和bug问题&#xff0c;且厂家临时修改的版本未经长期测试。为确保稳定性和质量&#xff0c;需要制定系统化的测试和反馈机制、建立严格的版本控制、与厂家协作优化、并进行深入的自测…

C语言刷题(数组)

1. 编写程序利用数组实现将一个数插入到一个有序的数列中&#xff0c;要求插入后仍有序。 C语言代码 #include <stdio.h> int main(){ int n 0; printf("请输入有序数组元素的个数&#xff1a;\n"); scanf("%d",&n); //定义并输入数组 …

3. MySQL 数据表的基本操作

文章目录 【 1. MySQL 创建数据表 】【 2. MySQL 查看表 】2.1 查看表的属性DESCRIBE/DESC 以表格的形式展示表属性SHOW CREATE TABLE 以SQL语句的形式展示表属性 2.2 查看表的内容 【 3. MySQL 修改数据表结构 】3.1 修改表名3.2 修改表字符集3.3 添加字段在末尾添加字段在开头…

LLMs Can’t Plan, But Can Help Planning in LLM-Modulo Frameworks

更多精彩内容&#xff0c;请关注微信公众号&#xff1a;NLP分享汇 原文链接&#xff1a;LLMs Can’t Plan, But Can Help Planning in LLM-Modulo Frameworks 你是怎么理解LLM的规划和推理能力呢&#xff0c;来自亚利桑那州立大学最近的一篇论文&#xff0c;对LLM的规划、推理…

RESTful API开发:Flask库设计用户认证接口的6个要点

在当今的Web开发世界里&#xff0c;RESTful API已然成为应用程序间数据交互的标准方式。它们简洁、灵活&#xff0c;使得前后端分离更加顺畅。而Flask&#xff0c;作为一款轻量级且功能强大的Python Web框架&#xff0c;无疑是构建RESTful API的理想工具。然而&#xff0c;要确…

Java面试题:如何在Java中实现线程间的通信?请列举几种常见的方式

在Java中&#xff0c;线程间的通信主要涉及到线程间的数据交换和协调。以下是几种常见的线程间通信方式&#xff1a; 共享对象&#xff1a; 线程可以通过共享对象的实例变量或方法参数来进行通信。这种方式需要特别注意线程安全&#xff0c;通常需要同步代码块或使用锁来避免并…

ios 新安装app收不到fcm推送

&#x1f3c6;本文收录于「Bug调优」专栏&#xff0c;主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案&#xff0c;希望能够助你一臂之力&#xff0c;帮你早日登顶实现财富自由&#x1f680;&#xff1b;同时&#xff0c;欢迎大家关注&&收藏&&…

Python库之Playwright简介、安装、使用方法详细攻略

Python库之Playwright简介、安装、使用方法详细攻略 引言 在自动化测试领域&#xff0c;Playwright是一个强大的库&#xff0c;它支持无头浏览器自动化&#xff0c;允许开发者在多种浏览器上进行网页自动化操作。Playwright由微软开发&#xff0c;支持Chromium、Firefox和Web…

拼图游戏完整思路(全代码演示)

主界面 小练习1&#xff1a; 一、三个界面的设置1&#xff1a;创建窗体 1、将三个主界面分开为三个类&#xff0c;每个类都去继承JFrame这个类&#xff0c;使得每个类都可以使用创建页面功能 2、对每个类进行空参构造&#xff0c;在空参构造里面进行窗体属性的赋值 3、创建一个…

苍穹外卖--sky-take-out(二)3-5

sky-take-out&#xff08;一&#xff09;1-2https://blog.csdn.net/kussm_/article/details/138614737?spm1001.2014.3001.5501 第三天 公共字段填充--利用AOP 问题提出 这些字段属于公共字段 &#xff1a;在新增员工或者新增菜品分类时需要设置创建时间、创建人、修改时间…

蓝桥杯软件测试-十五届模拟赛2期题目解析

十五届蓝桥杯《软件测试》模拟赛2期题目解析 PS 需要第十五界蓝桥杯模拟赛2期功能测试模板、单元测试被测代码、自动化测试被测代码请加&#x1f427;:1940787338 备注&#xff1a;15界蓝桥杯省赛软件测试模拟赛2期 题目1&#xff1a;功能测试题目 1&#xff08;测试用例&…

[极速版]写个linux探测自己机器ip地址的tool(基于shell + sshpass)

适用情况&#xff1a;上级路由ssh or teamviewer访问下级路由的机器&#xff0c;但下级路由不支持查看IP 自行完成端口映射or DMZ整机映射 apt-get install sshpass#!/bin/bash mkdir log for i in $(seq 2 255) dosshpass -p tmp ssh -E err.log -o StrictHostKeyCheckingno …

【解决】Tree prefab at index 8 is missing.

开发平台&#xff1a;Unity 2020 版本以上   问题描述 翻译&#xff1a;树预制体集合中第8位预制体丢失。   解决方法&#xff1a;修复丢失树资产 关联 Unity Terrier 组件使用&#xff0c;前往 树绘制工作区&#xff0c;检查 “树资产” 引用是否丢失&#xff1f;删除或重…

【面试题-013】MyBatis 中,`#` 和 `$` 符号区别

在 MyBatis 中&#xff0c;# 和 $ 符号用于参数替换和表达式。它们在 SQL 语句中用于防止 SQL 注入&#xff0c;并允许动态地插入参数值。 # 符号&#xff08;预编译参数&#xff09;: #{parameter} 用于预编译参数。在 SQL 语句中&#xff0c;#{parameter} 会被 MyBatis 解析…

【C/C++】C++类的六个特殊成员函数,附亲测实例

在C中&#xff0c;类的特殊成员函数是指那些由编译器自动生成的函数&#xff0c;它们在特定情况下会被调用&#xff0c;以支持类的某些操作。这些特殊成员函数包括&#xff1a; 默认构造函数&#xff08;Default Constructor&#xff09;&#xff1a; 当没有提供任何构造函数时…

【C++】C++程序的四个区和智能指针的实现

这篇文章介绍下 C 程序的四个区&#xff0c;以及一个智能指针的简单实现。 起因 最近在公司审查代码的时候&#xff0c;coverity 对以下代码&#xff1a; T fun() {Obj obj;//代码逻辑 }报出了 obj 占用空间过大&#xff0c;有可能栈溢出的问题。 以前从来没有考虑过C的代码…

双指针练习:盛水最多的容器

题目链接&#xff1a;11.盛水最多的容器 题目描述&#xff1a; 给定一个长度为 n 的整数数组 height 。有 n 条垂线&#xff0c;第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线&#xff0c;使得它们与 x 轴共同构成的容器可以容纳最多的水。 返回容器可…

【多模态】34、LLaVA-v1.5 | 微软开源,用极简框架来实现高效的多模态 LMM 模型

文章目录 一、背景二、方法2.1 提升点2.2 训练样本 三、效果3.1 整体效果对比3.2 模型对于 zero-shot 形式的指令的结果生成能力3.3 模型对于 zero-shot 多语言的能力3.4 限制 四、训练4.1 数据4.2 超参 五、代码 论文&#xff1a;Improved Baselines with Visual Instruction …

深入了解 Java 泛型

Java 泛型&#xff08;Generics&#xff09;是 Java SE 5 引入的一个强大特性&#xff0c;它允许你定义类、接口和方法时使用类型参数&#xff0c;从而使代码更加灵活和可重用。本篇博客将详细讲解 Java 泛型的概念、使用方法和注意事项&#xff0c;并通过多个代码示例&#xf…