Search bar using RecyclerView with Firebase(OnClick) - android

I am trying to build a firebase application where a user could search for their client and then click on the search result, will redirect to client profile activity with their data were passed on. I am using firebase realtime database. I can't seem to find a way to pass the data to from the search list when I click on the list. Basically, I am having trouble passing the data via OnClick after the search result
Search_lecturer class
public class Search_lecturer extends AppCompatActivity {
EditText search_lecturer;
RecyclerView recyclerView;
DatabaseReference databaseReference;
FirebaseUser firebaseUser;
ArrayList <String> NameList;
Search_Adapter_lecturer search_adapter_lecturer;
String lecturer_name2,lectuer_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_lecturer);
search_lecturer = findViewById(R.id.search_Lecturer);
recyclerView = findViewById(R.id.recyclerView_Lect);
databaseReference = FirebaseDatabase.getInstance().getReference();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
NameList = new ArrayList<>();
search_lecturer.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().isEmpty()){
setAdapter(s.toString());
} else {
NameList.clear();
recyclerView.removeAllViews();
}
}
});
}
private void setAdapter(final String searchString) {
final Intent intent2 = null;
databaseReference.child("lecturer").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
NameList.clear();
recyclerView.removeAllViews();
int counter = 0;
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
String uid = snapshot.getKey();
String Lect_Name = snapshot.child("Name").getValue(String.class);
if(Lect_Name.contains(searchString)){
NameList.add(Lect_Name);
counter++;
}
if (counter == 10){
break;
}
}
search_adapter_lecturer = new Search_Adapter_lecturer(Search_lecturer.this, NameList);
recyclerView.setAdapter(search_adapter_lecturer);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Adapter class
public class Search_Adapter_lecturer extends RecyclerView.Adapter<Search_Adapter_lecturer.SearchViewHolder> {
Context context;
ArrayList<String> NameList;
class SearchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView lect_name, lect_email;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
lect_name = itemView.findViewById(R.id.lect_name);
lect_email = itemView.findViewById(R.id.lecturer_email);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context, notification_menu.class);
context.startActivity(intent);
}
}
public Search_Adapter_lecturer(Context context, ArrayList<String> nameList) {
this.context = context;
this.NameList = nameList;
}
#NonNull
#Override
public Search_Adapter_lecturer.SearchViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.search_list_items, viewGroup, false);
return new Search_Adapter_lecturer.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder searchViewHolder, int position) {
searchViewHolder.lect_name.setText(NameList.get(position));
}
#Override
public int getItemCount() {
return NameList.size();
}
}
I tried to implement a search function into my application. I learn from a tutorial from youtube. It works but now I can't seem to find a way for which after the search, user manage to click on the name list and redirect to another activity with the data that the user clicks on. Hope to learn from you guys.

Related

How to set Recyclview items on TextView in android

This is my main screen and i want when i click on Select All checkbox then check all checkboxes and set all checkbox's text on below textView(Just text). I successfully select all checkboxes but can't set text on textbox with separate commas, with the help of adapter i get the list of whole data but can't set it on main activity textview layout. plz suggest me any helpful way for done this. Thnakyou.
public class MainActivity extends AppCompatActivity {
CheckBox checkboxAll;
EditText editSearch;
RecyclerView recyclerView;
TextView dataList;
MainAdapter mainAdapter;
DataAdapter dataAdapter;
List<MainModel> list;
List<String> showList = new ArrayList<>();
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = this.getSharedPreferences("prefs", Context.MODE_PRIVATE);
recyclerView = findViewById(R.id.recyclerView);
checkboxAll = findViewById(R.id.checkboxAll);
dataList = findViewById(R.id.dataList);
editSearch = findViewById(R.id.editSearch);
editSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String editValue = String.valueOf(charSequence);
filter(editValue);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
checkboxAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (checkboxAll.isChecked()) {
mainAdapter.selectAll();
} else {
mainAdapter.unselectAll();
}
}
});
list = new ArrayList<>();
String[] cityname = getResources().getStringArray(R.array.cityList);
for (int i = 0; i < cityname.length; i++) {
MainModel mainModel = new MainModel(false, cityname[i]);
list.add(mainModel);
}
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mainAdapter = new MainAdapter(MainActivity.this, list);
recyclerView.setAdapter(mainAdapter);
}
private void filter(String searchValue) {
ArrayList<MainModel> filteredList = new ArrayList<>();
for (MainModel item : list) {
if (item.getCityName().toLowerCase().contains(searchValue.toLowerCase())) {
filteredList.add(item);
}
}
mainAdapter.filterList(filteredList);
}
}
Adapter is:-
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
Context context;
List<MainModel> cityList = new ArrayList<>();
int checkValue = 0;
List<String> allValues;
SharedPreferences sharedPreferences;
public MainAdapter(Context context, List<MainModel> list) {
sharedPreferences = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
this.context = context;
this.cityList = list;
}
public void selectAll() {
checkValue = 1;
notifyDataSetChanged();
}
public void unselectAll() {
checkValue = 2;
notifyDataSetChanged();
}
#NonNull
#Override
public MainAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MainAdapter.ViewHolder holder, int position) {
holder.itemName.setText(cityList.get(position).getCityName());
if (checkValue == 1) {
holder.itemCheckBox.setChecked(true);
} else if (checkValue == 2) {
holder.itemCheckBox.setChecked(false);
}
}
#Override
public int getItemCount() {
return cityList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CheckBox itemCheckBox;
TextView itemName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
itemCheckBox = itemView.findViewById(R.id.itemCheckBox);
itemName = itemView.findViewById(R.id.itemName);
}
}
public void filterList(ArrayList<MainModel> filteredList) {
cityList = filteredList;
notifyDataSetChanged();
}
}
You can acheive it using Interface, I am addding below code snipet
class MainActivity extends AppCompatActivity implements MainAdapter.MyRecyclerClickListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
MainAdapter mainAdapter = new MainAdapter(MainActivity.this, list);
recyclerView.setAdapter(mainAdapter);
mainAdapter.setClickListener(this);
}
#Override
public void onAllItemSelected(String text) {
// set on TextView
}
#Override
public void onAllItemUnSelected(String text) {
// set on TextView toi clear all previous value
}
}
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private MyRecyclerClickListener myRecyclerClickListener;
public void selectAll() {
checkValue = 1;
StringBuilder stringBuilder = new StringBuilder();
for (MainModel cityModel : cityList) {
stringBuilder.append(cityModel.getCityName()).append(",");
}
myRecyclerClickListener.onAllItemSelected(stringBuilder.toString());
notifyDataSetChanged();
}
public void unselectAll() {
checkValue = 2;
myRecyclerClickListener.onAllItemUnSelected("");
notifyDataSetChanged();
}
public void setClickListener(MyRecyclerClickListener myRecyclerClickListener){
this.myRecyclerClickListener = myRecyclerClickListener
}
public interface MyRecyclerClickListener{
void onAllItemSelected(String text);
void onAllItemUnSelected(String text);
}
}
On the event when all check boxes are selected you update an observable field which is binded to your text view. You post the updated string to that observable and you should see them on the text view.

RecyclerView onClick not working on search items

I have implemented a search function on my application and it displays the results however the results can not be clicked. When not in search the onClick method works fine. Here is the code for my main class where the search takes place
MainActivity.java
public class MainActivity extends AppCompatActivity implements
RecyclerViewAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<Buildings> mUploads;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private FirebaseStorage mStorage;
private ValueEventListener mDBListener;
private EditText msearch;
ArrayList<Buildings> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mStorage = FirebaseStorage.getInstance();
mDatabaseRef =
FirebaseDatabase.getInstance().getReference("Buildings");
mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(MainActivity.this);
msearch = findViewById(R.id.search);
arrayList = new ArrayList<>();
msearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().isEmpty())
{
search(s.toString());
}
else{
search("");
}
}
});
//GET DATA FROM FIREBASE!!
mDBListener = mDatabaseRef.addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Buildings upload = postSnapshot.getValue(Buildings.class);
upload.setKey(postSnapshot.getKey());
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
} //end of on create
private void search(String s) {
Query query = mDatabaseRef.orderByChild("name")
.startAt(s).endAt(s + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
Buildings selectedItem = mUploads.get(position);
final String name = selectedItem.getName();
final String address = selectedItem.getAddress();
final String image_url = selectedItem.getImage_url();
final double longt = selectedItem.getLongitude();
final double lat = selectedItem.getLatitude();
final String uid = selectedItem.getUserID();
final String desc = selectedItem.getDescription();
final String categ = selectedItem.getCategorie();
Intent mainIntent = new Intent(MainActivity.this, ProfileActivity2.class);
mainIntent.putExtra("b_name", name);
mainIntent.putExtra("b_address", address);
mainIntent.putExtra("b_image_url", image_url);
mainIntent.putExtra("b_userId", uid);
mainIntent.putExtra("b_desc", desc);
mainIntent.putExtra("b_categ", categ);
Bundle b = new Bundle();
b.putDouble("longt", longt);
b.putDouble("lat", lat);
mainIntent.putExtras(b);
startActivity(mainIntent);
finish();
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ImageViewHolder> {
private Context mContext;
private List<Buildings> mUploads;
private OnItemClickListener mListener;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private boolean checkUid;
public RecyclerViewAdapter(Context context, List<Buildings> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.buildings_row_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Buildings uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
holder.textViewAddress.setText(uploadCurrent.getAddress());
Glide.with(mContext).load(mUploads.get(position).getImage_url()).into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public TextView textViewAddress;
LinearLayout view_container;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.building_name);
imageView = itemView.findViewById(R.id.thumbnail);
view_container = itemView.findViewById(R.id.container);
textViewAddress = itemView.findViewById(R.id.address);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(checkUid =true && mCurrentUser != null){
MenuItem delete = menu.add(Menu.NONE, 1, 1, "Delete");
delete.setOnMenuItemClickListener(this);
}
else{
//do nothing
}
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
Should I be adding something to my search function?
You are creating new adapter on reponse of your query, which isn't having active interface attached. So instead of creating new adapter, just update the data list and notify adapter.
Refer below code.
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
// Remove below two lines,
// It is not needed as we only need to notify adapter about the data change.
// RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
// mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
In search method, you create a new adapter but not setting its onItemClickListener.
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
Separate the setData and construct method for adapter, then you don't need to create new adapter every search. Or just set mAdapter.setOnItemClickListener for it.

How to get the Key when i clicked the item on recyclerview?

I'm creating an application with search and recycler view.
Here is my search_adapter:
public class search_adapter extends RecyclerView.Adapter<search_adapter.SearchViewHolder> {
private Context context;
private DatabaseReference mDatabase;
ArrayList<String> fullNameList;
ArrayList<String> dDateList;
private OnItemClickListener mListener;
Snapshot snapshot;
public search_adapter(Context context, ArrayList<String> fullNameList, ArrayList<String> dDateList) {
this.context = context;
this.fullNameList = fullNameList;
this.dDateList = dDateList;
}
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class SearchViewHolder extends RecyclerView.ViewHolder{
CardView clickCard;
TextView full_Name;
TextView death_Date;
public SearchViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
full_Name = (TextView) itemView.findViewById(R.id.person_name);
death_Date = (TextView) itemView.findViewById(R.id.person_death);
clickCard = (CardView) itemView.findViewById(R.id.cardClick);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener !=null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
#Override
public search_adapter.SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.recyclerview_adapter,parent,false);
return new search_adapter.SearchViewHolder(view, mListener);
}
public void onBindViewHolder(SearchViewHolder holder, final int position) {
holder.full_Name.setText(fullNameList.get(position));
holder.death_Date.setText(dDateList.get(position));
}
#Override
public int getItemCount() {
return fullNameList.size();
}
In this class, i create the view for the recycler view with onclick listener
I also include an interface so that i can pass the position of the clicked item.
Here is my search_activity class:
public class SearchActivity extends AppCompatActivity implements search_adapter.OnItemClickListener{
private RecyclerView mPerson;
private EditText mFindField;
public DatabaseReference mDatabase;
ArrayList<String> fullNameList;
ArrayList<String> dDateList;
private search_adapter searchAdapter;
int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
//Database Access//
mDatabase = FirebaseDatabase.getInstance().getReference();
//Recycler View//
mPerson = (RecyclerView)findViewById(R.id.person_list);
mPerson.setHasFixedSize(true);
mPerson.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
mPerson.setLayoutManager(new GridLayoutManager(this,3));
mFindField = (EditText) findViewById(R.id.search_field);
fullNameList = new ArrayList<>();
dDateList = new ArrayList<>();
mFindField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (!editable.toString().isEmpty()){
setAdapter(editable.toString());
} else {
fullNameList.clear();
dDateList.clear();
mPerson.removeAllViews();
}
}
});
}
private void setAdapter(final String searchedString) {
mDatabase.child("person").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
fullNameList.clear();
dDateList.clear();
mPerson.removeAllViews();
int counter = 0;
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
String full_name = snapshot.child("fullName").getValue(String.class);
String dDate = snapshot.child("dDate").getValue(String.class);
if (full_name.toLowerCase().contains(searchedString.toLowerCase())){
fullNameList.add(full_name);
dDateList.add(dDate);
counter++;
} else if (dDate.toLowerCase().contains(searchedString.toLowerCase())){
fullNameList.add(full_name);
dDateList.add(dDate);
counter++;
}
if (counter == 15)
break;
}
searchAdapter = new search_adapter(SearchActivity.this, fullNameList, dDateList);
mPerson.setAdapter(searchAdapter);
searchAdapter.setOnItemClickListener(SearchActivity.this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//new search//
#Override
public void onItemClick(int position) {
}
this is where the passed position will go,
but my problem is, I don't know how to get the key of that passed position, I try using getRef like the others did but it's not working.
My goal is for the user to clicked a data on the recycler view, open a new intent, and view all of the details of that certain clicked data.
Please help.
You have a list of names and a list of dates in your adapter, in the same way you can generate and add a list of keys, and in the viewholder onBind method you can bind the key to a field in your viewholder. And instead of sending position in your on click listener you can send your key.

How to load firebase data into recyclerview

I'm seeking help on how to load a data stored in a Firebase Database into a recyclerview.
The below screenshot indicates how I would like for the data to be structured when loaded into the recyclerview.
I am able to access the data from individual paths such as "Upcoming/Events/03/23" using the addEventListener but unable to load dynamically into a recyclerview in the format above.
See Code below that I have below to load the children under the different nodes, but i'm able to load it into the recyclerview
private ListView mUserList;
private ArrayList<String> mUpcomingList = new ArrayList<>();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,mUpcomingList);
mUserList.setAdapter(arrayAdapter);
String CurrentString = date.toString().trim();
StringTokenizer tokens = new StringTokenizer(CurrentString, "/");
String first = tokens.nextToken();
String second = tokens.nextToken();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Upcoming/Events").child(first);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
Public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG,"Listing children");
for (DataSnapshot child: dataSnapshot.getChildren()) {
mUpcomingList.add(child.getKey());
arrayAdapter.notifyDataSetChanged();
}
Your help is appreciated.
when you used then you make recyclerview adatper and bind this adapter into a recycler view . used below code for display firebase all the data and change according your need and make changes.
RecyclerView Adapter::
public class DisplayAllData extends RecyclerView.Adapter<DisplayAllData.ItemViewHolder>{
private List<User> mUserLsit=new ArrayList<>();
private Context mContext;
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext,List<User> mUserLsit) {
this.mContext=mContext;
this.mUserLsit = mUserLsit;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user=mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
#Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName,mTvEmail,mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail=itemView.findViewById(R.id.rlTvEmail);
mTvName=itemView.findViewById(R.id.rlTvName);
mTvPwd=itemView.findViewById(R.id.rlTvPwd);
}
}
}
In Adapter take a simple layout and make three textview control and bind data into that.
then after take activity layout and define recycler view in xml. then after used below code to read firebase database record and display recyclerview.
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List<User> mUserList = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
You have to use FirebaseRecyclerAdapter,
as
FirebaseRecyclerAdapter<Model, ViewHolder> Adapter = new FirebaseRecyclerAdapter<Model, ViewHolder>(
Model.class, //Name of model class
R.layout.row, //Row layout to show data
viewHolder.class, //Name of viewholder class
mDatabaseRef // Database Refernce
) {
#Override
protected void populateViewHolder(VieHolder viewHolder, Model model, int position) {
//Your Method to load Data
}
};
RecyclerView.setAdapter(Adapter);
For this you have to create two other classes, One is viewholder ( to display data) and second model class ( refers to name of nodes from where you are fetching data ).
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions<Cart> options = new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products"), Cart.class).build();
FirebaseRecyclerAdapter<Cart, CartViewHolder> adapter =
new FirebaseRecyclerAdapter<Cart, CartViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull CartViewHolder holder, int position, #NonNull final Cart model) {
holder.txtProductQuantity.setText("Quantity = " + model.getQuantity());
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price = " + model.getPrice() + "৳");
int oneTypeProductPrice = ((Integer.valueOf(model.getPrice()))) * Integer.valueOf(model.getQuantity());
overTotalPrices = overTotalPrices + oneTypeProductPrice;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]
{
"Edit",
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0){
Intent intent = new Intent(CartActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
if (i == 1){
cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(CartActivity.this,"Item removed successfully.",Toast.LENGTH_LONG).show();
Intent intent = new Intent(CartActivity.this, HomeActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout, parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}

Firebase list of data is unable to load in Custom recycler adaper

I am trying to load firebase list of data in my custom recycler adapter but I am unable to load it.
this code is displaying data in my logcat but I am unable to load in my app.
logcat showing no errors though. If I use firebase UI and try to do this thing then it is working fine but I want to inset native ads in recycler view to I had to migrate to custom adapter and now I am stuck with this issue. :(
my custom recycler adapet.
public class AuthorNameCustomRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<AuthorsCLA> authorlist;
Context mcontext;
public class NamesHolder extends RecyclerView.ViewHolder {
public TextView name;
public NamesHolder(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.authorNameTextView);
}
}
public AuthorNameCustomRecyclerAdapter(ArrayList<AuthorsCLA> authorlist, Context mcontext) {
this.authorlist = authorlist;
this.mcontext = mcontext;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 1: {
View view = inflater.inflate(R.layout.author_list_cv, parent, false);
viewHolder = new NamesHolder(view);
break;
}
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final AuthorsCLA authorsModel = authorlist.get(holder.getAdapterPosition());
switch (holder.getItemViewType()){
case 1:{
NamesHolder nameHolder = (NamesHolder) holder;
nameHolder.name.setText(authorsModel.getAuthorname());
nameHolder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AuthorQuotesDetailActvity.class);
mcontext.startActivity(intent);
}
});
}
}
}
#Override
public int getItemCount() {
return authorlist.size();
}
}
here is the class where i am calling custom recycler adapter.
public class AuthorsList extends AppCompatActivity {
private RecyclerView recyclerViewAuthor;
private StaggeredGridLayoutManager mlayoutManager;
private GridLayoutManager manager;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mdatabaseReference = database.getReference();
private AdView mAdView;
private RecyclerView.Adapter adapter;
private ArrayList<AuthorsCLA> authorlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authors_list);
MobileAds.initialize(this, "ca-app-pub-7854400750152181~4721849113");
mAdView = (AdView) findViewById(R.id.adView1);
AdRequest adRequest = new AdRequest.Builder().addTestDevice("2A79E20CADE70C60CF36B2E8EE9103FF").build();
mAdView.loadAd(adRequest);
recyclerViewAuthor = (RecyclerView) findViewById(R.id.authorsRecyclerView);
DatabaseReference mListItemRef = mdatabaseReference.child("en/of");
authorlist = new ArrayList<>();
manager = new GridLayoutManager(this,2);
recyclerViewAuthor.setLayoutManager(manager);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("Added",dataSnapshot.getKey());
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mListItemRef.addChildEventListener(childEventListener);
adapter = new AuthorNameCustomRecyclerAdapter(authorlist, this);
recyclerViewAuthor.setAdapter(adapter);
}
private void fetchData(DataSnapshot dataSnapshot) {
AuthorsCLA listItem=dataSnapshot.getValue(AuthorsCLA.class);
authorlist.add(listItem);
// recyclerViewAuthor.setAdapter(adapter);
}
}
onChildAdded() will be called each time when the child is fetched by firebase call. This is asynchronous process.
In your code you are adding it into ArrayList<>, but somehow you are not notifying the adapter that child is being added. It is safe to do that in your
private void fetchData(DataSnapshot dataSnapshot) {
AuthorsCLA listItem = dataSnapshot.getValue(AuthorsCLA.class);
authorlist.add(listItem);
adapter.notifyItemInserted(authorlist.size() - 1); // Notify the adapter
}

Categories

Resources