0
類
我有我的應用程序的網絡組件,讓我注入改裝到我的活動&片段,我想把它注入到我的工作類,這裏就是我所做的試圖注入到工作
NetComponent接口:
@Singleton
@Component(modules={AppModule.class, NetModule.class})
public interface NetComponent {
void inject(MainActivity activity);
void inject(SplashActivity activity);
void inject(RegisterActivity activity);
void inject(SettingsFragment fragment);
void inject(Context cont); // also tried void inject(Job job);
}
在我的作業類我注入這樣的:
public class LogUploader extends Job {
public static final String TAG = "UPLOAD_LOGS" ;
@Inject
Retrofit mRetrofitClient;
@Override
@NonNull
protected Result onRunJob(Params params) {
((MyApp) getContext()).getNetComponent().inject(getContext());
// run your job here
Log.e("LogFile", " "+ TAG);
//// TODO: 10/18/2017 send log
checklogs(this.getContext());
//// TODO: 10/18/2017 get phone db update
return Result.SUCCESS;
}
}
和碰撞吸能:
ClassCastException: com.evernote.android.job.v21.PlatformJobService cannot be cast to com.**.**.Application.MyApp
任何想法我應該做什麼不同? 感謝所有的幫手!
UPDATE
第一崩潰(CCE)是因爲我做的getContext並轉換爲MyApp的,我把它改成
((MyApp) this.getContext().getApplicationContext()).getNetComponent().inject(getContext());
現在崩潰更有意義:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object retrofit2.Retrofit.create(java.lang.Class)' on a null object reference
我檢查了調試,注射線不注入mRetrofitClient
任何想法?
NetModule類:
@Module
public class NetModule {
String mBaseUrl;
// Constructor needs one parameter to instantiate.
public NetModule(String baseUrl) {
this.mBaseUrl = baseUrl;
}
// Dagger will only look for methods annotated with @Provides
@Provides
@Singleton
// Application reference must come from AppModule.class
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}
@Provides
@Singleton
Cache provideOkHttpCache(Application application) {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(application.getCacheDir(), cacheSize);
return cache;
}
@Provides
@Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
return gsonBuilder.create();
}
@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
OkHttpClient client = new OkHttpClient().newBuilder().cache(cache).build();
return client;
}
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build();
return retrofit;
}
}
請爲您添加翻新提供邏輯。 –
增加了整個網絡模塊,謝謝 – yanivtwin
請提供NPE的完整堆棧跟蹤 – crgarridos