热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

匕首2注射无效

如何解决《匕首2注射无效》经验,如何解决这个问题?

提供Gson,Retrofit和OkHttpClient单例的模块

@Module
public class MyModule {

    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsOnBuilder= new GsonBuilder();
        return gsonBuilder.create();
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient() {
        OkHttpClient client = new OkHttpClient();
        return client;
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(BuildConfig.SERVER_BASE_URL)
                .client(okHttpClient)
                .build();
        return retrofit;
    }
}

允许将单例注入活动和片段的组件

@Singleton
@Component(modules={MyModule.class})
public interface MyComponent {

    void inject(Activity activity);
    void inject(Fragment fragment);
    void inject(Application application);
}

构建组件的主要应用程序类

public class MyApp extends Application{


    private MyComponent component;

    @Inject
    Retrofit retrofit;

    @Override
    public void onCreate() {
        super.onCreate();
        compOnent= DaggerMyComponent.builder()
                .myModule(new MyModule()).build();
        getComponent().inject(this); // inject retrofit here
    }

    public MyComponent getComponent() {
        return component;
    }
}

这是我要注入改造的片段。

public class MyFragment extends Fragment {

    @Inject
    Retrofit retrofit;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        ((MyApp)getActivity().getApplication()).getComponent().inject(this);
      ....

    }
}

在MyApp和MyFragment中,改造实例均为null。


推荐阅读
author-avatar
一号小蘑菇妖
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有