Save recyclerView state between fragments on bottom navigation view - java

When i'm switching from another fragment to home fragment, the fragment loads again the data to my recycler view. I want to save the recycler view state and restoring it when the user switch to my home fragment. My problem is that i don't know how to save a custom array list to onSaveInstanceState() and then retrieve this from the onCreateView() method.
My HomeFragment:
public class HomeFragment extends Fragment {
LoadingDialog progressDialog;
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
boolean isSearchOpen = false;
private EditText searchView;
ArrayList<PostModel> postModelArrayList;
RecyclerView recyclerView;
void loadPosts(View fragmentView, FirebaseUser user, ArrayList<PostModel> postModelArrayList, RecyclerView.Adapter postsAdapter, boolean isRefresh) {
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
new Handler().postDelayed(() -> {
fragmentView.findViewById(R.id.constraintLayout2).setVisibility(View.GONE);
((HomeActivity)getContext()).findViewById(R.id.bottom_nav).setVisibility(View.VISIBLE);
}, 2000);
for (DataSnapshot snap : snapshot.child("posts").getChildren()) {
PostModel postModel = new PostModel();
postModel.setId(snap.child("id").getValue(String.class));
postModel.setImgUrl(snap.child("imgUrl").getValue(String.class));
postModel.setLikes(snap.child("likes").getValue(String.class));
postModel.setName(snap.child("name").getValue(String.class));
postModel.setProfileImgUrl(snap.child("authorProfilePictureURL").getValue(String.class));
postModel.setPostType(snap.child("postType").getValue(String.class));
// Show post in recycler adapter only if the user is not blocked
if (!snapshot.child("users").child(user.getUid()).child("blockedUsers").child(snap.child("name").getValue(String.class)).exists()) {
postModelArrayList.add(postModel);
}
}
if (snapshot.child("users").child(user.getUid()).child("blockedUsers").exists()) {
System.out.println(snapshot.child("users").child(user.getUid()).child("blockedUsers"));
}
postsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(getContext(), "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
// i don't know what i need to do here
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
TextView usernameLoadingScreen = view.findViewById(R.id.textView40);
ImageButton searchUserBtn = view.findViewById(R.id.searchPersonButton);
ImageButton notificationsBtn = view.findViewById(R.id.notificationsButton);
ImageButton searchUserButton = view.findViewById(R.id.enter_search_button);
View postsOfTheMonthBtn = view.findViewById(R.id.posts_of_the_month_btn);
searchView = view.findViewById(R.id.search_view);
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
AdView mAdView = view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
recyclerView = view.findViewById(R.id.home_recycler_view);
postModelArrayList = new ArrayList<>();
final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
final RecyclerView.Adapter recyclerAdapter = new PostRecyclerAdapter(postModelArrayList, getContext(), getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
progressDialog = LoadingDialog.Companion.get(getActivity());
searchView.setVisibility(View.GONE);
searchUserButton.setVisibility(View.GONE);
((HomeActivity)getContext()).findViewById(R.id.bottom_nav).setVisibility(View.GONE);
loadPosts(view, user, postModelArrayList, recyclerAdapter, false);
}
}

Related

How to add AdMob Banner AD in RecyclarView after 5 or 10 CardView using FirebaseRecyclerAdapter

I am working on an android app where I am showing some text coming through the firebase database, now I want to show AdMob Banner AD after 5 CardView in the RecyclarView but I am not understand how to do that because I am beginner in Java and Android Programming language. Can anyone help me to do this implementation.
MY JAVA CODE
POJO CLASS
private String shaData;
public Model(){
}
public Model(String sha) {
this.shaData = sha;
}
public String getShaData() {
return shaData;
}
public void setShaData(String shaData) {
this.shaData = shaData;
}
}
MY VIEW HOLDER CLASS
public class Holder extends RecyclerView.ViewHolder{
public TextView txtShayari;
public Button copyButton, shareButton, whatsappButton;
public Holder(#NonNull View itemView) {
super(itemView);
txtShayari = (TextView)itemView.findViewById(R.id.textView);
copyButton = (Button) itemView.findViewById(R.id.copyBtn);
shareButton = (Button) itemView.findViewById(R.id.shBtn);
whatsappButton = (Button) itemView.findViewById(R.id.waBtn);
}
}
MY MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ProgressBar progressBar;
ImageView imageView;
FirebaseRecyclerAdapter<Model, Holder> recyclerAdapter;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("MyQuotes");
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
progressBar = findViewById(R.id.progress);
loadData();
}
private void loadData()
{
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(databaseReference,Model.class)
.build();
recyclerAdapter = new FirebaseRecyclerAdapter<Model, Holder>(options) {
int AD_TYPE = 0;
int CONTENT_TYPE = 1;
#Override
protected void onBindViewHolder(#NonNull final Holder holder, int position, #NonNull final Model model) {
holder.txtShayari.setText(model.getShaData());
progressBar.setVisibility(View.GONE);
holder.copyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager)holder.itemView.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(Intent.EXTRA_TEXT, model.getShaData());
clipboard.setPrimaryClip(clip);
Toast.makeText(holder.itemView.getContext(), "Shayari Copied", Toast.LENGTH_SHORT).show();
}
});
holder.whatsappButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, model.getShaData());
try {
holder.itemView.getContext().startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(holder.itemView.getContext(), "Whatsapp have not been installed", Toast.LENGTH_SHORT).show();
}
}
});
holder.shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent .setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, model.getShaData());
intent.setType("text/plain");
intent = Intent.createChooser(intent, "Share With");
holder.itemView.getContext().startActivity(intent);
}
});
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_view,viewGroup,false);
return new Holder(view);
}
};
recyclerAdapter.notifyDataSetChanged();
recyclerAdapter.startListening();
recyclerView.setAdapter(recyclerAdapter);
}
}
This is my whole code too fetch text data from the Firebase server and it is working very well, Simply now I am want too show AdMob banner ads after 5 cardviews on the recyclarview, So please anyone guide me.

Update WebView in Fragment from RecyclerView Item

I'm trying to update my WebView in a Fragment when RecyclerView Item is clicked. In the debug console it's printing my hard-coded URL, but it's not updating the View - it is staying on "Google" webpage without any changes, but seems like onClickListener is working.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add Websites
ArrayList<Website> websitesList = new ArrayList<>();
websitesList.add(new Website(R.drawable.ic_launcher_background, "Line 1", "https://google.com/"));
websitesList.add(new Website(R.drawable.ic_launcher_background, "Line 2", "https://yahoo.com/"));
websitesList.add(new Website(R.drawable.ic_launcher_background, "Line 3", "https://abv.bg/"));
mRecyclerView = findViewById(R.id.recyclerView);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new WebsiteAdapter(websitesList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
public void switchContent(int id, Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(id, fragment);
ft.commit();
}
}
RecyclerView Adapter
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
final Website currentItem = mWebsiteList.get(position);
holder.mImageView.setImageResource(currentItem.getImage());
holder.mTitle.setText(currentItem.getTitle());
holder.mTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragmentJump(currentItem);
}
});
}
#Override
public int getItemCount() {
return mWebsiteList.size();
}
private void fragmentJump(Website mItemSelected) {
Fragment mFragment = new WebsiteView();
Bundle mBundle = new Bundle();
mBundle.putString("url", "http://facebook.com/");
mFragment.setArguments(mBundle);
switchContent(R.id.fragment, mFragment);
}
public void switchContent(int id, Fragment fragment) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) mContext;
mainActivity.switchContent(id, fragment);
}
}
WebView Fragment
private WebView webView;
String mUrl;
public WebsiteView() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_website_view, container, false);
try {
mUrl = getArguments().getString("url");
} catch(Exception ex) {
System.out.println(ex.toString());
mUrl = "http://google.com/";
}
System.out.println(mUrl);
webView = v.findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(mUrl);
return v;
}
Okay, it appeared that I'm actually trying to update the Fragment data, and when I replace another fragment with my desired one it works. Any ideas how to update the WebView in the fragment?

How to Load the RecyclerView upon starting to the application automatically?

I created a fragment with recyclerview and when I executed the application it doesn't load the data automatically for that I have to move to another view and then come back to this particular view to get the data loaded, I want when the application starts the list in recyclerview automatically retrieves the data from the firestore database.
If my code is required do let know.
Thank You for the assistance in advance.
HomeFragement Class
public class HomeFragment extends Fragment {
RelativeLayout mParent;
//FloatingActionButton addButton;
private static final String TAG = "DocSnippets";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference PostsRef = db.collection("posts");
private CollectionReference likesRef;
private PostsAdapter adapter;
private FirestoreRecyclerOptions options;
private FirebaseAuth mAuth;
private String mUserId, id;
private Button commentsbutton;
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
mAuth = FirebaseAuth.getInstance();
mUserId = mAuth.getUid();
likesRef = db.collection("users").document(mUserId).collection("likes");
final View view = inflater.inflate(R.layout.fragment_home, container, false);
final FragmentActivity c = getActivity();
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
Query query = PostsRef.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<PostsModel> options = new FirestoreRecyclerOptions.Builder<PostsModel>()
.setQuery(query, PostsModel.class)
.build();
adapter = new PostsAdapter(options);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
// recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(c));
recyclerView.setAdapter(adapter);
commentsbutton = (Button) view.findViewById(R.id.commenting_button);
mParent =view.findViewById(R.id.relative_home);
// return inflater.inflate(R.layout.fragment_home, null);
adapter.setOnItemClickListener(new PostsAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
PostsModel note = documentSnapshot.toObject(PostsModel.class);
id = documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
Log.d(TAG, "String post Id is: " + id);
Intent gotoClickPostDetailActivity = new Intent (view.getContext(), ClickPost.class);
gotoClickPostDetailActivity.putExtra("PostKey",id);
startActivity(gotoClickPostDetailActivity);
//
// Toast.makeText(c, "Position: " + position + " ID: " + id, Toast.LENGTH_SHORT).show();
//Toast.makeText(HomeFragment.this, "Position: " + position + " ID: " + id, Toast.LENGTH_SHORT).show();
}
});
return view;
}
private String getTime(long timestamp){
long ts = timestamp*1000;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
String time = sdf.format(new Date(ts));
return time;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
MainActivity Class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth mauth;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference UsersRef = db.collection("Users");
private DocumentReference noteRef = db.document("Notebook/My First Note");
private MySharedPreferences sp;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = MySharedPreferences.getInstance(this);
setContentView(R.layout.activity_main);
mauth = FirebaseAuth.getInstance();
// currentUserID = mauth.getCurrentUser().getUid();
UsersRef =FirebaseFirestore.getInstance().collection("Users");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
Intent intent = new Intent(MainActivity.this, AddPostActivity.class);
startActivity(intent);
// fragment = new NotificationsFragment();
break;
case R.id.navigation_post:
fragment = new ProfileFragment();
break;
case R.id.navigation_postlist:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
};
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
#Override
protected void onStart()
{
super.onStart();
FirebaseUser currentUser = mauth.getCurrentUser();
if(currentUser == null)
{
SendUserToSignInActivity();
}
else
{
checkUserExistence();
}
}
}
your problem is in this line of code
Query query = PostsRef.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<PostsModel> options = new
FirestoreRecyclerOptions.Builder<PostsModel>()
.setQuery(query, PostsModel.class)
.build();
adapter = new PostsAdapter(options);
PostsRef.orderBy take some time to get result from firebase but you can set result immediately which cause the problem

E/RecyclerView: No adapter attached; skipping layout (Android) [duplicate]

This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
No adapter attached; skipping layout [duplicate]
(2 answers)
Closed 3 years ago.
I have attached my adapter to my main activity's onCreate, after loading the user data to a model class named (Users.java) and then passing this ArrayList to the adapter.I am using Firestore.
It was working earlier but then after a few tests it stopped working. App crashes as soon as main activity is loaded. Please help. Thanks in advance.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// To make App Bar from Action Bar (AppComp)
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
mAuth = FirebaseAuth.getInstance();
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// Check if user is signed in (non null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
Intent authIntent = new Intent(MainActivity.this, SignUpActivity.class);
startActivity(authIntent);
finish();
} else {
mUsers = new ArrayList<>();
db.collection("users")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
Users users = document.toObject(Users.class);
mUsers.add(users);
}
mAdapter = new UsersAdapter(MainActivity.this, mUsers);
mRecyclerView.setAdapter(mAdapter);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar9);
progressBar.setVisibility(View.INVISIBLE);
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}
}
UsersAdapter.java
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> {
private Context mContext;
private List<Users> mUsers;
public UsersAdapter(Context context, List<Users> users) {
mContext = context;
mUsers = users;
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.users_card, parent, false);
return new UsersViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull UsersViewHolder holder, int position) {
Users currentUser = mUsers.get(position);
holder.textViewName.setText(currentUser.getUserName());
Picasso.get()
.load(currentUser.getUserImageUrl())
.fit()
.centerCrop()
.into(holder.imageViewPhoto);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class UsersViewHolder extends RecyclerView.ViewHolder{
public ImageView imageViewPhoto;
public TextView textViewName;
public UsersViewHolder(View itemView) {
super(itemView);
imageViewPhoto = itemView.findViewById(R.id.user_image);
textViewName = itemView.findViewById(R.id.user_name);
}
}
}
Logcat
E/RecyclerView: No adapter attached; skipping layout
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sandeeppradhan.sailors, PID: 3286
java.lang.IllegalArgumentException: Path must not be empty.
at com.squareup.picasso.Picasso.load(Picasso.java:332)
at com.example.sandeeppradhan.sailors.UsersAdapter.onBindViewHolder(UsersAdapter.java:39)
at com.example.sandeeppradhan.sailors.UsersAdapter.onBindViewHolder(UsersAdapter.java:17)
try doing this
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
in
mUsers = new ArrayList<>();
db.collection("users")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
Users users = document.toObject(Users.class);
mUsers.add(users);
}
//HERE
mAdapter = new UsersAdapter(MainActivity.this, mUsers);
mRecyclerView.setAdapter(mAdapter);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar9);
progressBar.setVisibility(View.INVISIBLE);
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}
Also make sure that your string with the url of the image isn't empty, in that case if some users haven't a imgurl just do a try catch in onBindViewHolder our just check of the image is empty with an if

Trying to display users information in a recyclerview - Firebase

My app is using Firebase. The user can register and login. In the main activity, there is a menu option called All Users. All I want for now is to display the registered users in a recyclerview. Of course this means that I will have to query the database using
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
If I put a breakpoint in this line, I can read the users. That's no problem.
Next, I use this page to implement the FirebaseRecyclerAdapter
The full code is shown below.
public class UsersActivity extends AppCompatActivity {
private Toolbar mToolbar;
private RecyclerView mUserList;
private DatabaseReference mUsersDatabase;
private FirebaseRecyclerOptions<Users> options;
private FirebaseRecyclerAdapter firebaseRecyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
mToolbar = (Toolbar)findViewById(R.id.users_appBar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("All Users");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUserList = (RecyclerView)findViewById(R.id.users_list);
mUserList.setHasFixedSize(true);
mUserList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
options =
new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(mUsersDatabase, Users.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_single_layout, parent, false);
return new UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(UsersViewHolder usersViewHolder, int i,Users users) {
usersViewHolder.setName(users.getName());
}
};
mUserList.setAdapter(firebaseRecyclerAdapter);
}
public static class UsersViewHolder extends RecyclerView.ViewHolder{
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName (String name){
TextView userNameView = (TextView) mView.findViewById(R.id.singleUserName);
userNameView.setText(name);
}
}
}
However, users are not displayed. Why is this happening?
Thanks,
Theo.
As explained in the page that you linked, you need to do the following:
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
You need to add startListening() to begin listening for data, and the stopListening() call removes the event listener and all data in the adapter.

Categories

Resources