Change RecyclerView Contents After Clicking On an Item in a DropDown Menu - java

I have two containers in my home activity, one is Top Bar Fragment Container and the other is ViewPagers Container. Top Bar Fragment Container consist of only one fragment which is the Top Bar Fragment (allows the user to pick a tag) while Viewpagers consists of 2 fragment which in each fragments they have a recycler view to display the posts with the selected tags on Top Bar Fragment.
What im trying to achieve is that when an item is clicked on the Top Bar Fragment, it gets the value to text then sends it to the Activity using an Interface and later on Fragment Viewpagers will get that value from the activity and set the firebase query in accordance with the text passed.
So far, the fragments are doing fine sending data to each other using interfaces. However, adapters only listens once, when view is created and not when data is passed from Fragments. How do I update the adapters after sending in data from Top Bar Fragment?
Here is my ViewPagerFragment(RecyclerView):
FirebaseRecyclerOptions options, options2;
FirebaseRecyclerAdapter<Question, QuestionsViewHolder> adapter;
<!---- oncreate Code---->
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
String ChosenTag = tvtest.getText().toString();
if (text.equals("")){
Query query = questionReference.orderByChild("location").equalTo("jakarta");
options = new FirebaseRecyclerOptions.Builder<Question>()
.setQuery(query, Question.class)
.build();
adapter = new FirebaseRecyclerAdapter<Question, QuestionsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull QuestionsViewHolder holder, int position, #NonNull Question model) {
holder.username.setText(model.getUsername());
}
#NonNull
#Override
public QuestionsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.snippet_card_question_new, viewGroup, false);
QuestionsViewHolder viewHolder = new QuestionsViewHolder(view);
return viewHolder;
}
};
qListRv.setAdapter(adapter);
adapter.startListening();
} else {
Query query = questionReference.orderByChild("tags").equalTo(ChosenTag);
options2 = new FirebaseRecyclerOptions.Builder<Question>()
.setQuery(query, Question.class)
.build();
adapter.updateOptions(options2);
}
}
To put it simply, if user has not chosen on the TopBarFragment then text is returning a null, adapter will then query on the current location of the user. Else if user chose a tag on the Top Bar Fragment, Top Bar Fragment then sends the tag to string, updates the String ChosenTag, then adapter will then update its options to options2, which queries on the chosen tag.
I am not able to refresh my recyclerview after choosing. Yet interfaces work fine. Is there any way to achieve this?

I've searched everywhere and it seems like none could help me out, so here is what i've done and this worked for me. Hope this helps.
I changed the Fragment B (TopBarFragment) to an Activity (TopBarActivity)
The reason why i changed the fragment to an activity is because i wanted the whole RecyclerView Adapters to stop listening whenever a user is directed to the TopBar Activity. This way i can initiate a new adapter upon returning to the Activity that holds the RecyclerViews.
The Plan
Make two sets of Adapters (one for defaultAdapter, the other for
what the user click on TopBarActivity. let's call it
menuItemAdapter).
Extras to send strings from TopBarActivity upon user clicks to MainActivity. From then Fragments will check the Strings of the
MainActivity.
Create two override methods (onPause & onResume), to either stop listening to the adapters, or start listening to them. We will
create conditions here to either listen to default adapters or
listen to what the user clicks. These Conditions will check if
Strings on point 2 exist or not. If it exists then listen to
menuItemAdapter else if strings does not exist, then listen to
defaultAdapters.
TopBarActivity Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_bar);
//I am using Recycler view to display the menu item lists on this activity.
//RecyclerView Codes goes here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), MainActivity.class);
i.putExtra("CHOSENITEM", (model.getItemName()));
startActivity(i);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private String choicesName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
setupTopBarStringListener();
}
private void setupTopBarStringListener() {
choicesName = getIntent().getStringExtra("CHOSENITEM");
}
public String ChoicesString() {
return choicesName;
}
}
String ChoicesString() will then be called later on in Fragment A
Fragment A Code
public class QuestionFragment extends Fragment {
private String myStringFromActivity;
RecyclerView contentListRv;
FirebaseRecyclerOptions options, newoptions;
FirebaseRecyclerAdapter<Post, PostsViewHolder> adapter, newadapters;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "onViewCreated: restart");
contentListRv= view.findViewById(R.id.contentListRv);
contentListRv.setLayoutManager(new LinearLayoutManager(getContext()));
HomeActivity activity = (HomeActivity) getActivity();
myStringFromActivity = activity.ChoicesString();
Log.i(TAG, "choices from activity= " + myStringFromActivity);
}
}
Add Default Recyclers to Fragment A
public void setupRecyclers() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dschild : dataSnapshot.getChildren()) {
String location = "" + dschild.child("location").getValue();
Query query = questionReference.orderByChild("location").equalTo(location);
options = new FirebaseRecyclerOptions.Builder<Question>()
.setQuery(query, Post.class)
.build();
adapter = new FirebaseRecyclerAdapter<Post, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull PostsViewHolder holder, int position, #NonNull Question model) {
holder.username.setText(model.getUsername());
}
#NonNull
#Override
public QuestionsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.snippet_posts_view, viewGroup, false);
PostsViewHolder viewHolder = new PostsViewHolder(view);
return viewHolder;
}
};
contentListRV.setAdapter(adapter);
adapter.startListening();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Then add menuItem Recyclers to Fragment A
public void menuItemRecyclers() {
Query query2 = questionReference.orderByChild("tags").equalTo(myStringFromActivity);
newoptions = new FirebaseRecyclerOptions.Builder<Question>()
.setQuery(query2, Post.class)
.build();
newadapters = new FirebaseRecyclerAdapter<Post, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull PostsViewHolder holder, int position, #NonNull Question model) {
holder.username.setText(model.getUsername());
}
#NonNull
#Override
public QuestionsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.snippet_posts_view, viewGroup, false);
PostsViewHolder viewHolder = new PostsViewHolder(view);
return viewHolder;
}
};
contentListRV.setAdapter(newadapters);
newadapters.startListening();
}
}
}
The code above shows that the String myStringFromActivity retrieved from MainActivity will be our query for the new Adapters.
Finally, we implement the onPause and onResume Methods to our Fragment A
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "onStop: adapter stopped");
if(myStringFromActivity== null){
adapter.stopListening();
} else {
newadapters.stopListening();
}
}
#Override
public void onResume() {
super.onResume();
if(myStringFromActivity==null){
setupRecyclers();
Log.e(TAG, "onResume: String null" );
}else{
menuItemRecyclers();
}
}
Code above shows that if we String myStringFromActivity is null (user hasn't clicked on any items in our Topbaractivity, then it runs the default Recyclers. Else if the user picked on an item then it runs the menuItemRecyclers (based on what the user chooses).
I am still open to better implementation regarding this one. Hope this helps!

Related

Calling a fragment and getting the id in the RecyclerView adapter

I have a list using the RecyclerView, what I want is that when I click on the list item, it opens a fragment, I've been searching and I only found it with an activity, but I'm working only with fragments, if I use activity it disappears with my action bar, it's all set in the fragment.
This is my adapter class:
public class CreditCardAdapter extends RecyclerView.Adapter<CreditCardHolder> {
private final List<CreditCard> creditList;
public CreditCardAdapter(List<CreditCard> creditList) {
this.creditList = creditList;
}
#NonNull
#Override
public CreditCardHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.credit_card_item, parent, false);
return new CreditCardHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CreditCardHolder holder, int position) {
CreditCard credit = creditList.get(position);
String flag = credit.getFlag();
holder.flag.setText(flag);
String owner = credit.getOwner();
holder.owner.setText(owner);
String valueLimit = String.format("%.2f", credit.getLimit());
holder.limit.setText(valueLimit.replace(".", ","));
holder.creditCardId = credit.getId();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Method on click
}
});
}
#Override
public int getItemCount() {
return creditList.size();
}
}
I need to send the credit card id to the fragment, to call the controller and get the information from the database, I tried it with the intent, but it only worked if I call the activity with startActivity(intent).
So here it is the fragment class:
public class InfoCreditCardFragment extends Fragment {
public InfoCreditCardFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_info_credit_card, container, false);
String id; //Here I need the id from the Adapter
TextView flagInfoTxt = view.findViewById(R.id.flagInfoTxt);
TextView ownerInfoTxt = view.findViewById(R.id.ownerInfoTxt);
CreditCard cc = CreditCardController.getWithId(id);
flagInfoTxt.setText(cc.getFlag());
ownerInfoTxt.setText(cc.getOwner());
return view;
}
}
If anyone knows anything to help, please, I'm desperate.
So, I managed to go to the fragment using this:
Bundle bundle = new Bundle();
bundle.putString("id", holder.creditCardId);
InfoCreditCardFragment fragment = new InfoCreditCardFragment();
AppCompatActivity activity = (AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, fragment).addToBackStack(null).commit();
And inside the fragment I just get the bundle with "getArguments().getString("id");"

How to show all child data from firebase but exclude specific child inside a recycleview?

I am doing my project where the function is user can select a time slot from tutor that showing in a recycleview. The tutor also is a user, so i want to implement a function that can retrieve data(time slot) except the data(time slot) from who are searching. The related query method is orderbyChild().equalTo(), but i know it cant use for inequality.
I set "TimeSlotsRef" as DatabaseReferences object to getInstances and getReference from child("TimeSlots").
For now i only can set query as "TimeSlotsRef" to show data inside recycleview, so can someone provide me a query method to retrive all data from a child except data from a specific nested child?
Below is my code:
public void onStart(){
super.onStart();
TimeSlotsRef = FirebaseDatabase.getInstance().getReference()
.child("Time Slots");
FirebaseRecyclerOptions<TimeSlots> options =
new FirebaseRecyclerOptions.Builder<TimeSlots>()
.setQuery(TimeSlotsRef, TimeSlots.class)
.build();
FirebaseRecyclerAdapter<TimeSlots, TimeSlotViewHolder> adapter =
new FirebaseRecyclerAdapter<TimeSlots, TimeSlotViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull TimeSlotViewHolder holder, int i, #NonNull TimeSlots model)
{
holder.txtTutorName.setText(model.getTutorID());
holder.txtTutorTime.setText(model.getStartTime() + " - " + model.getEndTime());
holder.txtTutorDate.setText(model.getDate());
holder.txtArea.setText(model.getArea());
holder.txtTutorPrice.setText(model.getPrice());
holder.txtTutorSubject.setText(model.getSubject());
holder.txtLevel.setText(model.getLevel());
holder.txtCategory.setText(model.getCategory());
Picasso.get().load(model.getTutorImage()).placeholder(R.drawable.blank_profile).into(holder.tutorImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), SpecificTimeSlotDetailsActivity.class);
intent.putExtra("timeSlotID", model.getTimeSlotID());
startActivity(intent);
}
});
}
#NonNull
#Override
public TimeSlotViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.tutor_item_layout, parent, false);
TimeSlotViewHolder holder = new TimeSlotViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening(); }

How to call onRewardedVideoAdLoaded in onBindViewHolder

I want to use admob with recyclerview but there is a problem. I need to hide some elements that are belong to viewholder. I need to hide the imageview in which position the ImageView belongs. When i click holder.btnReklamIzle the picture in that position must be hid in onRewardedVideoAdLoaded method. How can i transmit the position to onRewardedVideoAdLoaded method?
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_kuponlar, container, false);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(KuponlarFragment.this.getActivity());
mRewardedVideoAd.setRewardedVideoAdListener(this);
tahminlerRecyclerView = root.findViewById(R.id.tahminlerRecyclerView);
linearLayoutManager = new LinearLayoutManager(this.getActivity());
tahminlerRecyclerView.setLayoutManager(linearLayoutManager);
tahminlerRecyclerView.setHasFixedSize(true);
loadRewardedVideoAd();
fetch();
return root;
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd(getString(R.string.admob_ads_id),
new AdRequest.Builder().build());
}
private void fetch() {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("tahminler");
FirebaseRecyclerOptions<Mac> options =
new FirebaseRecyclerOptions.Builder<Mac>()
.setQuery(query, new SnapshotParser<Mac>() {
#NonNull
#Override
public Mac parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Mac((double)snapshot.child("oran").getValue(),
snapshot.child("tahmin").getValue().toString(),
);
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Mac, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tahmin_tasarim_recyclerview, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(final ViewHolder holder, final int position, Mac mac) {
holder.btnReklamIzle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}});
}
};
tahminlerRecyclerView.setAdapter(adapter);
}
#Override
public void onRewardedVideoAdLoaded() {
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
}
}
onRewardedVideoAdLoaded is a callback method for an asynchronous operation hence you cannot pass values to it as arguments but use referenced variables.
For your case do the following:
Firstly
Create a global variable to hold the list of views to hide
ArrayList<View> views_to_hide = new ArrayList<>();
Secondly
Create a helper function to hide the views
function hideViews(ArrayList<View> views){
for(View v : views) v.setVisibility(View.GONE);
}
Thirdly
Inside onBindViewHolder Add to the list the views you want to hide under your button onClick
public void onClick(View v) {
//...
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
// Ads already shown you may want to manually hide other images here
}else{
// We only need to add to list when ads not loaded
// We also want to make sure we don't add same view to the list twice
if(!views_to_hide.contains(holder.image))
views_to_hide.add(holder.image);
}});
//...
Finally
Call your helper function inside onRewardedVideoAdLoaded
#Override
public void onRewardedVideoAdLoaded() {
//This hides the views that was added to the list before now
hideViews(views_to_hide);
}

showing RecyclerView on fragment with data from Firebase

I'm having a problem with making a RecycleView in a fragment with data from Firebase. I expect the app to show the RecycleView after I clicked on a button to change from one fragment to the RecycleView fragment, but it does change the showed fragment but it does not show anything.
I know there are plenty of questions like this but I don't seem to find the correct solution to this problem.
I've made everything needed for a Firebase RecyclerView, and also tried to build it inside an activity instead fragment and it did work, but not with the fragment.
I've tried to initialize the adapter and recyclerview inside the onCreateView method, onActivityCreated, and onViewCreated method and none of them seem to be working.
Here's my fragment code:
private KidAdapter adapter;
private RecyclerView recyclerView;
Button button;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.uangsaku_menu_fragment, container, false);
button = view.findViewById(R.id.btn_add);
button.setOnClickListener(this);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
setUpRecyclerView();
return view;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_add){
Intent intent = new Intent(getActivity(), Register.class);
startActivity(intent);
}
}
public void setUpRecyclerView(){
Query query = FirebaseDatabase.getInstance().getReference("kids");
FirebaseRecyclerOptions<kidData> options = new FirebaseRecyclerOptions.Builder<kidData>()
.setQuery(query, kidData.class)
.build();
adapter = new KidAdapter(options);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
if (adapter != null) {
adapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
The adapter class
public class KidAdapter extends FirebaseRecyclerAdapter<kidData, KidAdapter.KidViewHolder> {
public KidAdapter(#NonNull FirebaseRecyclerOptions<kidData> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull KidViewHolder holder, int position, #NonNull kidData model) {
holder.nama.setText(model.getKidName());
holder.balance.setText(model.getKidBalance());
holder.limit.setText("Limit: "+model.getKidLimit());
holder.spending.setText("Spending xxx.xxx");
}
#NonNull
#Override
public KidViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.kids_card,
viewGroup, false);
return new KidViewHolder(v);
}
public class KidViewHolder extends RecyclerView.ViewHolder {
TextView nama, balance, limit, spending;
public KidViewHolder(#NonNull View itemView) {
super(itemView);
nama = itemView.findViewById(R.id.tv_nama);
balance = itemView.findViewById(R.id.tv_balance);
limit = itemView.findViewById(R.id.tv_dailylimit);
spending = itemView.findViewById(R.id.tv_dailyspending);
}
}
}
The kidData model class
public class kidData {
String kidName, kidEmail, kidDoB, kidLimit, kidBalance;
public kidData(){
}
public kidData(String kidName, String kidEmail, String kidDoB, String kidLimit, String kidBalance) {
this.kidName = kidName;
this.kidEmail = kidEmail;
this.kidDoB = kidDoB;
this.kidLimit = kidLimit;
this.kidBalance = kidBalance;
}
public String getKidName() {
return kidName;
}
public String getKidEmail() {
return kidEmail;
}
public String getKidDoB() {
return kidDoB;
}
public String getKidLimit() {
return kidLimit;
}
public String getKidBalance() {
return kidBalance;
}
}
The problem in your code is the use of the following line of code:
recyclerView.setHasFixedSize(true);
And this is because when using the latest version of Firebase-UI library, there is no need to set the size of the RecyclerView as fixed. The solution for solving this problem is to simply remove/comment the above line of code. That's it!

ListView not populated. Problem with ViewPager and fragments

I have three fragments switched using a ViewPager and the third one contains a ListView.
My problem is that the ListView is not populated on the first time that I switch to that fragment. I have to switch back to the first then back to the third again and only will the ListView be populated. What seems to be the problem here?
How does ViewPager works anyways?
Here is my TabAdapter
public class TabAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
TabAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
Here is ListAdapter for the listView
public class ListAdapter extends BaseAdapter {
private ArrayList data = new ArrayList();
public ListAdapter(LinkedHashMap<String, ArrayList<String>> lhm) {
try {
data.addAll(lhm.entrySet());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return data.size();
}
#Override
public LinkedHashMap.Entry<String, ArrayList<String>> getItem(int position) {
return (LinkedHashMap.Entry) data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final LinkedHashMap.Entry<String, ArrayList<String>> item = getItem(position);
final ArrayList quotesList = item.getValue();
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.archive_list, parent, false);
}
TableRow tableRow = convertView.findViewById(R.id.container);
TextView title = convertView.findViewById(R.id.title);
ImageView copy = convertView.findViewById(R.id.copy);
copy.setVisibility(View.INVISIBLE);
title.setText(item.getKey() + " Quotes");
tableRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ViewActivity.class);
intent.putExtra("title", item.getKey());
intent.putStringArrayListExtra("quotes", quotesList);
if (interstitialAd.isLoaded()) {
interstitialAd.show();
startActivity(intent);
} else {
startActivity(intent);
}
}
});
return convertView;
}
}
Update
The problem seems to be from the Linkedhashmap. I tried manually putting values into the Hashmap and it worked. The problem now is my current code. I populate my hashmap by retrieving data from firebase and that seems to be the problem? Pershaps it isn't populated as quickly?
private void initArchives() {
DatabaseReference dBase = FirebaseDatabase.getInstance().getReference().child("archive");
dBase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
DataPojo dp = snapshot.getValue(DataPojo.class);
hm.put(dp.getName(), dp.getMessages());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_archive, container, false);
listView = view.findViewById(R.id.listView);
searchView = view.findViewById(R.id.searchView);
initArchives();
listAdapter = new ListAdapter(hm);
listView.setAdapter(listAdapter);
listView.invalidateViews();
loadAds();
return view;
}
First of all FragmentStatePagerAdapter is really a pain in the ass. But we have to work with that. I suggest you to Ctrl + click on FragmentStatePagerAdapter and read source code.
Another thing is adding fragments to your ArrayList with addFragment() method might not be the best idea since FragmentStatePagerAdapter is saving the states of the fragments and loads them from its own FragmentManager.
So the fragment you added might not be the fragment you are getting.
A possible solution to that would be using tags.
There are some must read articles about the topic here here and here.
And oh one other thing. ViewPager creates three fragments at a time when using FragmentStatePagerAdapter. First it creates fragment to display and next the fragment on the right and last the fragment on the left. Since you have three fragments, the last (3rd) fragment is not created right away (There is no fragment on the left of the first fragment). Maybe you are loading some data that takes time to download on the third fragment? And next time you display the 3rd fragment it loads from the saved state of FragmentStatePagerAdapter. These are just some possibilities to think about. Not necessarily is the right solution. Good luck.

Categories