Recyclerview not display the results on a fragment - java

I'm trying to use recyclerview on fragment with dummy data sample, but does not display any results in fragments that I made, but when I tried it on the activity, the desired results appear in the class activity. Here is a method fragment manager that I made to replace each fragment:
public void changeFragment(Fragment targetFragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_fragment, targetFragment)
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
and this is my current line of code to access the target fragment :
setOnItemClickListener(new DrawerItem.OnItemClickListener() {
#Override
public void onClick(DrawerItem drawerItem, long l, int i) {
changeFragment(new NewsFeedSantri().newInstance());
closeDrawer();
}
})
This is my adapter to generate dummy data :
public class NewsFeedAdapter extends RecyclerView.Adapter<NewsFeedAdapter.NewsFeedHolder> {
private List<NewsFeedItem> newsList;
public NewsFeedAdapter() {
super();
newsList = new ArrayList<NewsFeedItem>();
NewsFeedItem nf = new NewsFeedItem();
for (int i=1; i <= 20; i++) {
nf.setNewsTittle("Judul Berita");
nf.setNewsDate("20/12/2015");
nf.setNewsContent("Ini lorem ipsum dll");
newsList.add(nf);
}
}
#Override
public NewsFeedHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.base_newsfeed_item, parent, false);
NewsFeedHolder viewHolder = new NewsFeedHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(NewsFeedHolder holder, int position) {
NewsFeedItem newsfeed = newsList.get(position);
holder.viewTittle.setText(newsfeed.getNewsTittle());
holder.viewDate.setText(newsfeed.getNewsDate());
holder.viewContent.setText(newsfeed.getNewsContent());
}
#Override
public int getItemCount() {
return newsList.size();
}
public class NewsFeedHolder extends RecyclerView.ViewHolder {
protected TextView viewTittle;
protected TextView viewUrl;
protected TextView viewContent;
protected TextView viewDate;
public NewsFeedHolder(View itemView) {
super(itemView);
viewTittle = (TextView) itemView.findViewById(R.id.news_tittle);
viewDate = (TextView) itemView.findViewById(R.id.news_date);
viewContent = (TextView) itemView.findViewById(R.id.news_content);
}
}
This is NewsFeedItem class :
public class NewsFeedItem {
protected String idNewsTittle;
protected String newsTittle;
protected String newsUrl;
protected String newsContent;
protected String newsDate;
public String getIdNewsTittle() {
return idNewsTittle;
}
public void setIdNewsTittle(String idNewsTittle) {
this.idNewsTittle = idNewsTittle;
}
public String getNewsTittle() {
return newsTittle;
}
public void setNewsTittle(String newsTittle) {
this.newsTittle = newsTittle;
}
public String getNewsUrl() {
return newsUrl;
}
public void setNewsUrl(String newsUrl) {
this.newsUrl = newsUrl;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
public String getNewsDate() {
return newsDate;
}
public void setNewsDate(String newsDate) {
this.newsDate = newsDate;
}
And this is my fragment :
public class NewsFeedSantri extends Fragment {
private RecyclerView recList;
public static NewsFeedSantri newInstance() {
NewsFeedSantri fragment = new NewsFeedSantri();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.base_newsfeed_rcview, container, false);
recList = (RecyclerView) rootView.findViewById(R.id.news_rcview);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
NewsFeedAdapter nfa = new NewsFeedAdapter();
recList.setAdapter(nfa);
return rootView;
} }
No error is generated, this is what makes me confused, did I miss something?

Related

RecylerView does not remove last item

I have a list adapter connected to a recycler view. I use SwipToDelete which calls deleteItem().
If I remove an item, the list entry in the recycler view gets removed.
The problem: If there is only one item in the recycler view and I try to remove it, the list entry is still visible in the recycler view. But it is gone as soon as a restart the app.
I think notifyItemRemoved() should take care of it, like it does if there is more than one item.
RepoListAdapter:
public class RepoListAdapter extends ListAdapter<Repo, RepoViewHolder> {
private RecyclerView recyclerView;
public RepoListAdapter(#NonNull DiffUtil.ItemCallback<Repo> diffCallback) {
super(diffCallback);
}
#NonNull #Override
public RepoViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
return RepoViewHolder.create(viewGroup);
}
#Override
public void onBindViewHolder(RepoViewHolder holder, int position) {
Repo current = getItem(position);
holder.bind(current.getName());
}
public static class RepoDiff extends DiffUtil.ItemCallback<Repo> {
#Override
public boolean areItemsTheSame(#NonNull Repo oldItem, #NonNull Repo newItem) {
return oldItem == newItem;
}
#Override
public boolean areContentsTheSame(#NonNull Repo oldItem, #NonNull Repo newItem) {
return oldItem.getName().equals(newItem.getName());
}
}
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.recyclerView = recyclerView;
}
public Context getContext() {
return recyclerView.getContext();
}
public void deleteItem(int position) {
Repo recentlyDeletedRepo = getItem(position);
RepoViewModel repoViewModel = new ViewModelProvider((ViewModelStoreOwner) getContext()).get(RepoViewModel.class);
repoViewModel.delete(recentlyDeletedRepo);
notifyItemRemoved(position);
notifyItemRangeRemoved(position, 1);
Snackbar snackbar = Snackbar.make(recyclerView, R.string.snackbar_undo, Snackbar.LENGTH_LONG);
snackbar.setAction(R.string.snackbar_undo, v -> undoDelete(recentlyDeletedRepo, position));
snackbar.show();
}
private void undoDelete(Repo recentlyDeletedRepo, int position) {
RepoViewModel repoViewModel = new ViewModelProvider((ViewModelStoreOwner) getContext()).get(RepoViewModel.class);
repoViewModel.insert(recentlyDeletedRepo);
notifyItemInserted(position);
}
}
RepoViewModel:
public class RepoViewModel extends AndroidViewModel {
private final RepoRepository repoRepository;
private final LiveData<List<Repo>> allRepos;
private Repo currentRepo;
public RepoViewModel(Application application) {
super(application);
repoRepository = new RepoRepository(application);
allRepos = repoRepository.getAllRepos();
}
public Repo getCurrentRepo() {
return currentRepo;
}
public void setCurrentRepo(Repo currentRepo) {
this.currentRepo = currentRepo;
}
public LiveData<Repo> getRepoById(int id) {
return repoRepository.getRepoById(id);
}
public LiveData<List<Repo>> getAllRepos() {
return allRepos;
}
public long insert(Repo repo) {
return repoRepository.insert(repo);
}
public void update(Repo repo) {
repoRepository.update(repo);
}
public void delete(Repo repo) {
repoRepository.delete(repo);
}
}
ProjectsFragment:
public class ProjectsFragment extends Fragment {
private RecyclerView recyclerView;
private TextView textview_no_project;
private RepoListAdapter repoListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FloatingActionButton floatingActionButton = ((MainActivity) requireActivity()).getFloatingActionButton();
floatingActionButton.setVisibility(View.VISIBLE);
return inflater.inflate(R.layout.fragment_projects, container, false);
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textview_no_project = view.findViewById(R.id.textview_no_project);
repoListAdapter = new RepoListAdapter(new RepoListAdapter.RepoDiff());
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(repoListAdapter);
ItemTouchHelper itemTouchHelper = new
ItemTouchHelper(new SwipeToDeleteCallback(repoListAdapter));
itemTouchHelper.attachToRecyclerView(recyclerView);
RepoViewModel repoViewModel = new ViewModelProvider(requireActivity()).get(RepoViewModel.class);
repoViewModel.getAllRepos().observe(getViewLifecycleOwner(), this::onLoaded);
}
private void onLoaded(List<Repo> list){
if (list.size() == 0) {
textview_no_project.setVisibility(View.VISIBLE);
}
else {
textview_no_project.setVisibility(View.INVISIBLE);
repoListAdapter.submitList(list);
}
}
}
just try notifyDataSetChanged(); in your adapter

Recyclerview los data when rotate display , data is load when push button Android

sorry for my bad english
My problem: when I rotate my application, all data is lost, I am using a ViewModel, my data loads when I push the button, this is my code for test .
https://github.com/elviss116/androidMvvm-master
This is the Fragment :
public class MovieListFragment extends Fragment {
private MovieListViewModel mViewModel;
private List<MovieModel.DataModel> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private MoviesAdapter mAdapter;
private Button cargar;
public static MovieListFragment newInstance() {
return new MovieListFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.movie_list_fragment, container, false);
recyclerView = (RecyclerView)view.findViewById(R.id.recycler_view);
cargar = view.findViewById(R.id.btnCargar);
mAdapter = new MoviesAdapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
cargar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mViewModel = ViewModelProviders.of(MovieListFragment.this).get(MovieListViewModel.class);
mViewModel.init();
mViewModel.getMovies().observe(MovieListFragment.this, new Observer<MovieModel>() {
#Override
public void onChanged(#Nullable MovieModel movieModels) {
movieList.addAll(movieModels.getData());
mAdapter.notifyDataSetChanged();
}
});
}
});
}
}
this is the ViewModel :
public class MovieModel {
#SerializedName("data")
List<DataModel> data;
public List<DataModel> getData() {
return data;
}
public void setData(List<DataModel> data) {
this.data = data;
}
public class DataModel {
#SerializedName("name")
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
this is the adapter :
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
private List<MovieModel.DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
}
}
public MoviesAdapter(List<MovieModel.DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.movie_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
MovieModel.DataModel movie = moviesList.get(position);
holder.name.setText(movie.getName());
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
When you rotate your phone the activity gets destroyed and re-created, so that is why you're seeing your data dissapear.
What I would recommend is grabbing and observing the view model when the activity is created, outside of the click listener. This way the fragment will immediately start observing the data when it is rotated, but will only be initialized when the button is clicked.
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(MovieListFragment.this).get(MovieListViewModel.class);
mViewModel.getMovies().observe(MovieListFragment.this, new Observer<MovieModel>() {
#Override
public void onChanged(#Nullable MovieModel movieModels) {
movieList.addAll(movieModels.getData());
mAdapter.notifyDataSetChanged();
}
});
cargar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mViewModel.init();
}
});
}

getAdapterPosition not doing what it is supposed to do

I have a RecyclerView Fragment to which I added a Filter Search in an edit text. It works, but when I click in a Card of the Recycler, it goes to the wrong detail. My best guess is that it's getting the wrong position from the getAdapterPosition since let's say I have this list {a,b,c,d,e,f,g,h}. when I filter and get two itmes left like {d,g}. If I click d it redirects to a, if I click g it redirects to b.
This is my RecyclerView
public class RecyclerProfile extends Fragment implements
Adapter.AdapterListener, com.example.cake.profiling.Adapter.SearchListener
{
private RecyclerListener recyclerListener;
private List<Profile> profiles = (new DAOProfile()).getProfile();
private Adapter recyclerAdapter= new Adapter(profiles, this);
public RecyclerProfile() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_recycler_profile,
container, false);
RecyclerView recyclerView = view.findViewById(R.id.recyclerProfile);
EditText editText = view.findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new
LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerAdapter);
setHasOptionsMenu(true);
return view;
}
private void filter(String text){
ArrayList<Profile> filteredList = new ArrayList<>();
for (Profile profile: profiles){
if (profile.getName().toLowerCase().contains(text.toLowerCase())){
filteredList.add(profile);
}
}
recyclerAdapter.filterList(filteredList);
profiles = new ArrayList<>(filteredList);
}
#Override
public void listen(Profile profile, Integer position) {
recyclerListener.send(profile, position);
}
#Override
public void profileSelected(Profile profile) {
}
//INTERFACE
public interface RecyclerListener {
void send(Profile profile, Integer position);
}
//ON ATTACH
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.recyclerListener = (RecyclerListener) context;
}
}
This is my Adapter
public class Adapter extends RecyclerView.Adapter<Adapter.ProfileViewHolder> {
private List<Profile> profiles;
private AdapterListener adapterListener;
//CONSTRUCTOR
public Adapter(List<Profile> profiles,AdapterListener adapterListener) {
this.profiles = profiles;
this.adapterListener = adapterListener;
}
#NonNull
#Override
public Adapter.ProfileViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.card_profile, parent, false);
ProfileViewHolder profileViewHolder = new ProfileViewHolder(view);
return profileViewHolder;
}
#Override
public void onBindViewHolder(#NonNull Adapter.ProfileViewHolder holder, int position) {
Profile profile = profiles.get(position);
holder.setter(profile);
}
#Override
public int getItemCount() {
return profiles.size();
}
public void filterList (ArrayList<Profile> filteredList){
profiles = filteredList;
notifyDataSetChanged();
}
//VIEWHOLDER
class ProfileViewHolder extends RecyclerView.ViewHolder{
private ImageView image;
private TextView name;
public ProfileViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.nameProfile);
image = itemView.findViewById(R.id.imageProfile);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Profile profile = profile.get(getAdapterPosition());
adapterListener.receive(profile, getAdapterPosition());
}
});
}
public void setter (Profile profile){
name.setText(profile.getName());
image.setImageResource(profile.getImage());
}
}
public interface AdapterListener {
void receive(Profile profile, Integer position);
}
}
getAdapterPosition()
this will return the position of the item of current data set. This is what I'd do
class ProfileViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView image;
private TextView name;
Profile mProfile;
public ProfileViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.nameProfile);
image = itemView.findViewById(R.id.imageProfile);
name.setOnClickListener(this);
image.setOnClickListener(this);
}
public void setter (Profile profile){
if(profile != null) {
mProfile = profile;
name.setText(mProfile.getName());
image.setImageResource(mProfile.getImage());
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.item_nameProfile:
case R.id.item_imageProfile:
for(int i = 0 ; i < profiles.size() ; i++) {
if(profiles.get(i).getName().equalsIgnoreCase(mProfile.getName()) {
adapterListener.receive(profiles.get(i), i);
break;
}
}
break;
}
}
public interface AdapterListener {
void receive(Profile profile, Integer position);
}
}

How to use getChildFragmentManager with a class that extends Dialog fragment

I am a having a fragment with TabLayout. As soon as I move from TabLayout Fragment to the next Fragment and press the back key. The content on the default TabLayout fragment disappears. I found a possible solution to this in the post. Following is the code for the TabLayout.
public class IndividualCollectionSheetFragment extends MifosBaseFragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private View rootView;
public IndividualCollectionSheetFragment() {
}
public static IndividualCollectionSheetFragment newInstance() {
Bundle args = new Bundle();
IndividualCollectionSheetFragment fragment = new IndividualCollectionSheetFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_individual_recycler, container, false);
ButterKnife.bind(this, rootView);
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet));
viewPager = rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new NewIndividualCollectionSheetFragment(), Constants.NEW);
adapter.addFragment(new SavedIndividualCollectionSheetFragment(), Constants.SAVED);
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
The solution in the post suggested using getChildFramentManager instead of getSupportFragmentManager. As soon as I changed to getChildFragmentManager. I got the error.
java.lang.IllegalStateException: Fragment CollectionSheetDialogFragment{572dd42 #0 Identifier Dialog Fragment} declared target fragment NewIndividualCollectionSheetFragment{45e8153 #0 id=0x7f090361 android:switcher:2131297121:0} that does not belong to this FragmentManager!
which might be because of the class CollectionSheetDialogFragment which extends DialogFragment and there must be inconsistencies with the different Fragment Managers being used.
NewIndividualCollectionSheet.java(first fragment in tablayout)
public class NewIndividualCollectionSheetFragment extends MifosBaseFragment implements
IndividualCollectionSheetMvpView, MFDatePicker.OnDatePickListener,
Spinner.OnItemSelectedListener, View.OnClickListener {
#BindView(R.id.btn_fetch_collection_sheet)
Button btnFetchSheet;
#BindView(R.id.sp_office_list)
Spinner spOffices;
#BindView(R.id.sp_staff_list)
Spinner spStaff;
#BindView(R.id.tv_repayment_date)
TextView tvRepaymentDate;
#Inject
NewIndividualCollectionSheetPresenter presenter;
private IndividualCollectionSheet sheet;
private DialogFragment datePicker;
private RequestCollectionSheetPayload requestPayload;
private View rootView;
private ArrayAdapter<String> officeAdapter;
private ArrayList<String> officeNameList;
private List<Office> officeList;
private ArrayAdapter<String> staffAdapter;
private ArrayList<String> staffNameList;
private List<Staff> staffList;
private int officeId;
private int staffId;
private int requestCode = 1;
private boolean success = true;
private String actualDisbursementDate;
private String transactionDate;
public NewIndividualCollectionSheetFragment() {
}
public static NewIndividualCollectionSheetFragment newInstance() {
Bundle args = new Bundle();
NewIndividualCollectionSheetFragment fragment = new NewIndividualCollectionSheetFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
if (savedInstanceState != null) {
sheet = (IndividualCollectionSheet) savedInstanceState.get(
Constants.EXTRA_COLLECTION_INDIVIDUAL);
}
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_new_collection_sheet, container, false);
ButterKnife.bind(this, rootView);
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet));
presenter.attachView(this);
setUpUi();
return rootView;
}
private void setUpUi() {
setRepaymentDate();
officeNameList = new ArrayList<>();
officeAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, officeNameList);
officeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOffices.setAdapter(officeAdapter);
spOffices.setOnItemSelectedListener(this);
staffNameList = new ArrayList<>();
staffAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, staffNameList);
staffAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spStaff.setAdapter(staffAdapter);
tvRepaymentDate.setOnClickListener(this);
btnFetchSheet.setOnClickListener(this);
presenter.fetchOffices();
}
void setRepaymentDate() {
datePicker = MFDatePicker.newInsance(this);
String date = DateHelper.
getDateAsStringUsedForCollectionSheetPayload(MFDatePicker.getDatePickedAsString());
tvRepaymentDate.setText(date.replace('-', ' '));
transactionDate = date.replace('-', ' ');
actualDisbursementDate = transactionDate;
}
private void prepareRequestPayload() {
requestPayload = new RequestCollectionSheetPayload();
requestPayload.setOfficeId(officeId);
requestPayload.setStaffId(staffId);
requestPayload.setTransactionDate(tvRepaymentDate.getText().toString());
}
#Override
public void setOfficeSpinner(List<Office> offices) {
officeList = offices;
officeNameList.clear();
officeNameList.add(getString(R.string.spinner_office));
officeNameList.addAll(presenter.filterOffices(officeList));
officeAdapter.notifyDataSetChanged();
}
#Override
public void onDatePicked(String date) {
String d = DateHelper.getDateAsStringUsedForCollectionSheetPayload(date);
tvRepaymentDate.setText(d.replace('-', ' '));
}
public void retrieveCollectionSheet() {
prepareRequestPayload();
presenter.fetchIndividualCollectionSheet(requestPayload);
}
public void setTvRepaymentDate() {
datePicker.show(getActivity().getSupportFragmentManager(),
FragmentConstants.DFRAG_DATE_PICKER);
}
#Override
public void setStaffSpinner(List<Staff> staffs) {
spStaff.setOnItemSelectedListener(this);
staffList = staffs;
staffNameList.clear();
staffNameList.add(getString(R.string.spinner_staff));
staffNameList.addAll(presenter.filterStaff(staffList));
staffAdapter.notifyDataSetChanged();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (adapterView.getId()) {
case R.id.sp_office_list:
if (i == officeList.size() || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_office));
} else {
Toaster.show(rootView, officeNameList.get(i));
officeId = officeList.get(i - 1).getId();
presenter.fetchStaff(officeId);
}
break;
case R.id.sp_staff_list:
if (i == staffList.size() || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_staff));
} else {
staffId = staffList.get(i - 1).getId();
}
break;
}
}
public void popupDialog() {
CollectionSheetDialogFragment collectionSheetDialogFragment =
CollectionSheetDialogFragment.newInstance(tvRepaymentDate.getText().toString(),
sheet.getClients().size());
collectionSheetDialogFragment.setTargetFragment(this, requestCode);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_DOCUMENT_LIST);
collectionSheetDialogFragment.show(fragmentTransaction, "Identifier Dialog Fragment");
}
public void getResponse(String response) {
switch (response) {
case "FillNow":
FragmentManager fm = getActivity()
.getSupportFragmentManager();
fm.popBackStack();
IndividualCollectionSheetDetailsFragment frag = new
IndividualCollectionSheetDetailsFragment().newInstance(sheet,
actualDisbursementDate, transactionDate);
((MifosBaseActivity) getActivity()).replaceFragment(frag,
true, R.id.container);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
#Override
public void showSheet(IndividualCollectionSheet individualCollectionSheet) {
sheet = individualCollectionSheet;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(Constants.EXTRA_COLLECTION_INDIVIDUAL, sheet);
}
#Override
public void showSuccess() {
if (success) {
popupDialog();
}
}
#Override
public void showError(String message) {
Toaster.show(rootView, message);
}
#Override
public void showNoSheetFound() {
success = false;
Toaster.show(rootView, getStringMessage(R.string.no_collectionsheet_found));
}
#Override
public void showProgressbar(boolean b) {
if (b) {
showMifosProgressDialog();
} else {
hideMifosProgressDialog();
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_repayment_date:
setTvRepaymentDate();
break;
case R.id.btn_fetch_collection_sheet:
retrieveCollectionSheet();
break;
}
}
}
CollectionSheetDialogFragment.java
public class CollectionSheetDialogFragment extends DialogFragment {
#BindView(R.id.tv_due_date)
TextView tvDueDate;
#BindView(R.id.tv_members)
TextView tvMembers;
#BindView(R.id.btn_fillnow)
Button btnFillnow;
#BindView(R.id.btn_cancel)
Button btnCancel;
private View rootView;
private String date;
private int members;
public CollectionSheetDialogFragment() {
}
public static CollectionSheetDialogFragment newInstance(String date, int members) {
CollectionSheetDialogFragment collectionSheetDialogFragment =
new CollectionSheetDialogFragment();
Bundle args = new Bundle();
args.putString(Constants.REPAYMENT_DATE, date);
args.putInt(Constants.MEMBERS, members);
collectionSheetDialogFragment.setArguments(args);
return collectionSheetDialogFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
date = getArguments().getString(Constants.REPAYMENT_DATE);
members = getArguments().getInt(Constants.MEMBERS);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable
ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_collection_sheet_dialog, container, false);
ButterKnife.bind(this, rootView);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tvDueDate.setText(date);
tvMembers.setText(Integer.toString(members));
}
#OnClick(R.id.btn_fillnow)
public void setBtnFillnow() {
((NewIndividualCollectionSheetFragment) getTargetFragment()).getResponse("FillNow");
}
#OnClick(R.id.btn_cancel)
public void setBtnCancel() {
getDialog().dismiss();
}
}
Can someone help me get around this error so I can persist the TabLayout On back press?
Maybe This Work :
Replace getFragmentManager() instead of getChildFragmentManager()
Try this changing seupViewPager() in IndividualCollectionSheetFragment.java like this
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
adapter.addFragment(new NewIndividualCollectionSheetFragment(), Constants.NEW);
adapter.addFragment(new SavedIndividualCollectionSheetFragment(), Constants.SAVED);
viewPager.setAdapter(adapter);
}

How can i pass a string value from recyclerview adapter to fragment

I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.

Categories