RecyclerView disappearing after switching between fragments on a particular Activity - java

The problem I have been facing with the development is that there is a recyclerview inside my fragment which gets disappeared after I switch between two fragments on a particular activity. On the first time when the fragment loads everything works fine but afterwards I don't understand what goes wrong. I had tried to refer to various ways that people had posted over github like notifyDatasetChanged, etc. But nothing seems to work. I would appreciate if someone could help me out with this issue.
So here are my classes.
The ProfileFragment.java :
public class ProfileFragment extends Fragment {
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
RecyclerView itemRecycler;
List<ModelProfile> modelProfiles;
AdapterProfile adapterProfile;
String storagePath= "Users_Profile_Cover_Image/-";
ImageView avatarIv,dp;
CardView card,cardArrow;
TextView nameTv, emailTv, phoneTv;
Button logout,update;
ExtendedFloatingActionButton fab;
ProgressDialog pd;
//..
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view= inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user= firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference= getInstance().getReference();
loadItems();
return view;
}
private void loadItems() {
//Problem could be here
GridLayoutManager layoutManager= new GridLayoutManager(getContext(),3);
itemRecycler.setHasFixedSize(true);
itemRecycler.setLayoutManager(layoutManager);
itemRecycler.setVisibility(View.VISIBLE);
CollectionReference ref =FirebaseFirestore.getInstance().collection("All_Posts");
com.google.firebase.firestore.Query query = ref.whereEqualTo("uid",uid);
FirestoreRecyclerOptions<ModelProfile> options = new FirestoreRecyclerOptions.Builder<ModelProfile>()
.setQuery(query,ModelProfile.class).build();
adapterProfile = new AdapterProfile(options,getActivity());
itemRecycler.setAdapter(adapterProfile);
adapterProfile.startListening();
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
assert value != null;
Log.i("Size",String.valueOf(value.getDocuments().size()));
if (value.getDocuments().size() > 0) { // List is populated
card.setVisibility(View.GONE);
cardArrow.setVisibility(View.GONE);
} else { // List is empty
card.setVisibility(View.VISIBLE);
cardArrow.setVisibility(View.VISIBLE);
}
}
});
}
//
// #Override
// public void onStart() {
// super.onStart();
// adapterProfile.startListening();
// }
//
//
//
// #Override
// public void onStop() {
// super.onStop();
// adapterProfile.stopListening();
// }
#Override
public void onResume() {
super.onResume();
adapterProfile.startListening();
}
}
Adapter:-
public class AdapterProfile extends FirestoreRecyclerAdapter<ModelProfile,AdapterProfile.MyHolder> {
Context context;
public String im;
public AdapterProfile(#NonNull FirestoreRecyclerOptions<ModelProfile> options, Activity Context) {
super(options);
context = Context;
}
#Override
protected void onBindViewHolder(#NonNull MyHolder holder, int position, #NonNull ModelProfile model) {
String uid = model.getUid();
String uEmail =model.getuEmail();
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//..
}
class MyHolder extends RecyclerView.ViewHolder{
//..
}
Activity on which Fragment switching takes place
public class LandingActivity extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference userDbRef;
FirebaseUser user;
String uid,dp;
ChipNavigationBar chipNavigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();
bottomMenu();
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
//problem could be here as well.........
#Override
public void onItemSelected(int i) {
Fragment fragment=null;
switch(i) {
case R.id.bottom_nav_2:
fragment = new CltFragment();
break;
case R.id.bottom_nav_3:
fragment = new MaceFragment();
break;
case R.id.bottom_nav_profile:
fragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
}
private void checkUserStatus()
{
FirebaseUser user= firebaseAuth.getCurrentUser();
if(user !=null)
{
uid=user.getUid();
}
else
{
startActivity(new Intent(LandingActivity.this,MainActivity.class));
finish();
}
}
#Override
public void onResume() {
//Problem could be here
super.onResume();
Intent intent = getIntent();
String frag = "";
if(intent.hasExtra("frag")) {
frag = intent.getExtras().getString("frag");
}
else
{
//..
}
switch(frag)
{
//..
case "ProfileFragment":
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ProfileFragment()).commit();
chipNavigationBar.setItemSelected(R.id.bottom_nav_profile,true);
break;
}
}
}
Thanks for having looked at my Problem!

Try using this
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new InventoryFragment()).commit();
Instead of this
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();

Related

Firebase firestore Recycle View in fragment. How to do delete on slide

I'm working on my school project with Firebase firestore and firebase Auth. It's something like a Kanban app.
My intend is to add delete documents from database while slide, and move documents to another catalog while sliding left-right. My main activity (TestActivity) is tabbed, so I want the deletion or moving to depend on direction and actual tab. Each tab have own Recycle View. You know: To do, In progress, Done.
I tried to follow Code Flow: https://www.youtube.com/watch?v=ub6mNHWGVHw&list=PLrnPJCHvNZuAXdWxOzsN5rgG2M4uJ8bH1
but my project need fragments, and with them, his "NoteAdapter" doesn't work. I found this tutorial: https://www.youtube.com/watch?v=FFHuYcB3YnU
and used it to place the adapter in right fragment.
Everything works until I want to do something with the firebase documents. This doesn't work at all or I just don't have idea where to place it:
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
Im using firebase and fragments first time.
Here comes some of my code: TestActivity (my main, I have also a drawer with user info and signout button, but this button which doesn't work,too):
public class TestActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private TabLayout tabLayout;
private ViewPager viewPager;
private SectionsPagerAdapter adapter;
private DrawerLayout drawer;
FirebaseAuth mAuth;
FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toolbar toolbar = findViewById(R.id.toolbar); // toolbar staje sie action bar
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
updateNavHeader();
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new TodoFragment(), "To Do");
adapter.AddFragment(new InprogressFragment(), "In Progress");
adapter.AddFragment(new DoneFragment(), "Done");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.add_todo);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Add new item", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
updateUI();
}
});
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// po zalogowaniu dane w drawer sie zmienia
public void updateNavHeader() {
NavigationView navigationView =(NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navUserName = headerView.findViewById(R.id.nav_username);
TextView navUserEmail = headerView.findViewById(R.id.nav_useremail);
ImageView userAvatar = headerView.findViewById(R.id.nav_useravatar);
navUserName.setText(currentUser.getDisplayName());
navUserEmail.setText(currentUser.getEmail());
if (currentUser.getPhotoUrl() != null) {
Glide.with(this).load(currentUser.getPhotoUrl()).into(userAvatar);
} else {
Glide.with(this).load(R.drawable.userphoto).into(userAvatar);
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (item.getItemId() == R.id.nav_signout) {
FirebaseAuth.getInstance().signOut();
Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void updateUI() {
Intent NewActivity = new Intent(getApplicationContext(), NewActivity.class);
startActivity(NewActivity);
finish();
}
}
TodoFragment:
public class TodoFragment extends Fragment {
private View v;
private RecyclerView recyclerView;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference TodoRef= db.collection("ToDo");
FirebaseAuth mAuth;
String Uemail;
public TodoFragment() {
// Required empty public constructor
}
public static TodoFragment newInstance() {
TodoFragment fragment = new TodoFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
Query q =TodoRef.whereEqualTo("email", Uemail);
FirestoreRecyclerOptions options=new FirestoreRecyclerOptions.Builder<Item>().setQuery(q, Item.class).build();
FirestoreRecyclerAdapter<Item, ItemViewHolder>adapter= new FirestoreRecyclerAdapter<Item, ItemViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ItemViewHolder itemViewHolder, int i, #NonNull Item item) {
itemViewHolder.textViewItem.setText(item.getTextitem());
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
ItemViewHolder viewHolder = new ItemViewHolder(v);
return viewHolder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class ItemViewHolder extends RecyclerView.ViewHolder{
TextView textViewItem;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
textViewItem = itemView.findViewById(R.id.item_text);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_todo, container, false);
recyclerView = v.findViewById(R.id.recycler_view_todo);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth=FirebaseAuth.getInstance();
Uemail= mAuth.getCurrentUser().getEmail();
return v;
}
}
My Item class:
public class Item {
private String textitem;
private String email;
public Item(){
//needed
}
public Item(String textitem, String email) {
this.email=email;
this.textitem=textitem;
}
public String getTextitem() {
return textitem;
}
public void setTextitem(String textitem) {
this.textitem = textitem;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
And my Section Pager Adapter:
public SectionsPagerAdapter( FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
#Override
public int getCount() {
return titles.size();
}
public void AddFragment(Fragment fragment, String title ){
fragments.add(fragment);
titles.add(title);
}
}
I did my best to find the solution on my own, but I apparently failed.
EDIT:
I finally found out how to handle it.
I moved adapter to independent class again, but with little changes in both fragments and adapter.
My adapter now: (with moving and deleting docs in Firestore)
public class ItemAdapter extends FirestoreRecyclerAdapter<Item, ItemAdapter.NoteHolder> {
public ItemAdapter(#NonNull FirestoreRecyclerOptions<Item> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder holder, int position, #NonNull Item model) {
holder.textViewTitle.setText(model.getTextitem());
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,
parent, false);
return new NoteHolder(v);
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
Log.d("Firestore", "DocumentSnapshot successfully deleted!");
}
public void moveItem(int position, CollectionReference ColRef) {
DocumentReference from= getSnapshots().getSnapshot(position).getReference();
DocumentReference to =ColRef.document();
moveFirestoreDocument( from, to);
}
public void moveFirestoreDocument(final DocumentReference fromPath, final DocumentReference toPath) {
fromPath.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
toPath.set(document.getData())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("Firestore", "DocumentSnapshot successfully written!");
fromPath.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("Firestore", "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("Firestore", "Error deleting document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("Firestore", "Error writing document", e);
}
});
} else {
Log.d("Firestore", "No such document");
}
} else {
Log.d("Firestore", "get failed with ", task.getException());
}
}
});
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
public NoteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.item_text);
}
}
}
And my Fragment now looks like this:
public class TodoFragment extends Fragment {
private View v;
private RecyclerView recyclerView;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference TodoRef = db.collection("ToDo");
CollectionReference InProgRef = db.collection("InProgress");
ItemAdapter adapter;
FirebaseAuth mAuth;
String Uemail;
public TodoFragment() {
}
public static TodoFragment newInstance() {
TodoFragment fragment = new TodoFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_todo, container, false);
recyclerView = v.findViewById(R.id.recycler_view_todo);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth=FirebaseAuth.getInstance();
Uemail= mAuth.getCurrentUser().getEmail();
setUpRecyclerView(recyclerView);
return v;
}
private void setUpRecyclerView(RecyclerView recyclerView) {
Query q =TodoRef.whereEqualTo("email", Uemail);
FirestoreRecyclerOptions<Item> options = new FirestoreRecyclerOptions.Builder<Item>()
.setQuery(q, Item.class)
.build();
adapter = new ItemAdapter(options);
recyclerView.setAdapter(adapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT|ItemTouchHelper.UP) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int right = 8;
if(direction==right){
adapter.moveItem(viewHolder.getAdapterPosition(),InProgRef);
}else{
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}
}).attachToRecyclerView(recyclerView);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
To sum up:
setUpRecyclerView function neded to get the right Recycler View as an argument, without it there was NullPointer Excepction all the time.
I made a mistake with wrong layout in inflaters, too
Hope it will be usefull for somebody.

How do I send data from fragment to another activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
In my app, i have an activity that have recyclerview inside a fragment and the recycleview retrieve data from cloud store Firebase. I want to open new activity that will retrieve the data according to the link(that display on the recycler view) user has clicked.
How do i get the data and display it in new activity?
From ForumTitle.java > Show ReviewFragment.java > User click a value > Show ForumInterface.java
ForumTitle.java
public class ForumTitle extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
ImageButton IVReview,IVTechnical,IVHardware;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_title);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment selectedFragment = null;
if (v == findViewById(R.id.iBReview)){
selectedFragment = new ReviewFragment();
}
else if (v == findViewById(R.id.iBTech)){
selectedFragment = new TechnicalSupportFragment();
}
else if (v == findViewById(R.id.iBHardware)){
selectedFragment = new HardwareFragment();
}
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,selectedFragment);
transaction.commit();
}
};
IVReview = (ImageButton)findViewById(R.id.iBReview);
IVTechnical = (ImageButton)findViewById(R.id.iBTech);
IVHardware = (ImageButton)findViewById(R.id.iBHardware);
IVReview.setOnClickListener(listener);
IVTechnical.setOnClickListener(listener);
IVHardware.setOnClickListener(listener);
}
}
ReviewFragment.java
public class ReviewFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference userRef = db.collection("Review");
private ForumAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_review,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Query query = userRef.orderBy("DatePosted",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Forum> options = new
FirestoreRecyclerOptions.Builder<Forum>()
.setQuery(query,Forum.class)
.build();
adapter = new ForumAdapter(options);
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.rvReview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new ForumAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
Forum forum = documentSnapshot.toObject(Forum.class);
String title = forum.getTitle();
String id = documentSnapshot.getId();
Intent intent = new Intent(getActivity(), ForumInterface.class);
Bundle extras = intent.getExtras();
extras.putString("FORUM_TYPE","Review");
extras.putString("FORUM_ID",id);
extras.putString("TITLE",title);
startActivity(intent);
}
});
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
ForumInterface.java
public class ForumInterface extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
private CollectionReference userRef = db.collection(forum_type).document(forum_id).collection(forum_title);
private ForumAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_interface);
TextView test = (TextView)findViewById(R.id.tvForumTitle);
test.setText(forum_title);
}
}
ForumAdapter.java
public class ForumAdapter extends FirestoreRecyclerAdapter<Forum,ForumAdapter.ForumHolder> {
private OnItemClickListener listener;
public ForumAdapter(FirestoreRecyclerOptions<Forum> options) {
super(options);
}
#Override
public void onBindViewHolder(ForumHolder forumHolder, int i, Forum forum) {
forumHolder.textViewTitle.setText(forum.getTitle());
forumHolder.textViewDescription.setText(forum.getDescription());
forumHolder.timeStamp.setText(forum.getDatePosted().toString());
}
#NonNull
#Override
public ForumHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
android.view.View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforumtitle,parent,false);
return new ForumHolder(v);
}
class ForumHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDescription;
TextView timeStamp;
public ForumHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.title);
textViewDescription = itemView.findViewById(R.id.description);
timeStamp = itemView.findViewById(R.id.timestamp);
textViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
// NO_POSITION to prevent app crash when click -1 index
if(position != RecyclerView.NO_POSITION && listener !=null ){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return super.getItemCount();
}
}
With the code above i run it, i got an error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Bundle.putString(java.lang.String, java.lang.String)' on a null object reference
at my.edu.fsktm.um.finalproject.Fragment.ReviewFragment$1.onItemClick(ReviewFragment.java:61)
at my.edu.fsktm.um.finalproject.ForumTitle.ForumAdapter$ForumHolder$1.onClick(ForumAdapter.java:56)
The picture of my app
When I clicked the title "GTX 1660 Ti Gaming X"
You try to set content on a Bundle which is null in your ReviewFragment's onClick. Use new Bundle() instead of intent.getExtras(); to instantiate Bundle
Bundle extras = new Bundle();
extras.putString("FORUM_TYPE","Review");
extras.putString("FORUM_ID",id);
extras.putString("TITLE",title);
//You have to set the bundle to intent
intent.putExtras(extras);
startActivity(intent);
Beside this move below code inside onCreate of ForumInterface Activity
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
And here is the complete Activity.
public class ForumInterface extends AppCompatActivity {
private FirebaseFirestore db;
private CollectionReference userRef;
private ForumAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_interface);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
db = FirebaseFirestore.getInstance();
userRef = db.collection(forum_type).document(forum_id).collection(forum_title);
TextView test = (TextView)findViewById(R.id.tvForumTitle);
test.setText(forum_title);
}
}

SearchData Method resets query? Firebase Database Android

In general, the thing is, I have three fragments. In the second snippet, it gets the data provided, here's the code.
1)MyPostFragment.class
public class MyPostsFragment extends PostListFragment {
public MyPostsFragment() {}
#Override
public Query getQuery(DatabaseReference databaseReference) {
return databaseReference.child("songsDB")
.orderByChild("stars/" + getUid())
.equalTo(true);
}
2)PostListFragment
public abstract class PostListFragment extends Fragment {
private DatabaseReference mDatabase;
private FirebaseRecyclerAdapter mAdapter;
private RecyclerView mRecycler;
private Activity mActivity;
Query mRef;
SearchView searchView;
LinearLayoutManager mManager;
FirebaseDatabase mFirebaseDatabase;
public PostListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
mRecycler = rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
mDatabase = FirebaseDatabase.getInstance().getReference();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
// Set up Layout Manager, reverse layout
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
Query postsQuery = getQuery(mDatabase);
ShowData(postsQuery);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
SearchData(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//Filter as you type
SearchData(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private FirebaseRecyclerAdapter getMAdapter(Query query){
mActivity = getActivity();
final Dialog mDialog = new Dialog(mActivity, R.style.NewDialog);
mDialog.addContentView(
new ProgressBar(mActivity),
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
);
mDialog.setCancelable(true);
mDialog.show();
FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(query, Post.class)
.build();
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
#Override
protected void onBindViewHolder(PostViewHolder viewHolder, int position, final Post model) {
final DatabaseReference postRef = getRef(position);
// Determine if the current user has liked this post and set UI accordingly
if (model.stars.containsKey(getUid())) {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
} else {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
if (!TextUtils.isEmpty(model.kzSongytblink))
viewHolder.mImage.setImageResource(R.drawable.on_line_logo);
else viewHolder.mImage.setImageResource(R.drawable.off_line_logo);
// Bind Post to ViewHolder, setting OnClickListener for the star button
viewHolder.bindToPost(model, new View.OnClickListener() {
#Override
public void onClick(View starView) {
// Need to write to both places the post is stored
DatabaseReference globalPostRef = mDatabase.child("songsDB").child(postRef.getKey());
// Run two transactions
onStarClicked(globalPostRef);
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, PostDetailActivity.class);
intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postRef.getKey());
startActivity(intent);
}
});
}
#Override
public PostViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
return new PostViewHolder(inflater.inflate(R.layout.item_post, viewGroup, false));
}
};
return mAdapter;
}
public void ShowData(Query postsQuery) {
mAdapter=getMAdapter(postsQuery);
mRecycler.setAdapter(mAdapter);
}
public void SearchData(String searchText){
//SearchData
mFirebaseDatabase = FirebaseDatabase.getInstance();
mRef = FirebaseDatabase.getInstance().getReference("songsDB");
Query postsQuery= mRef.orderByChild("kzSongTitle").startAt(searchText).endAt(searchText + "\uf8ff");
mAdapter=getMAdapter(postsQuery);
mRecycler.setAdapter(mAdapter);
}
#Override
public void onStart() {
super.onStart();
if (mAdapter != null) {
mAdapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
Log.d("postTransaction", "onComplete:" + dataSnapshot.getKey());
}
});
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
}
If you remove the SearchData method, everything is loaded normally, but the searching is not working and I need it.
Without method SearchData :
If you don't remove SearchData load all data from database in all fragments.
I need to fix it, but I don't know how. Help me please.
With method SearchData :

FirebaseRecyclerAdapter OnItemClick from fragment to fragment

I'm using the firebaseRecyclerAdaper on a fragment and i want to open an item from de populated list from firebase and send the data to a new fragment. Can u guys tell me please how can i start the FragmentDetail from the onCLickListener on FragmentAllPosts and pass the PostModel parameter to it?
Main Activity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "TAG" ;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference , postsRef;
private StorageReference profileImgRef;
private CircleImageView circleImageViewMain;
private TextView nameEdtTxt, emailEdtTxt;
Fragment fragment= null;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Please wait!");
progressDialog.setCanceledOnTouchOutside(false);
//Initialize Firebase modules
firebaseAuth=FirebaseAuth.getInstance();
databaseReference= FirebaseDatabase.getInstance().getReference().child("users");
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
profileImgRef= FirebaseStorage.getInstance().getReference();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
circleImageViewMain = (CircleImageView) header.findViewById(R.id.circleImageHeader);
nameEdtTxt = (TextView) header.findViewById(R.id.txtName);
emailEdtTxt =(TextView)header.findViewById(R.id.txtEmail);
if (firebaseAuth.getCurrentUser()!=null){
LoadUserData(CheckUserDataBase());
}
ViewPager vp_pages= (ViewPager) findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter=new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
TabLayout tbl_pages= (TabLayout) findViewById(R.id.tabs);
tbl_pages.setupWithViewPager(vp_pages);
tbl_pages.setTabTextColors(ColorStateList.valueOf(Color.parseColor("#FFFFFF")));
tbl_pages.setHorizontalScrollBarEnabled(true);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragment= new AddPostFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.add(R.id.add_post_container, fragment).commit();
fab.hide();
}
});
}
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentAllPosts();
case 1:
return new FragmentLosts();
case 2:
return new FragmentFounds();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
//
//Your tab titles
//
case 0:return "All";
case 1:return "Losts";
case 2: return "Founds";
default:return null;
}
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user= firebaseAuth.getCurrentUser();
if (user == null){
SendUserToLogin();
} else {
CheckUserDataBase();
}
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
private void UpdateHome() {
}
private void LoadUserData(final String uid) {
try {
final File localFile =File.createTempFile("profile","png");
StorageReference filepath=profileImgRef.child(uid).child("profileImg/profile.png");
filepath.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Picasso.get()
.load(localFile)
.placeholder(R.drawable.ic_account)
.into(circleImageViewMain);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,
"Profile photo not found, please update your profile!",
Toast.LENGTH_SHORT).show();
SendUserToSetup();
}
});
} catch (IOException e) {
e.printStackTrace();
}
databaseReference.child(uid).child("userInfo").addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("name")){
String name = dataSnapshot.child("name").getValue().toString();
nameEdtTxt.setText(name);
String email = dataSnapshot.child("email").getValue().toString();
emailEdtTxt.setText(email);
} else {
Toast.makeText(MainActivity.this,
"Profile name does not exists, please update your profile",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
}
#Override
protected void onStop() {
super.onStop();
}
private String CheckUserDataBase() {
final String userID =firebaseAuth.getCurrentUser().getUid();
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(userID).hasChild("userInfo")){
SendUserToSetup();
} else {
UpdateHome();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
return userID;
}
private void SendUserToSetup() {
Intent i = new Intent(this,SetupActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
private void SendUserToLogin() {
Intent i = new Intent(this,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() >0)
{
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
} else
{
super.onBackPressed();
}
fab.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_home:
super.onResume();
if (fragment!=null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.remove(fragment).commit();
fab.show();
}
break;
case R.id.nav_profile:
super.onPause();
break;
case R.id.nav_my_posts:
super.onPause();
break;
case R.id.nav_messeges:
super.onPause();
break;
case R.id.nav_settings:
super.onPause();
break;
case R.id.nav_logout:
SendUserToLogin();
firebaseAuth.signOut();
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment with the FirebaseRecyclerAdapter
public class FragmentAllPosts extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private DatabaseReference postsRef;
private Context context= getContext();
Fragment mFragment;
Bundle mBundle;
public FragmentAllPosts() {
// Required empty public constructor
}
public static FragmentAllPosts newInstance(String param1, String param2) {
FragmentAllPosts fragment = new FragmentAllPosts();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
private RecyclerView recyclerAllPosts;
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
progressDialog= new ProgressDialog(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_all_posts,container,false);
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
recyclerAllPosts= v.findViewById(R.id.recycler_all_posts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerAllPosts.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
#Override
public void onStart() {
super.onStart();
progressDialog.show();
FirebaseRecyclerOptions<PostsModel> options=
new FirebaseRecyclerOptions.Builder<PostsModel>()
.setQuery(postsRef,PostsModel.class)
.setLifecycleOwner(this)
.build();
FirebaseRecyclerAdapter<PostsModel,PostsViewHolder> adapter=
new FirebaseRecyclerAdapter<PostsModel, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final PostsModel model) {
String processedTime= CalculateTime(model.getData());
Picasso.get().load(Uri.parse(model.getUserImg())).into(holder.circleImageView);
Picasso.get().load(Uri.parse(model.getImageUri())).into(holder.imageView);
holder.authorNdate.setText(model.getAuthor()+" updated "+processedTime);
holder.location.setText(model.getLocation());
holder.description.setText(model.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment frag= new FragmentDetail();
getFragmentManager().beginTransaction().replace(R.id.add_post_container,frag)
.addToBackStack(null).commit();
}
});
}
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_view,viewGroup,false );
PostsViewHolder viewHolder= new PostsViewHolder(view);
return viewHolder;
}
};
recyclerAllPosts.setAdapter(adapter);
progressDialog.dismiss();
adapter.startListening();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public String CalculateTime(String inputTime){
String timeOut;
Calendar currentTime= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat(getString(R.string.date_format));
dateFormat.format(currentTime.getTime());
SimpleDateFormat postFormat= new SimpleDateFormat(getString(R.string.date_format));
Calendar postTime = Calendar.getInstance();
try {
Date datePost=postFormat.parse(inputTime);
postTime.setTime(datePost);
} catch (ParseException e) {
e.printStackTrace();
}
long timeCurrent= currentTime.getTimeInMillis();
long timePost = postTime.getTimeInMillis();
long diff= timeCurrent- timePost;
long minutes= diff/(60*1000);
long hours = diff/(60 * 60 * 1000);
long days = diff/(24 * 60 * 60 * 1000);
if (minutes<59 && minutes>1){
timeOut=Long.toString(minutes)+" mins ago";
} else if (minutes<1){
timeOut=" just now";
}else if (hours<24 && minutes>59){
timeOut=Long.toString(hours)+" hour(s) ago";
}else {
timeOut=Long.toString(days)+" day(s) ago";
}
return timeOut;
}
static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setTag(this);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Detail Fragment:
public class FragmentDetail extends Fragment {
public FragmentDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
I'd suggest a read on the documentation. Passing data between two activities should be done via interfaces.
As suggested by the official site

Android pass value from third fragment to first fragment

Here is my adapter
viewHolder.Edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
mAuth=FirebaseAuth.getInstance();
FirebaseFirestore firebaseFirestore=FirebaseFirestore.getInstance();
firebaseFirestore.collection("bookings").whereEqualTo("customer",mAuth.getUid())
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for (DocumentSnapshot document : task.getResult()) {
currentUserId=document.getId();
Log.d("ID", String.valueOf(currentUserId));
}
StylistFragment servicesFragment = new StylistFragment();
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Bundle bundle=new Bundle();
bundle.putString("userdocumentid",currentUserId);
servicesFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction()
.replace(R.id.frameLayout, servicesFragment).addToBackStack(null).commit();
// change navigation item color of a fragment when button is clicked
((HomeActivity)view.getContext()).changeMenu(R.id.navigation_stylist);
}
});
}
});
this is my fragment where i am receiving value from third fragment to first fragment
public class StylistFragment extends Fragment {
private RecyclerView recyclerView;
private String docid;
CircleImageView stylistImg;
public StylistFragment() {
// 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.stylist_recycler, container, false);
recyclerView=view.findViewById(R.id.stylistRecycler);
stylistImg=view.findViewById(R.id.stylistImg);
Bundle bundle=getArguments();
if(bundle!=null){
docid=bundle.getString("userdocumentid","");
Log.d("selectedDocumentId",docid);
}
try{
FirebaseFirestore db = FirebaseFirestore.getInstance();
try {
db.collection("stylist").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
try {
ArrayList<String> stylistId=new ArrayList<>();
for(DocumentSnapshot documentSnapshot:task.getResult()){
String id=documentSnapshot.getId();
stylistId.add(id);
}
StylistAdapter listAdapter = new StylistAdapter(task,docid,stylistId,stylistImg);
RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecorator(ContextCompat.getDrawable(getContext(), R.drawable.divider));
recyclerView.addItemDecoration(dividerItemDecoration);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter);
}catch (Exception e){
e.printStackTrace();
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
return view;
}
}
I am passing value from third fragment to first fragment.In third fragment i am using recyclerview if recyclerview excutes first item the value is available which i am getting in docid but if it executes more than one time the docid is null.Earlier i used the same code its worked fine i don't know what happend its not working now
Make use of interfaces.
Make a interface inside the third fragment and implement it in first fragment and call the function from third fragment with the value.
you can use the value in first fragment.
public class MainActivity extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, StylistFragment.getInstannce("navigation_home")).addToBackStack(null).commit();
return true;
case R.id.navigation_dashboard:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, StylistFragment.getInstannce("navigation_dashboard")).addToBackStack(null).commit();
return true;
case R.id.navigation_notifications:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, StylistFragment.getInstannce("navigation_notifications")).addToBackStack(null).commit();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
public static class StylistFragment extends Fragment {
private static final String TAG_VALUE = "tag_value";
public static StylistFragment getInstannce(String myValue){
Bundle extras = new Bundle();
extras.putString(TAG_VALUE,myValue);
StylistFragment fragment = new StylistFragment();
fragment.setArguments(extras);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String myStringValue = getArguments().getString(TAG_VALUE);
Log.d(TAG_VALUE, "My passed Value: " + myStringValue);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Output
D/tag_value: My passed Value: navigation_home
D/tag_value: My passed Value: navigation_dashboard
D/tag_value: My passed Value: navigation_notifications

Categories

Resources