我有2个选项卡第一个选项卡(newsFragment)解析recycler中的json查看第二个选项卡(favouritnewsfragment),所以当我在第一个水龙头中单击一行时我想要的东西将转到第二个选项卡,然后将其放入recyclerView我无法从newsAdapter将数据发送到favAdapter的问题是我的代码
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
Context context;
ArrayList<Result> articles;
public NewsAdapter(Context context, ArrayList<Result> articles) {
this.context = context;
this.articles = articles;
}
@NonNull
@Override
public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.news_fragment_items, parent, false);
return new NewsViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull NewsViewHolder holder, final int position) {
holder.tvName.setText(articles.get(position).getWebTitle());
holder.tvDesCription.setText(articles.get(position).getSectionName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
** i guess here i need to take the data that i click on it and send it into the second fragment or insert it in the database **
}
});
}
@Override
public int getItemCount() {
return articles.size();
}
public class NewsViewHolder extends RecyclerView.ViewHolder{
TextView tvName;
TextView tvDesCription;
public NewsViewHolder(@NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tvName);
tvDesCription = itemView.findViewById(R.id.tvDesCription);
}
}
}
这是新闻片段
public class NewsFragment extends Fragment {
ArrayList<Result> articleArrayList = new ArrayList<>();
NewsAdapter newsAdapter;
RecyclerView rvHeadline;
private SwipeRefreshLayout swipeRefreshLayout;
private static final String TAG = "NewsFragment";
private NoteViewModel pageViewModel;
public NewsFragment() {
// Required empty public constructor
}
public static NewsFragment newInstance() {
return new NewsFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.news_fragment, container, false);
rvHeadline = root.findViewById(R.id.rvNews);
swipeRefreshLayout= root.findViewById(R.id.swip_refresh_layout);
if (CheckInternet.isNetwork(getActivity())) {
pageViewModel.getNewsRepository().observe(this, new Observer<NewsResponse>() {
@Override
public void onChanged(NewsResponse newsResponse) {
List<Result> newsArticles = newsResponse.getResponse().getResults();
articleArrayList.addAll(newsArticles);
newsAdapter.notifyDataSetChanged();
}
});
}else{
Toast.makeText(getActivity(),"something",Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (CheckInternet.isNetwork(getActivity())) {
pageViewModel.getNewsRepository().observe(getActivity(), new Observer<NewsResponse>() {
@Override
public void onChanged(NewsResponse newsResponse) {
List<Result> newsArticles = newsResponse.getResponse().getResults();
articleArrayList.addAll(newsArticles);
newsAdapter.notifyDataSetChanged();
}
});
}else{
Toast.makeText(getActivity(),"something",Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
}
});
setupRecyclerView();
return root;
}
private void setupRecyclerView() {
if (newsAdapter == null) {
newsAdapter = new NewsAdapter(getActivity(), articleArrayList);
rvHeadline.setLayoutManager(new LinearLayoutManager(getActivity()));
rvHeadline.setAdapter(newsAdapter);
rvHeadline.setItemAnimator(new DefaultItemAnimator());
rvHeadline.setNestedScrollingEnabled(true);
} else {
newsAdapter.notifyDataSetChanged();
}
}
}
现在是最喜欢的广告人
public class FavAdapter extends RecyclerView.Adapter<FavAdapter.FavAdapterViewHolder> {
List<FavNews> favNews = new ArrayList<>();
@NonNull
@Override
public FavAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fav_fragment_items, parent, false);
return new FavAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull FavAdapterViewHolder holder, int position) {
FavNews favNews2 = favNews.get(position);
holder.tvName.setText(favNews2.getTitle());
holder.tvDesCription.setText(favNews2.getDescription());
}
@Override
public int getItemCount() {
return favNews.size();
}
public void setNotes(List<FavNews> favNews){
this.favNews = favNews ;
notifyDataSetChanged();
}
public class FavAdapterViewHolder extends RecyclerView.ViewHolder{
TextView tvName;
TextView tvDesCription;
public FavAdapterViewHolder(@NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tvName2);
tvDesCription = itemView.findViewById(R.id.tvDesCription2);
}
}
}
favFragment
public class FavFragment extends Fragment {
private static final String TAG = "FavFragment";
private NoteViewModel pageViewModel;
private RecyclerView recyclerView;
FavAdapter favAdapter;
public FavFragment() {
// Required empty public constructor
}
/**
* @return A new instance of fragment SpeedDialFragment.
*/
public static FavFragment newInstance() {
return new FavFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fav_fragment, container, false);
recyclerView = root.findViewById(R.id.rvNews2);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
favAdapter = new FavAdapter();
recyclerView.setAdapter(favAdapter);
pageViewModel.getAllNotes().observe(this, new Observer<List<FavNews>>() {
@Override
public void onChanged(List<FavNews> favNewsList) {
favAdapter.setNotes(favNewsList);
favAdapter.notifyDataSetChanged();
Log.e("size",favNewsList.size()+"");
}
});
return root;
}
}
这是我的Viewmodel
public class NoteViewModel extends AndroidViewModel {
private NewsRepository repository;
private LiveData<List<FavNews>> allNotes;
public MutableLiveData<NewsResponse> getNewsRepository() {
repository = NewsRepository.getInstance();
return repository.getNews( "b70d396f-d5b4-43f0-8b67-222524937f25");
}
public NoteViewModel(@NonNull Application application) {
super(application);
repository = new NewsRepository(application);
allNotes = repository.getAllNotes();
}
public void insert(FavNews favNews) {
repository.insert(favNews);
}
public void update(FavNews favNews) {
repository.update(favNews);
}
public void delete(FavNews favNews) {
repository.delete(favNews);
}
public void deleteAllNotes() {
repository.deleteAllNotes();
}
public LiveData<List<FavNews>> getAllNotes() {
return allNotes;
}
}
数据库
@Database(entities = {FavNews.class}, version = 1,exportSchema = false)
public abstract class FavNewsDatabase extends RoomDatabase {
private static FavNewsDatabase instance;
public abstract FavNewsDao noteDao();
public static synchronized FavNewsDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),
FavNewsDatabase.class, "note_database")
.fallbackToDestructiveMigration()
.addCallback(roomCallback)
.build();
}
return instance;
}
private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
new PopulateDbAsyncTask(instance).execute();
}
};
private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
private FavNewsDao favNewsDao;
private PopulateDbAsyncTask(FavNewsDatabase db) {
favNewsDao = db.noteDao();
}
@Override
protected Void doInBackground(Void... voids) {
favNewsDao.insert(new FavNews("Title 1", "Description 1"));
favNewsDao.insert(new FavNews("Title 2", "Description 2"));
favNewsDao.insert(new FavNews("Title 3", "Description 3"));
///those are examples and it shows in the favouriteFragment recyclerView
return null;
}
}
}
这是存储库
public class NewsRepository {
private FavNewsDao favNewsDao;
private LiveData<List<FavNews>> allNotes;
private NewsApi newsApi;
private static NewsRepository newsRepository;
public static NewsRepository getInstance(){
if (newsRepository == null){
newsRepository = new NewsRepository();
}
return newsRepository;
}
private NewsRepository(){
newsApi = RetrofitService.cteateService(NewsApi.class);
}
public MutableLiveData<NewsResponse> getNews(String key){
final MutableLiveData<NewsResponse> newsData = new MutableLiveData<>();
newsApi.getNewsList( key).enqueue(new Callback<NewsResponse>() {
@Override
public void onResponse(Call<NewsResponse> call,
Response<NewsResponse> response) {
if (response.isSuccessful()){
newsData.setValue(response.body());
}
}
@Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
newsData.setValue(null);
}
});
return newsData;
}
public NewsRepository(Application application) {
FavNewsDatabase database = FavNewsDatabase.getInstance(application);
favNewsDao = database.noteDao();
allNotes = favNewsDao.getAllNotes();
}
public void insert(FavNews favNews) {
new InsertNoteAsyncTask(favNewsDao).execute(favNews);
}
public void update(FavNews favNews) {
new UpdateNoteAsyncTask(favNewsDao).execute(favNews);
}
public void delete(FavNews favNews) {
new DeleteNoteAsyncTask(favNewsDao).execute(favNews);
}
public void deleteAllNotes() {
new DeleteAllNotesAsyncTask(favNewsDao).execute();
}
public LiveData<List<FavNews>> getAllNotes() {
return allNotes;
}
private static class InsertNoteAsyncTask extends AsyncTask<FavNews, Void, Void> {
private FavNewsDao favNewsDao;
private InsertNoteAsyncTask(FavNewsDao favNewsDao) {
this.favNewsDao = favNewsDao;
}
@Override
protected Void doInBackground(FavNews... favNews) {
favNewsDao.insert(favNews[0]);
return null;
}
}
private static class UpdateNoteAsyncTask extends AsyncTask<FavNews, Void, Void> {
private FavNewsDao favNewsDao;
private UpdateNoteAsyncTask(FavNewsDao favNewsDao) {
this.favNewsDao = favNewsDao;
}
@Override
protected Void doInBackground(FavNews... favNews) {
favNewsDao.update(favNews[0]);
return null;
}
}
private static class DeleteNoteAsyncTask extends AsyncTask<FavNews, Void, Void> {
private FavNewsDao favNewsDao;
private DeleteNoteAsyncTask(FavNewsDao favNewsDao) {
this.favNewsDao = favNewsDao;
}
@Override
protected Void doInBackground(FavNews... favNews) {
favNewsDao.delete(favNews[0]);
return null;
}
}
private static class DeleteAllNotesAsyncTask extends AsyncTask<Void, Void, Void> {
private FavNewsDao favNewsDao;
private DeleteAllNotesAsyncTask(FavNewsDao favNewsDao) {
this.favNewsDao = favNewsDao;
}
@Override
protected Void doInBackground(Void... voids) {
favNewsDao.deleteAllNotes();
return null;
}
}
}