I have seen many answers regarding this issue, but nothing works for my coding.
I referred the codes based on this youtube videos and now I have this issue. Not sure how his code works and mine don't. Apparently I'm also new into this topic (RecyclerView).
This is my main activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_product) ;
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").child("Products");
recyclerView = findViewById(R.id.stallproductRecyclerView);
//newest
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
//
searchView = findViewById(R.id.searchProductStall);
}
#Override
protected void onRestart() {
super.onRestart();
if (ref!=null)
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
list.add(ds.getValue(Model.class));
}
ViewHolder viewHolder = new ViewHolder(list);
recyclerView.setAdapter(viewHolder);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ViewProduct.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
and this is ViewHolder class.
ArrayList<Model> list;
public ViewHolder (ArrayList<Model> list)
{
this.list=list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_product,
viewGroup,false);
return new MyViewHolder(view);
}
Set adapter in oncreate() with empty data and after fetching data you should call adapter.notifyDataSetChanged() like following.
ViewHolder viewHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_product) ;
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").child("Products");
recyclerView = findViewById(R.id.stallproductRecyclerView);
//newest
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
//
searchView = findViewById(R.id.searchProductStall);
// here you have to set the adapter to your recycler view
list = new ArrayList<>();
viewHolder = new ViewHolder(list);
recyclerView.setAdapter(viewHolder);
}
#Override
protected void onRestart() {
super.onRestart();
if (ref!=null)
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
// clear your previous data
list.clear();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
list.add(ds.getValue(Model.class));
}
// here you have to notify you adapter that your data set is changed like below
viewHolder.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ViewProduct.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
Related
I am new in android development. I am trying to create list of firebase data. so i have created a recyclerview and represent the data in recyclerview.
I have featched data from firebase and assign to adapter class. but data is not showing in recyclerview.
Fragment Class
public class HomeFragment extends Fragment {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Carmodel> list = new ArrayList<>();;
CarAdapter adapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.recyclerview, container, false);
recyclerView = (RecyclerView) root.findViewById(R.id.recycler);
recyclerView.setLayoutManager( new LinearLayoutManager(getContext()));
reference = FirebaseDatabase.getInstance().getReference().child("AddCar");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Carmodel p = dataSnapshot1.getValue(Carmodel.class);
Log.e("Get Data", p.getCarName());
list.add(p);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), "Opsss.... Something is wrong", Toast.LENGTH_SHORT).show();
}
});
adapter = new CarAdapter(getContext(), list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return root;
}
}
Adapert Class
public class CarAdapter extends RecyclerView.Adapter<CarAdapter.MyViewHolder> {
Context context;
ArrayList<Carmodel> profiles;
public CarAdapter(Context c , ArrayList<Carmodel> p)
{
context = c;
profiles = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.fragment_admin_home, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.name.setText(profiles.get(position).getCarName());
holder.seater.setText(profiles.get(position).getSeater());
holder.price.setText(profiles.get(position).getPrice());
holder.status.setText(profiles.get(position).getAvailable());
Picasso.get().load(profiles.get(position).getImageURL()).into(holder.car_image);
}
#Override
public int getItemCount() {
return profiles.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
TextView name,seater,price, status;
ImageView car_image;
#SuppressLint("CutPasteId")
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.CarName);
seater = (TextView) itemView.findViewById(R.id.Seater);
price = (TextView) itemView.findViewById(R.id.Seater);
car_image = (ImageView) itemView.findViewById(R.id.imageView);
status = (TextView) itemView.findViewById(R.id.Status);
}
}
Carmodel p = dataSnapshot1.getValue(Carmodel.class);
make you sure it is (p) not empty
You are notifying your adapter in wrong time for data change
adapter = new CarAdapter(getContext(), list);
recyclerView.setAdapter(adapter);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Carmodel p = dataSnapshot1.getValue(Carmodel.class);
Log.e("Get Data", p.getCarName());
list.add(p);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), "Opsss.... Something is wrong", Toast.LENGTH_SHORT).show();
}
});
Please modify your method like this
I would like to know how can I do a recyclerView that shows data that I got from this database reference:
Salas= new ArrayList<String>();
DatabaseReference referenceSalas = FirebaseDatabase.getInstance().getReference("salas/");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("usuarios/");
FirebaseAuth autenticacao = FirebaseAuth.getInstance();
String emailUsu = autenticacao.getCurrentUser().getEmail();
reference.orderByChild("email").equalTo(emailUsu).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
nomeProf = datas.child("nome").getValue().toString();
referenceSalas.orderByChild("nomeProf").equalTo(nomeProf).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
Salas.add(datas.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
I tried to do the RecyclerView like this:
public class salasFragment extends Fragment {
private RecyclerView mRecycleViewSalas;
private adapterSalas adapterSalas;
private ArrayList<salas> listaSalas= new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private TextView txtSalas, txtTeste;
private String nomeProf;
private String teste="", piru;
private DatabaseReference reference = FirebaseDatabase.getInstance().getReference("usuarios/");
private DatabaseReference referenceSalas = FirebaseDatabase.getInstance().getReference("salas/");
private ValueEventListener valueEventListenerSalas;
ArrayList<String> salasAula = new ArrayList<String>();
public salasFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_salas, container, false);
final Context context = view.getContext();
txtSalas= view.findViewById(R.id.txtSalas);
txtTeste= view.findViewById(R.id.txtTeste);
mRecycleViewSalas= view.findViewById(R.id.recyclerSalas);
adapterSalas= new adapterSalas(listaSalas, context);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
mRecycleViewSalas.setLayoutManager(layoutManager);
mRecycleViewSalas.setHasFixedSize(true);
mRecycleViewSalas.setAdapter(adapterSalas);
return view; }
#Override
public void onStart() {
super.onStart();
recuperarSalas();
}
#Override
public void onStop() {
super.onStop();
reference.removeEventListener(valueEventListenerSalas);
}
public void recuperarSalas(){
FirebaseAuth autenticacao = FirebaseAuth.getInstance();
String emailUsu = autenticacao.getCurrentUser().getEmail();
valueEventListenerSalas = reference.orderByChild("email").equalTo(emailUsu).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
nomeProf = datas.child("nome").getValue().toString();
referenceSalas.orderByChild("nomeProf").equalTo(nomeProf).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
salas salas=datas.getKey(salas.class);
listaSalas.add(salas);
}
adapterSalas.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
my adapter:
public class adapterSalas extends RecyclerView.Adapter<adapterSalas.myViewHolder> {
private List<salas> Salas;
private Context context;
public adapterSalas(List<salas> listaSalas, Context c ) {
this.Salas= listaSalas;
this.context = c;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_salas, parent, false);
return new myViewHolder(itemLista);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
salas sala = Salas.get(position);
holder.btn1.setText(sala.getPrimeiro());
}
#Override
public int getItemCount() {
return Salas.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
Button btn1;
public myViewHolder(#NonNull View itemView) {
super(itemView);
btn1 = itemView.findViewById(R.id.btn1);
}
}
}
Although this line "salas salas=datas.getKey(salas.class);" does not work properly when I use "getKey", It only works when "getValue" is used. There is no way of me doing this project with "getValue" instead of "getKey". So there is any way that can make this recyclerView works properly with "getKey" ?
Have you got the data from the firebase already?
If you got the data in an arraylist already, simply plug it in an adapter (you will need to create a RecyclerView adapter, a class to describe the value of each RecyclerView items) and set it to the RecyclerView and you are good to go!
You can use FirebasRecyclerAdapter as you recyclerView adapter. check out this link for a guide on how to use it.
https://medium.com/android-grid/how-to-use-firebaserecycleradpater-with-latest-firebase-dependencies-in-android-aff7a33adb8b
I am new to Firebase and just used it today for our app. I have successfully inserted the items to my Firebase console. Now I want these items to display in my Recyclerview using Fragments.
I have experienced this error since morning and exhausted all the information but nothing seems to work for me.
Please check this code and enlighten me what seems to be the problem:
This my Category model
package com.example.devcash.Object;
public class Category {
public String category_name;
public Category(){
}
public Category(String category_name){
this.category_name = category_name;
}
public String getCategory_name() {
return category_name;
}
public void setCategory_name(String category_name) {
this.category_name = category_name;
}
}
CategoriesFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_categories, container, false);
//
categoryrecyclerView = (RecyclerView) view.findViewById(R.id.catrecyclerview);
categoryrecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
catlist = new ArrayList<Category>();
reference = FirebaseDatabase.getInstance().getReference().child("Category");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
Category c = dataSnapshot1.getValue(Category.class);
catlist.add(c);
}
adapter = new CategoryAdapter(getContext(), catlist);
categoryrecyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), "Something is wrong, please try that again.", Toast.LENGTH_SHORT).show();
}
});
return view;
}
AddCategory
public class AddCategoryActivity extends AppCompatActivity {
private DatabaseReference firebaseDatabase;
private FirebaseDatabase firebaseInstance;
private String CategoryId;
TextInputEditText categoryName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
categoryName = (TextInputEditText) findViewById(R.id.text_categoryname);
firebaseInstance = FirebaseDatabase.getInstance();
firebaseDatabase = firebaseInstance.getReference("DataDevcash");
CategoryId = firebaseDatabase.push().getKey();
}
public void addCategory (String categoryName){
Category category = new Category(categoryName);
firebaseDatabase.child("Category").child(CategoryId).setValue(category);
}
public void insertCategory(){
addCategory(categoryName.getText().toString().trim());
Toast.makeText(getApplicationContext(), "Category Successfully Added!", Toast.LENGTH_SHORT).show();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
onBackPressed();
return true;
}else if(id == R.id.action_save){ //if SAVE is clicked
insertCategory();
}
return super.onOptionsItemSelected(item);
}
}
CategoryAdapter
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
Context context;
ArrayList<Category> categoryArrayList;
public CategoryAdapter(Context c, ArrayList<Category> categories){
context = c;
categoryArrayList = categories;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.customlayout_category, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.categoryname.setText(categoryArrayList.get(i).getCategory_name());
}
#Override
public int getItemCount() {
return categoryArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView categoryname;
public ViewHolder(#NonNull View itemView) {
super(itemView);
categoryname = (TextView) itemView.findViewById(R.id.txtcategory_name);
}
}
}
fragment_categories.xml
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/catrecyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="1dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/addcategories_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_add"
android:tint="#color/whiteBG"
android:backgroundTint="#color/colorPrimary"/>
</FrameLayout>
Logcat
RecyclerView: No adapter attached; skipping layout
When I try to move my FirebaseDatabase code from onCreateView to onCreate, I will get this error from my logcat.
Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at com.example.devcash.Fragments.CategoriesFragment.onCreate
I have also tried to change the layout_height from match_parent to wrap_content and vice versa but still the items will not show..
The first logcat is simply a warning saying that .setAdapter has not been called on your recyclerView hence nothing would be loaded to it. This is probably because the overridden method onDataChange where you added setAdapter trigger was never called.
The second logcat is an error telling you that you tried to access the RecyclerView before it is initialized. Why? Because you are calling from the wrong method block. Check android fragment lifecycle for more info
To fix both issues refactor your code like below
-- Initialize your adapter and recyclerView only once. i.e inside onCreateView block
catlist = new ArrayList<Category>();
adapter = new CategoryAdapter(getActivity(), catlist);
categoryrecyclerView.setAdapter(adapter);
-- Call notifyDataSetChanged on the adapter anytime the value of catlist changes. Add the below code inside onDataChange callback method
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
Category c = dataSnapshot1.getValue(Category.class);
catlist.add(c);
}
adapter.notifyDataSetChanged();
// adapter = new CategoryAdapter(getContext(), catlist);
// categoryrecyclerView.setAdapter(adapter);
}
You can verify if your implementation is right by adding some dummy data to catlist
//call this any where and if it works then be rest assured
//that no data is returned from your firebase reference
catlist.add(new Category("Sample Category"));
adapter.notifyDataSetChanged();
try this
CategoryAdapter adapter = new CategoryAdapter(getContext());
categoryrecyclerView.setLayoutManager(new
LinearLayoutManager(getContext()));
categoryrecyclerView.setAdapter(adapter );
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
Category c = dataSnapshot1.getValue(Category.class);
catlist.add(c);
}
adapter.pushData(catlist);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), "Something is wrong, please try that
again.", Toast.LENGTH_SHORT).show();
}
});
inside your adapter add this method
public void pushData(List<Category> list){
this.list.clear();
this.list.addAll(list);
notifyDataSetChanged();
}
CategoryAdapter adapter = new CategoryAdapter(getactivity(),catlist);
categoryrecyclerView.setLayoutManager(new
LinearLayoutManager(getactivity()));
categoryrecyclerView.setAdapter(adapter );
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
catlist.clear();
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
Category c = dataSnapshot1.getValue(Category.class);
catlist.add(c);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), "Something is wrong, please try that
again.", Toast.LENGTH_SHORT).show();
}
});
change your adapter with attached array list.Get value from it.
I have implemented a notification center using a
recyclerview displayed on a fragment , when I click on the item it writes a value on the database and then base of the condition the green Notification Bell appears/dissapears, the problem here is that all items get affected from trembling effect
Image:
https://im4.ezgif.com/tmp/ezgif-4-1adb4a5b29e3.gif
My adapter
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
NotifsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(currentUserID).child("comments").child(delUid).hasChild("state"))
{
String state = dataSnapshot.child(currentUserID).child("comments").child(delUid).child("state").getValue().toString();
if (state.equals("unread"))
{
holder.notifImg.setVisibility(View.VISIBLE);
}
else {
holder.notifImg.setVisibility(View.GONE);
}}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{ NotifsRef.child(currentUserID).child("comments").child(delUid).child("state").setValue("read");
}
});
}
#Override
public int getItemCount() {
return mNotifications.size();
}
Fragment:
{
OnCreate{...}
notificationList = (RecyclerView) notificationFragmentView.findViewById(R.id.notifications_list);
notificationAdapter = new NotificationAdapter(getContext(), mNotifications);
notificationList.setAdapter(notificationAdapter);
notificationList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
notificationList.setLayoutManager(linearLayoutManager);
}
private void readMsgList()
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{ mNotifications.clear();
for (DataSnapshot snapshot : dataSnapshot.child(currentUserID).child("comments").getChildren())
{
Notifications notifications = snapshot.getValue(Notifications.class);
mNotifications.add(notifications);
}
notificationAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});
}
I have tried to change the listener from ValueEventListener to SingleValueEventListener but without any result.
Is there any way to correct this ?
I create fire base Real time data base project and try to display student List in Recycler View, the data appear normally in fire base console but didn't appear in the simulator ?
Here is the Recycler View Class code :
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentHolder> {
private Context context;
private List<Student> studentList;
public StudentAdapter(Context context, List<Student> studentList) {
this.context = context;
this.studentList = studentList;
}
#Override
public StudentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_row, parent, false);
return new StudentHolder(row);
}
#Override
public void onBindViewHolder(StudentHolder holder, int position) {
final Student student = studentList.get(position);
holder.studentNameTv.setText(student.getName());
holder.studentAvgTv.setText(String.valueOf(student.getAverage()));
holder.editStudentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, EditStudentActivity.class);
intent.putExtra("name", student.getName());
context.startActivity(intent);
}
});
holder.deleteStudentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
Query query = ref.child("students").orderByChild("name").equalTo(student.getName());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
snapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return studentList.size();
}
class StudentHolder extends RecyclerView.ViewHolder {
TextView studentNameTv, studentAvgTv;
Button deleteStudentBtn, editStudentBtn;
public StudentHolder(View itemView) {
super(itemView);
studentNameTv = (TextView) itemView.findViewById(R.id.student_name);
studentAvgTv = (TextView) itemView.findViewById(R.id.student_avg);
deleteStudentBtn = (Button) itemView.findViewById(R.id.delete_student);
editStudentBtn = (Button) itemView.findViewById(R.id.edit_student);
}
}
}
and Here is the Main Activity Class code :
public class MainActivity extends AppCompatActivity {
List<Student> studentList = new ArrayList<>();
StudentAdapter adapter;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ref = database.getReference();
ref.child("students").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
studentList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Student student = snapshot.getValue(Student.class);
studentList.add(student);
adapter.notifyDataSetChanged();
}
Collections.reverse(studentList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
adapter = new StudentAdapter(MainActivity.this, studentList);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(adapter);
SearchView searchView = (SearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Query fireQuery = ref.child("students").orderByChild("name").equalTo(query);
fireQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();
} else {
List<Student> searchList = new ArrayList<Student>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Student student = snapshot.getValue(Student.class);
searchList.add(student);
adapter = new StudentAdapter(MainActivity.this, searchList);
recyclerView.setAdapter(adapter);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
adapter = new StudentAdapter(MainActivity.this, studentList);
recyclerView.setAdapter(adapter);
return false;
}
});
}
}