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
Related
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);
}
}
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.
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.
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
I have one BlogActivity where it has profile image placeholder, username placeholder where I have used Recycle Adapter to populate each with user imge and name.
I created Second activity where it has one ImageView and TextView with id user_image and user_name.
How can I get the current user_image and current user_name to show in my Second activity?
The Recycle adapter for Blog activity is
public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> {
public List<BlogPost> blog_list;
public Context context;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private PopupWindow popWindow;
public BlogRecyclerAdapter(List<BlogPost> blog_list){
this.blog_list = blog_list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
context = parent.getContext();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.setIsRecyclable(false);
final String blogPostId = blog_list.get(position).BlogPostId;
final String currentUserId = firebaseAuth.getCurrentUser().getUid();
String desc_data = blog_list.get(position).getDesc();
holder.setDescText(desc_data);
String image_url = blog_list.get(position).getImage_url();
String thumbUri = blog_list.get(position).getImage_thumb();
holder.setBlogImage(image_url, thumbUri);
String user_id = blog_list.get(position).getUser_id();
//User Data will be retrieved here...
firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
String userName = task.getResult().getString("name");
String userImage = task.getResult().getString("image");
holder.setUserData(userName, userImage);
} else {
//Firebase Exception
}
}
});
#Override
public int getItemCount() {
return blog_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView blogUserName;
private CircleImageView blogUserImage;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
blogLikeBtn = mView.findViewById(R.id.blog_like_btn);
blogCommentBtn = mView.findViewById(R.id.blog_comment_icon);
}
public void setUserData(final String name, final String image) {
blogUserImage = mView.findViewById(R.id.blog_user_image);
blogUserName = mView.findViewById(R.id.blog_user_name);
blogUserName.setText(name);
RequestOptions placeholderOption = new RequestOptions();
placeholderOption.placeholder(R.drawable.profile_placeholder);
if (!((Activity) context).isFinishing()) {
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
}
mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("user_name", name);
intent.putExtra("user_image", image);
context.startActivity(intent);
}
});
}
public void updateLikesCount(int count){
blogLikeCount = mView.findViewById(R.id.blog_like_count);
blogLikeCount.setText(count + " Likes");
}
}
}
My second activity is
final String name = getIntent().getStringExtra("user_name");
Toast.makeText(getBaseContext(), "You're Offline!"+name, Toast.LENGTH_SHORT).show();
But here it throws error in name in Second activity and I couldn't resolve.
Please kindly suggest on how to get the user_image and user_name from used in Recycle adapter to any other activity TextView and ImageView
Below I have My Firebase structure image
Thanks in advance.
Try this
final String currentUserId = firebaseAuth.getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docRef = db.collection("Users").document(currentUserId);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d("check logcat", "DocumentSnapshot data: " + document.getData());
} else {
Log.d("", "No such document");
}
} else {
Log.d("", "get failed with ", task.getException());
}
}
});
here is doc : https://firebase.google.com/docs/firestore/query-data/get-data
If I have understood correctly, you just have to pass the user name and the image to the second activity that you set using setUserData function. So you just have to get an onClick method in your adapter which handles the passing data between your first activity to second activity. I hope you are fetching the data from your firebase database perfectly in your first activity.
public void setUserData(String name, String image) {
blogUserImage = mView.findViewById(R.id.blog_user_image);
blogUserName = mView.findViewById(R.id.blog_user_name);
blogUserName.setText(name);
RequestOptions placeholderOption = new RequestOptions();
placeholderOption.placeholder(R.drawable.profile_placeholder);
if (!((Activity) context).isFinishing()) {
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
}
mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("user_name", name);
intent.putExtra("user_image", image);
context.startActivity(intent);
}
});
}
Then in your MainActivity, just get the extras from your intent and show it in desired positions.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name = getIntent().getStringExtra("user_name");
String image = getIntent().getStringExtra("user_image");
// Use the name and image to show this is in respective TextView and ImageView
}