我正在开发新闻应用程序,并且在运行代码时在片段类中实现了dagger 2
Logcats:
致命异常:主要 流程:edgar.yodgorbek.sportnews,PID:8567 java.lang.ClassCastException:edgar.yodgorbek.sportnews.component.DaggerApplicationComponent无法转换为edgar.yodgorbek.sportnews.component.BBCSportFragmentComponent 在edgar.yodgorbek.sportnews.sportactivities.BBCSportFragment $ 1.onResponse(BBCSportFragment.java:72) 在retrofit2.ExecutorCallAdapterFactory $ ExecutorCallbackCall $ 1 $ 1.run(ExecutorCallAdapterFactory.java:70) 在android.os.Handler.handleCallback(Handler.java:873) 在android.os.Handler.dispatchMessage(Handler.java:99) 在android.os.Looper.loop(Looper.java:209)
在BBCSportFragment.java 类之下:
public class BBCSportFragment extends Fragment implements ArticleAdapter.ClickListener {
public List<Article> articleList = new ArrayList<>();
@ActivityContext
public Context activityContext;
@ApplicationContext
public Context mContext;
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
BBCSportFragmentComponent bbcSportFragmentComponent;
BBCFragmentContextModule bbcFragmentContextModule;
private SportNews sportNews;
private ArticleAdapter articleAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bbcsport, container, false);
Activity activity = getActivity();
ButterKnife.bind(this, view);
SportInterface sportInterface = SportClient.getApiService();
Call<SportNews> call = sportInterface.getArticles();
call.enqueue(new Callback<SportNews>() {
@Override
public void onResponse(Call<SportNews> call, Response<SportNews> response) {
sportNews = response.body();
if (sportNews != null && sportNews.getArticles() != null) {
articleList.addAll(sportNews.getArticles());
}
articleAdapter = new ArticleAdapter(articleList, sportNews);
ApplicationComponent applicationComponent = MyApplication.get(Objects.requireNonNull(activity)).getApplicationComponent();
bbcSportFragmentComponent = (BBCSportFragmentComponent) DaggerApplicationComponent.builder().contextModule(new ContextModule(getContext())).build();
bbcSportFragmentComponent.injectBBCSportFragment(BBCSportFragment.this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(articleAdapter);
}
@Override
public void onFailure(Call<SportNews> call, Throwable t) {
Log.e("Error", "error");
}
});
return view;
}
}
ArticleAdapter.java 类以下:
public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.CustomViewHolder> {
public static final String urlKey = "urlKey";
public static final String imageKey = "imageKey";
public ArticleAdapter.ClickListener listener;
Context context;
private List<Article> articles = new ArrayList<>();
public ArticleAdapter(List<Article> articles, SportNews sportNews) {
this.articles = articles;
this.listener = listener;
}
public ArticleAdapter(ArticleAdapter.ClickListener clickListener) {
}
@NonNull
@Override
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.article_list, null);
return new CustomViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull CustomViewHolder customViewHolder, int position) {
Article article = articles.get(position);
if(article!=null){
customViewHolder.articleAuthor.setText(article.getAuthor());
customViewHolder.articleTitle.setText(article.getTitle());
Picasso.get().load(article.getUrlToImage()).into(customViewHolder.articleImage);}
customViewHolder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(v.getContext(), DetailActivity.class);
intent.putExtra("urlKey", article.getUrl());
intent.putExtra("imageKey", article.getUrlToImage());
v.getContext().startActivity(intent);
});
}
@Override
public int getItemCount() {
if (articles == null) return 0;
return articles.size();
}
public interface ClickListener {
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.articleAuthor)
TextView articleAuthor;
@BindView(R.id.articleTitle)
TextView articleTitle;
@BindView(R.id.articleImage)
ImageView articleImage;
public CustomViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
MyApplication.java 类以下:
public class MyApplication extends Application {
ApplicationComponent applicationComponent;
public static MyApplication get(Activity activity) {
return (MyApplication) activity.getApplication();
}
@Override
public void onCreate() {
super.onCreate();
applicationComponent = DaggerApplicationComponent.builder().contextModule(new ContextModule(this)).build();
applicationComponent.injectApplication(this);
}
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
}
在清单文件下面:
<?xml version="1.0" encoding="UTF-8"?>
<manifest package="edgar.yodgorbek.sportnews" xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
-<application android:name=".component.MyApplication" tools:replace="android:appComponentFactory" tools:ignore="GoogleAppIndexingWarning" android:theme="@style/AppTheme" android:supportsRtl="true" android:roundIcon="@mipmap/ic_launcher_round" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:appComponentFactory="@string/app_name" android:allowBackup="true">
-<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
答案 0 :(得分:0)
关于Dagger设置,这一行似乎不正确:
// BBCSportFragment.onCreate > Callback.onResponse
(BBCSportFragmentComponent) DaggerApplicationComponent.builder().contextModule(new ContextModule(getContext())).build();
正确的设置不需要您强制转换.build()
的结果。
如果BBCSportFragmentComponent
使用组件依赖项(带有@Component(dependencies = ApplicationComponent.class)
之类的注释),也许您的意思是:
bbcSportFragmentComponent =
DaggerBBCSportFragmentComponent.builder()
.applicationComponent(applicationComponent)
.contextModule(new ContextModule(getContext()))
.build();
bbcSportFragmentComponent.injectBBCSportFragment(BBCSportFragment.this);
然后,应将Dagger应该注入的字段注释为@Inject
。否则bbcSportFragmentComponent.injectBBCSportFragment
将成功执行任何操作。
然后,Dagger文档建议使用injecting a Fragment inside onAttach
before super.onAttach()
。