I am working on a chat app with firebase and I want to fitch the user information to the recyclerview...my code is correct by when I set the adapter to the recycler view its show an error.
Here is my code:
package com.abdelatif.chatapp;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.squareup.picasso.Picasso;
public class ChatFragment extends Fragment {
private FirebaseFirestore firebaseFirestore;
LinearLayoutManager linearLayoutManager;
private FirebaseAuth firebaseAuth;
ImageView mimageviewofuser;
FirestoreRecyclerAdapter<FireBaseModel, NoteViewHolder> chatAdapter = null;
RecyclerView mrecyclerview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.chatfragment,container,false);
firebaseAuth=FirebaseAuth.getInstance();
firebaseFirestore= FirebaseFirestore.getInstance();
mrecyclerview=v.findViewById(R.id.recyclerView);
// Query query=firebaseFirestore.collection("Users");
Query query=firebaseFirestore.collection("Users").whereNotEqualTo("uid",firebaseAuth.getUid());
FirestoreRecyclerOptions<FireBaseModel> allusername=new FirestoreRecyclerOptions.Builder<FireBaseModel>().setQuery(query,FireBaseModel.class).build();
chatAdapter=new FirestoreRecyclerAdapter<FireBaseModel, NoteViewHolder>(allusername) {
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, int i, #NonNull FireBaseModel firebasemodel) {
noteViewHolder.particularusername.setText(firebasemodel.getName());
String uri=firebasemodel.getImage();
Picasso.get().load(uri).into(mimageviewofuser);
if(firebasemodel.getStatus().equals("Online"))
{
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
noteViewHolder.statusofuser.setTextColor(Color.GREEN);
}
else
{
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
}
noteViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "contactClicked", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_view_layout,parent,false);
return new NoteViewHolder(view);
}
};
mrecyclerview.setHasFixedSize(true);
linearLayoutManager=new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
mrecyclerview.setLayoutManager(linearLayoutManager);
mrecyclerview.setAdapter(chatAdapter);
chatAdapter.startListening();
return v;
}
public class NoteViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder
{
private TextView particularusername;
private TextView statusofuser;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
particularusername=itemView.findViewById(R.id.nameOfUser);
statusofuser=itemView.findViewById(R.id.statusOfUser);
mimageviewofuser=itemView.findViewById(R.id.imageViewOfUser);
}
}
}
the error is in the line: mrecyclerview.setAdapter(chatAdapter);
and the error is:
'setAdapter(androidx.recyclerview.widget.RecyclerView.Adapter)' in 'androidx.recyclerview.widget.RecyclerView' cannot be applied to '(com.firebase.ui.firestore.FirestoreRecyclerAdapter<com.abdelatif.chatapp.FireBaseModel,com.abdelatif.chatapp.ChatFragment.NoteViewHolder>)'
I hope someone give me a solution...i searched many time but nothing.
Make sure you call chatAdapter.startListening(); before calling mrecyclerview.setAdapter(chatAdapter);
Related
So this is my code for the fragment:
import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class Frag1 extends Fragment {
CustomViewModel viewModel;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag1_layout, container, false);
viewModel = new ViewModelProvider(this).get(CustomViewModel.class);
RecyclerView recyclerView = rootView.findViewById(R.id.rv1);
final Adapter adapter = new Adapter(new Adapter.Diff());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
viewModel.show().observe(getViewLifecycleOwner(), rEnts -> {
adapter.submitList(rEnts);
Log.d("ItemCount", String.valueOf(adapter.getItemCount()));
});
Log.d("ItemCountOUTSIDE", String.valueOf(adapter.getItemCount()));
return rootView;
}
when I run the app the recycler view is empty, in the logs the "ItemCountOUTSIDE" shows 0 and is written earlier the "ItemCount" which shows 2. RoomDB is capable of showing the 2 items that are in it when the app is run, so i'd imagine its not a problem with the ViewModel. I was able to output the objects in the DB on a TextView using the same observer function and also using the ViewModel. I understand that apparently observer runs in separate thread and that is executed later but I dont know how to fix that since I know concurrency only on a surface level. Also when doing my research this pattern that I'm using seems to be working for others, hence my frustration.
Additional Code for the Adapter and ViewHolder:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.w3c.dom.Text;
public class Holder extends RecyclerView.ViewHolder {
private final TextView textView;
private Holder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textName);
}
public void bind(rEnt E){
textView.setText(E.rN);
}
static Holder create(ViewGroup parent){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv1_item, parent, false);
return new Holder(view);
}
}
and
import android.util.Log;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Query;
import java.util.List;
public class Adapter extends ListAdapter<rEnt, Holder> {
List<rEnt> myList = getCurrentList();
public Adapter(#NonNull DiffUtil.ItemCallback<rEnt> diffCB){
super(diffCB);
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return Holder.create(parent);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
rEnt currentEnt = getItem(position);
holder.bind(currentEnt);
}
static class Diff extends DiffUtil.ItemCallback<rEnt>{ //fuck is this as well???
#Override
public boolean areItemsTheSame(#NonNull rEnt oldItem, #NonNull rEnt newItem) {
return oldItem.getId() == newItem.getId();
}
#Override
public boolean areContentsTheSame(#NonNull rEnt oldItem, #NonNull rEnt newItem) {
return oldItem.rN.equals(newItem.rN);
}
}
}
Hi i tried to inflate my home_items.xml in my application however it doesnt work it just gives me the fragment_home.xml ONLY im wondering how can i fix this? (I can send any part of my code.)
HomeAdapter.java:
package com.example.soulforge.adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.soulforge.R;
import com.example.soulforge.model.HomeModel;
import java.util.List;
import java.util.Random;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeHolder>{
private List<HomeModel> list;
Context context;
public HomeAdapter(List<HomeModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public HomeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_items, parent, false);
return new HomeHolder(view);
}
#Override
public void onBindViewHolder(#NonNull HomeHolder holder, int position) {
holder.userNameTv.setText(list.get(position).getUserName());
holder.timeTv.setText(""+list.get(position).getTimestamp());
int count = list.get(position).getLikeCount();
if(count ==0){
holder.likeCountTv.setVisibility(View.INVISIBLE);
}else if (count == 1){
holder.likeCountTv.setText(count + " like");
}else{
holder.likeCountTv.setText(count + " likes");
}
holder.descriptionTv.setText(list.get(position).getDescription());
Random random = new Random();
int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));
Glide.with(context.getApplicationContext())
.load(list.get(position).getProfileImage())
.placeholder(R.drawable.ic_person)
.timeout(6500)
.into(holder.profileImage);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageUrl())
.placeholder(new ColorDrawable(color))
.timeout(7000)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
static class HomeHolder extends RecyclerView.ViewHolder{
private CircleImageView profileImage;
private TextView userNameTv, timeTv, likeCountTv, descriptionTv;
private ImageView imageView;
private ImageButton likeBtn, commentBtn, shareBtn;
public HomeHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.profileImage);
imageView = itemView.findViewById(R.id.imageView);
userNameTv = itemView.findViewById(R.id.nameTv);
timeTv = itemView.findViewById(R.id.timeTv);
likeCountTv = itemView.findViewById(R.id.likeCountTv);
likeBtn = itemView.findViewById(R.id.likeBtn);
commentBtn = itemView.findViewById(R.id.commentBtn);
shareBtn = itemView.findViewById(R.id.shareBtn);
descriptionTv = itemView.findViewById(R.id.descTv);
}
}
}
Home.java:
package com.example.soulforge.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.soulforge.R;
import com.example.soulforge.adapter.HomeAdapter;
import com.example.soulforge.model.HomeModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Home extends Fragment {
private RecyclerView recyclerView;
HomeAdapter adapter;
private List<HomeModel> list;
private FirebaseUser user;
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init(view);
list = new ArrayList<>();
adapter = new HomeAdapter(list, getContext());
recyclerView.setAdapter(adapter);
loadDataFromFirestore();
}
private void init(View view) {
Toolbar toolbar = view.findViewById(R.id.toolbar);
if (getActivity() != null)
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseAuth auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
}
public void loadDataFromFirestore() {
CollectionReference reference = FirebaseFirestore.getInstance().collection("Users")
.document(user.getUid())
.collection("Post Images");
reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.e("Error: ", error.getMessage());
return;
}
if (value == null)
return;
for (QueryDocumentSnapshot snapshot : value) {
if (!snapshot.exists())
return;
HomeModel model = snapshot.toObject(HomeModel.class);
list.add(new HomeModel(
model.getUserName(),
model.getProfileImage(),
model.getImageUrl(),
model.getUid(),
model.getComments(),
model.getDescription(),
model.getId(),
model.getTimestamp(),
model.getLikeCount()
));
}
adapter.notifyDataSetChanged();
}
});
}
}
Any idea how to fix this? I tried to use inflate however it failed to work as shown it is missing the home items xml enter image description here.
Before you say i have cleared and rebuild and all the FAQ ways to fix this
You're updating wrong list instance
Create one method inside adapter
public updateList(List<HomeModel> list) {
this.list = list;
notifyDataSetChanged()
}
And call it like :
reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
...
adapter.updateList(new HomeModel(
model.getUserName(),
model.getProfileImage(),
model.getImageUrl(),
model.getUid(),
model.getComments(),
model.getDescription(),
model.getId(),
model.getTimestamp(),
model.getLikeCount()
));
}
}
});
I keep getting E/RecyclerView: No adapter attached; skipping layout. I have try onStop() and onStart() methods. I try to reorganize the way the method are structure still no luck. I have follow the instructions on https://firebaseopensource.com/projects/firebase/firebaseui-android/database/readme/ yet, I can't figure it out.
package mrcof.code.senior_tech_support_app;
import android.content.Context;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import static mrcof.code.senior_tech_support_app.R.id.result_list;
public class TV extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
private FirebaseRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tv);
mUserDatabase = FirebaseDatabase.getInstance().getReference("TV"); // TV in Database
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText); //Our own firebase usersearch
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(TV.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("Brand").startAt(searchText).endAt(searchText + "\uf8ff");
/*Query firebaseSearchQuery = FirebaseDatabase.getInstance()
.getReference()
.child("Brand")
.limitToLast(6).startAt(searchText).endAt(searchText + "\uf8ff");*/
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(firebaseSearchQuery, Users.class).build();
adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
holder.setDetails(getApplicationContext(), model.getBrand(), model.getImage());
}
};
mResultList = (RecyclerView) findViewById(result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mResultList.setAdapter(adapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String brandd, String brandImage){
TextView brand = (TextView) mView.findViewById(R.id.name_text);
ImageView brand_image = (ImageView) mView.findViewById(R.id.brandd_image);
brand.setText(brandd);
Glide.with(ctx).load(brandImage).into(brand_image);
}
}
}
package mrcof.code.senior_tech_support_app;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import static mrcof.code.senior_tech_support_app.R.id.result_list;
public class TV extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseRecyclerAdapter adapter;
private FirebaseDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tv);
//databaseReference = FirebaseDatabase.getInstance().getReference("TV"); // TV in Database
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
recyclerView = (RecyclerView) findViewById(result_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseReference = FirebaseDatabase.getInstance().getReference("TV"); // TV in Database
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseSearch(searchText);
}
});
}
private void firebaseSearch(String searched){
String query = searched;
Query firebaseSearchQuery = databaseReference.orderByChild("brand").startAt(query).endAt( query + "\uf8ff");
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(firebaseSearchQuery, Users.class).setLifecycleOwner(this).build();
FirebaseRecyclerAdapter<Users, ViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, ViewHolder>(options) {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Users model) {
holder.setDetails(getApplicationContext(), model.getBrand(), model.getImage());
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(databaseReference, Users.class).setLifecycleOwner(this).build();
FirebaseRecyclerAdapter<Users, ViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, ViewHolder>(options) {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Users model) {
holder.setDetails(getApplicationContext(), model.getBrand(), model.getImage());
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String brandd, String brandImage){
TextView brand = (TextView) mView.findViewById(R.id.brand_name);
ImageView brand_img = (ImageView) mView.findViewById(R.id.brand_image);
brand.setText(brandd);
Glide.with(ctx).load(brandImage).into(brand_img);
}
}
}
To put this simple, I have a table called Wishlist in Firebase Database which contains 2 different types of objects: attractions and sights.
Then, in my app I want to show in a fragment only those objects from Wishlist table which are sights. How could I achieve this? Right now, the code is as it follows: (obviously, it will crash if I put return null, but how else could I address this issue?)
package com.example.mytravelapp.Fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.mytravelapp.Adapters.WishlistViewHolder;
import com.example.mytravelapp.Models.Sight;
import com.example.mytravelapp.Models.Wishlist;
import com.example.mytravelapp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class WishlistSightsFragment extends Fragment {
private RecyclerView wishlist;
private DatabaseReference query;
private FirebaseRecyclerAdapter adapter;
private FirebaseUser user;
public WishlistSightsFragment() {
// 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_wishlist_sights, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
wishlist = view.findViewById(R.id.rvWishlistSights);
wishlist.setHasFixedSize(true);
user = FirebaseAuth.getInstance().getCurrentUser();
GridLayoutManager grid = new GridLayoutManager(getContext().getApplicationContext(), 1);
wishlist.setLayoutManager(grid);
fetch();
}
private void fetch(){
query = FirebaseDatabase.getInstance().getReference("wishlist").child(user.getUid());
FirebaseRecyclerOptions<Wishlist> options =
new FirebaseRecyclerOptions.Builder<Wishlist>()
.setQuery(query, new SnapshotParser<Wishlist>() {
#NonNull
#Override
public Wishlist parseSnapshot(#NonNull DataSnapshot snapshot) {
Wishlist attraction = new Wishlist(snapshot.child("idWishlist").getValue().toString(),
snapshot.child("idAttraction").getValue().toString(),
snapshot.child("name").getValue().toString(),
snapshot.child("description").getValue().toString(),
snapshot.child("image").getValue().toString(),
snapshot.child("type").getValue().toString());
if(attraction.getType().equals("sight")){
return attraction;
}
return null;
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Wishlist, WishlistViewHolder>(options) {
#Override
public WishlistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.wishlist_design, parent, false);
return new WishlistViewHolder(view);
}
#Override
protected void onBindViewHolder(final WishlistViewHolder holder, final int position, final Wishlist model) {
holder.setDetails(getActivity(), model.getName(), model.getDescription(), model.getIdAttraction(), model.getImage());
}
};
wishlist.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
I think this query is more useful for you.
query = FirebaseDatabase.getInstance().getReference("wishlist").child(user.getUid()).orderByChild("type").equalTo("sight");
FirebaseRecyclerOptions<Wishlist> options =
new FirebaseRecyclerOptions.Builder<Wishlist>()
.setQuery(query, Wishlist.class)
.build();
You can get the list of wish who have type sight.
im trying to call "view" from my inflater in my new method but it won't work, it says unresolved. if i move the whole code under setUpRecyclerView into onCreateView it works. is there a way to make it work as it is so i can keep my onCreatView tidy? all the code is in a Fragment. i alsi tried using getView.findViewById but that also didnt work.
'''
package com.example.hostapp;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class HomeFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference categoryref = db.collection("categories");
private categoryCardAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
public void setUpRecyclerView (){
Query query = categoryref.orderBy("name",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<categoryCard> options = new FirestoreRecyclerOptions.Builder<categoryCard>()
.setQuery(query, categoryCard.class)
.build();
adapter = new categoryCardAdapter(options);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_category);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
'''
this is the code that works:
package com.example.hostapp;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class HomeFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference categoryref = db.collection("categories");
private categoryCardAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
Query query = categoryref.orderBy("name",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<categoryCard> options = new FirestoreRecyclerOptions.Builder<categoryCard>()
.setQuery(query, categoryCard.class)
.build();
adapter = new categoryCardAdapter(options);
**RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_category);**
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(adapter);
return view;
}
public void setUpRecyclerView (){
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
You are not calling the setupRecyclerView() method in your first code sample. You can either call it from your createView() method before returning the view or you can call the method from onViewCreated() method. I would prefer the second option.