I'm developing an android app where the details from the Firebase Realtime Database will be shown in Recycler View.
I want to make it like expandable recyclerview.
But I'm getting a error when i tried to use my adapter.
Variable 'adapter' might not have been initialised
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Employee>()
.setQuery(mAttendanceDatabase, Employee.class)
.build();
final FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> adapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final EmployeeViewHolder holder, final int position, #NonNull Employee model) {
String employee_Id = getRef(position).getKey();
assert employee_Id != null;
mAttendanceDatabase.child(employee_Id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String employee_Name = dataSnapshot.child("employeeName").getValue().toString();
holder.employeeName.setText(employee_Name);
holder.btn_viewMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.getItem(position); //I'm getting error here
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_view_layout, parent, false);
EmployeeViewHolder viewHolder = new EmployeeViewHolder(view);
return viewHolder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class EmployeeViewHolder extends RecyclerView.ViewHolder{
TextView employeeName;
ImageButton btn_viewMore;
public EmployeeViewHolder(#NonNull View itemView) {
super(itemView);
employeeName = itemView.findViewById(R.id.employeeName_evl);
btn_viewMore = itemView.findViewById(R.id.viewMoreBtn);
}
}
I can't find any proper solution. Help me with this.
try to put the adapter over this in a variable:
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Employee>()
.setQuery(mAttendanceDatabase, Employee.class)
.build();
final FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> adapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final EmployeeViewHolder holder, final int position, #NonNull Employee model) {
String employee_Id = getRef(position).getKey();
assert employee_Id != null;
final FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> thisAdapter = this;
mAttendanceDatabase.child(employee_Id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String employee_Name = dataSnapshot.child("employeeName").getValue().toString();
holder.employeeName.setText(employee_Name);
holder.btn_viewMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
thisAdapter.getItem(position); //I'm getting error here
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_view_layout, parent, false);
EmployeeViewHolder viewHolder = new EmployeeViewHolder(view);
return viewHolder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
Edit
To support my case I made a minimal Example:
Related
I have a recycler view that is being populated by firebase database. On the item.xml I have a button alongside data. On clicking the button on each item, I want to save supplier name in my database. Get error: nullpointer exception as my class Suppliers remains null. What is causing it?
Code
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.MyViewHolder> {
Context context;
ArrayList<supplierClass> list;
public recyclerAdapter(Context context, ArrayList<supplierClass> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
supplierClass sc = list.get(position);
holder.sName.setText(sc.getsName());
holder.materialName.setText(sc.getMaterialName());
holder.CATEGORY.setText(sc.getCATEGORY());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView sName,materialName,CATEGORY;
Button btnSelect;
DatabaseReference ref;
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
public MyViewHolder(#NonNull View itemView) {
super(itemView);
sName = itemView.findViewById(R.id.lblSupplierName);
materialName = itemView.findViewById(R.id.lblMaterial);
CATEGORY = itemView.findViewById(R.id.lblLocation);
btnSelect=itemView.findViewById(R.id.btnSelect);
supplierClass sc=new supplierClass();
String id=user.getUid();
btnSelect.setOnClickListener(v -> {
ref= FirebaseDatabase.getInstance().getReference("dashboard");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
ref.child(id).setValue(sc.getsName());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
});
}
}
I need to add ClickListener to RecyclerView in my project but I couldn't.
I tried for days and failed :(
Help me, please.
(the variables are in Italian)
RecyclerView class:
public class ListaNonConsegnate extends AppCompatActivity{
private androidx.recyclerview.widget.RecyclerView recyclerView;
EditText searchBox;
DatabaseReference nonConsegnate;
private ArrayList<dati> list;
private String nomeUtente;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_non_consegnate);
Bundle extras = getIntent().getExtras();
nomeUtente = extras.getString("KEY_nomeUtente"); //variable from the previous activity
searchBox = findViewById(R.id.searchBox); //for filtered list
nonConsegnate = FirebaseDatabase.getInstance().getReference().child(nomeUtente + "/00-b-Non consegnate"); //path on the database
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
searchBox.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) {
ArrayList<dati> myList = new ArrayList<>();
//add filter
AdapterClass adapterClass = new AdapterClass(myList);
recyclerView.setAdapter(adapterClass);
}
});
}
#Override
protected void onStart() {
super.onStart();
if (nonConsegnate != null) {
nonConsegnate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
list = new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()) {
list.add(ds.getValue(dati.class));
}
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ListaNonConsegnate.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Adapter class:
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>{
ArrayList<dati> list;
public AdapterClass(ArrayList<dati> list){
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_items, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.bolla.setText(list.get(position).getDDT());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView bolla;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
bolla = itemView.findViewById(R.id.textViewBolla);
}
}
}
(OnClick will have to open a new activity by passing it the "nomeUtente" and "DDT" variables)
Thank you.
(StackOverflow tells me I need to add more details but there's nothing more to say so I write useless sentences) lol
1- Add this Code To Your Activity :
public void onClickCalled() {
// Your Code
}
2- and this in your adapter :
holder.nomeUtente.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((YourNewActivity) context).onClickCalled();
}
});
I have an ImageView which acts as a like button and when a user clicks on it, it changes to a different ImageView which indicates that that comment was liked. The problem is that when I click on one, more than one gets selected. Let's say that there are 6 comments in the list and I "like" the 4th comment, other ones get "liked" also which shouldn't happen. The only one that should be getting "liked" is the one I click on. How can I fix this?
CommentAdapter
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Comment comment = mCommentList.get(position);
holder.comment.setText(comment.getComment());
commentLike(comment.getCommentid(), holder.commentLike);
commentDislike(comment.getCommentid(), holder.commentDislike);
holder.commentLike.setOnClickListener(v -> {
if (holder.commentLike.getTag().equals("like") && holder.commentDislike.getTag().equals("dislike")) {
likeComment(comment.getCommentid(), mPostId, comment.getPublisher());
} else if (holder.commentLike.getTag().equals("like") && holder.commentDislike.getTag().equals("disliked")) {
likeComment(comment.getCommentid(), mPostId, comment.getPublisher());
removeDislike(comment.getCommentid());
} else {
removeLike(comment.getPublisher(), comment.getCommentid());
}
});
holder.commentDislike.setOnClickListener(v -> {
if (holder.commentDislike.getTag().equals("dislike") && holder.commentLike.getTag().equals("like")) {
dislikeComment(comment.getCommentid());
Toast.makeText(mContext, "Don't be mean", Toast.LENGTH_SHORT).show();
} else if (holder.commentDislike.getTag().equals("dislike") && holder.commentLike.getTag().equals("liked")) {
dislikeComment(comment.getCommentid());
removeLike(comment.getPublisher(), comment.getCommentid());
Toast.makeText(mContext, "Don't be mean", Toast.LENGTH_SHORT).show();
} else {
removeDislike(comment.getCommentid());
}
});
holder.itemView.setOnLongClickListener(v -> {
if (comment.getPublisher().equals(mFirebaseUser.getUid())) {
AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
alertDialog.setTitle("Would you like to delete this comment?");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "No", (dialog, which) -> dialog.dismiss());
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", (dialog, which) -> {
deleteCommentNotification(mPostId, comment.getCommentid());
FirebaseDatabase.getInstance().getReference("Comments Liked").child(comment.getCommentid()).setValue(null);
FirebaseDatabase.getInstance().getReference("Comments Disliked").child(comment.getCommentid()).setValue(null);
FirebaseDatabase.getInstance().getReference("Responses").child(comment.getCommentid()).setValue(null);
Toast.makeText(mContext, "Your comment has been deleted.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
});
alertDialog.show();
}
return true;
});
static class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image_profile;
TextView username, comment, commentLikesNumber, commentDislikesNumber, commentResponseNumber, timestamp;
ImageView commentLike, commentDislike, iconComment;
ViewHolder(#NonNull View itemView) {
super(itemView);
commentLike = itemView.findViewById(R.id.icon_thumb_up_grey);
commentDislike = itemView.findViewById(R.id.icon_thumb_down_grey);
}
}
private void commentLike(final String commentid, final ImageView imageView) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments Liked").child(commentid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (mFirebaseUser != null)
if (dataSnapshot.child(mFirebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_thumb_up_blue);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_thumb_up_grey);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void commentDislike(final String commentid, final ImageView imageView) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments Disliked").child(commentid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (mFirebaseUser != null)
if (dataSnapshot.child(mFirebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_thumb_down_blue);
imageView.setTag("disliked");
} else {
imageView.setImageResource(R.drawable.ic_thumb_down_grey);
imageView.setTag("dislike");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
CommentsActivity
private void readComments() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(mPostId);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Comment comment = dataSnapshot.getValue(Comment.class);
try {
comment.setComment(decrypt(comment.getComment(), mPassword));
} catch (Exception e) {
e.printStackTrace();
}
mCommentList.add(comment);
keysList.add(dataSnapshot.getKey());
mCommentAdapter.notifyItemInserted(mCommentList.size() - 1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = keysList.indexOf(dataSnapshot.getKey());
mCommentList.remove(index);
keysList.remove(index);
mCommentAdapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
reference.addChildEventListener(childEventListener);
}
I have seen your code and found that you are making mistake by fetching data from firebase by creating methods in the adapter and calling it from onBindViewHolder.
I am currently working with firebase realtime database and I had faced the same problem like you before 3 months and the solution i have used is working fine.
You should have to use asyncTask inside recycler view adapter. Please have a look at my code, this may help you.
Feel free to ask me if you need any help regarding android and firebase
ChooserAdapter.java
public class ChooserAdapter extends RecyclerView.Adapter<ViewHolder> {
ArrayList<Bean> list;
Context context;
public ChooserAdapter(ArrayList<DoctorList> list, Context context) {
this.listFiltered = list;
this.list = list;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.bean = list.get(position);
holder.asyncTask = new AsyncTask(holder,holder.bean.getId());
holder.asyncTask.execute();
}
#Override
public int getItemCount() {
return list.size();
}
public ArrayList<List> adapterList() {
return list;
}
public List getItem(int position) {
return list.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.txtTitle)
TextView txtTitle;
AsyncTask asyncTask;
Bean bean;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
static class AsyncTask extends AsyncTask<Void, Integer, String> {
ViewHolder viewHolder;
String Id;
DatabaseReference dbRef;
AsyncTask(ViewHolder viewHolder, String Id) {
this.viewHolder = viewHolder;
this.Id = Id;
dbRef = FirebaseDatabase.getInstance().getReference("FcmNode");
dbRef.keepSynced(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
if (!isCancelled())
dbRef.orderByChild("Id").equalTo(Id).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String name = dataSnapshot.getValue(String.class);
viewHolder.txtTitle.setText(name);
viewHolder.txtTitle.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return "";
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
}
}
}
I'm trying to remove data from my recyclerview and let it be updated in the mobile ui as well. It is an android app. I am able to delete the data alright but I always have to leave that page and come back when I make the changes. I tried making some modifications to the onChildRemoved method but I started getting crashes upon making this change. What do I do? Below is my code.
MainActivity.java
DatabaseReference databaseReference;
List<DataSnapshot> listData;
RecyclerView recyclerView;
MyCart.MyAdapter adapter;
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
listData = new ArrayList<>();
adapter = new MyCart.MyAdapter(listData);
adapter.setHasStableIds(true);
GetDataFirebase();
private void GetDataFirebase() {
databaseReference = FirebaseDatabase.getInstance().getReference()
.child("Customers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Items students = dataSnapshot.getValue(Items.class);
listData.add(dataSnapshot);
recyclerView.setAdapter(adapter);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = listData.indexOf(dataSnapshot);
listData.remove(index);
adapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyCart.MyAdapter.ViewHolder> {
List<DataSnapshot> list;
public MyAdapter(List<DataSnapshot> List) {
this.list = List;
}
#Override
public void onBindViewHolder(MyCart.MyAdapter.ViewHolder holder, int position) {
final DataSnapshot studentSnapshot = list.get(position);
final Items students = studentSnapshot.getValue(Items.class);
final String list_user_id = studentSnapshot.getKey();
holder.item_name.setText(students.getItem_name());
holder.item_price.setText(students.getItem_price());
Picasso.with(holder.item_image.getContext()).load(students.getItem_image()).placeholder(R.drawable.no_image_two).into(holder.item_image);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference prod_ref = FirebaseDatabase.getInstance().getReference().child("Customers").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart").child(list_user_id);
prod_ref.removeValue();
adapter.notifyDataSetChanged();
Toast.makeText(MyCart.this, "Item removed from cart", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public MyCart.MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_item_layout, parent, false);
return new MyCart.MyAdapter.ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView item_name, item_price;
ImageView item_image;
ImageView delete;
public ViewHolder(View itemView) {
super(itemView);
item_name = itemView.findViewById(R.id.item_name);
item_price = itemView.findViewById(R.id.item_price);
item_image = itemView.findViewById(R.id.item_image);
delete = itemView.findViewById(R.id.delete_item);
}
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference prod_ref = FirebaseDatabase.getInstance().getReference().child("Customers").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart").child(list_user_id);
prod_ref.removeValue();
//add/modify these two lines here
list.remove(position);
notifyDataSetChanged();
}
});
And one more change you need to do
// move this toast to onChildRemoved method and clear the other code from there
Toast.makeText(MyCart.this, "Item removed from cart", Toast.LENGTH_SHORT).show();
like
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
//remove these line these will raise the exception and Toast here
int index = listData.indexOf(dataSnapshot);
listData.remove(index);
adapter.notifyDataSetChanged();
}
When dataSnapshot does not exist in list, it returns -1. Index of list start from 0. Therefore, you're this getting error. You need to add a guard check here like:
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = listData.indexOf(dataSnapshot);
if(index > 0) {
listData.remove(index);
}
adapter.notifyDataSetChanged();
}
Can anyone check if there are errors in it. here my code, If there is any error in the code please tell me? I don't know how to fix the code Search.java.
in my RecyclerItemClickListener.java
public interface RecyclerItemClickListener {
void onItemClick(int position);
}
My Adapter HierAdapter.java
public class HireAdapter extends RecyclerView.Adapter<HireAdapter.ViewHolder>{
private ArrayList<HireItem> TeacherItemList;
private Context context;
private RecyclerItemClickListener itemClickListener;
public HireAdapter(Context c, ArrayList<HireItem> teacherItemList, RecyclerItemClickListener listener) {
TeacherItemList = teacherItemList;
context = c;
itemClickListener = listener;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public final TextView nameText, subjectText,levelText ,cityText;
public ViewHolder(View itemView) {
super(itemView);
nameText = (TextView)itemView.findViewById(R.id.result_name);
subjectText = (TextView)itemView.findViewById(R.id.result_subject);
levelText = (TextView)itemView.findViewById(R.id.result_level);
cityText = (TextView)itemView.findViewById(R.id.result_city);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return TeacherItemList.size();
}}
Here Search.java, I wrote notes at each error. Because I did not know how to correct some codes to work with HireAdapter and RecyclerItemClickListener, can anyone solve the error?
public class Search extends Fragment implements RecyclerItemClickListener {
private Context context;
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private List<HireItem> hireItem = new ArrayList<>();
HireAdapter mAdapter;
ImageView bt_search;
ProgressDialog progressDialog;
Spinner spinner_sort;
String key = "req_skill1";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_search,container,false);
//Getting FireBase Instance
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference("teachers");
//Getting id of Views
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_places);
recyclerView.setAdapter(mAdapter);
//
bt_search = (ImageView)view.findViewById(R.id.bt_search);
spinner_sort = (Spinner)view.findViewById(R.id.spinner_sort);
setupSpinner();
List<HireItem> hireItem = new ArrayList<>();
mAdapter = new HireAdapter(getContext(),R.layout.list_item_teachers,hireItem); // error at (getContext(),R.layout.list_item_teachers,hireItem)
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAdapter != null){
mAdapter.clear(); // error at .clear();
}
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Searching Teachers");
progressDialog.show();
FirebaseDatabase.getInstance().getReference("teachers").orderByChild("subject").startAt(key).endAt(key + "~")
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Teachers child = dataSnapshot.getValue(Teachers.class);
HireItem hireItem = new HireItem(child.teaname, child.city, child.subject, child.level, child.sex,child.mobile, child.qualification, child.skill1, child.experince, child.salary,child.age);
mAdapter.add(hireItem); // error at .add
progressDialog.dismiss();
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
#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) {
}
});
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
else{
recyclerView.setAdapter(mAdapter); // error at recyclerView
}
}
});
return view;
}
private void setupSpinner(){
ArrayAdapter adapter = ArrayAdapter.createFromResource(getContext(),R.array.array_teacher_sort,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_sort.setAdapter(adapter);
spinner_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
key = (String)adapterView.getItemAtPosition(i);
if(key.equals(getString(R.string.sort_A))){
key = "Math";
}else if(key.equals(getString(R.string.sort_AA))){
key = "computer";
}
else if(key.equals(getString(R.string.sort_AB))){
key = "Biology";
}
else if(key.equals(getString(R.string.sort_AD))){
key = "Physics";
}
else if(key.equals(getString(R.string.sort_AXX))){
key = "Holy Quran";
}
else if(key.equals(getString(R.string.sort_AZ))){
key = "Chysics";
}
else if(key.equals(getString(R.string.sort_AS))){
key = "English";
}
else if(key.equals(getString(R.string.sort_AQ))){
key = "Arabic";
}
else if(key.equals(getString(R.string.sort_ADD))){
key = "Science";
}
else if(key.equals(getString(R.string.sort_AE))){
key = "History";
}
else if(key.equals(getString(R.string.sort_AW))){
key = "Geograpghy";
}
else if(key.equals(getString(R.string.sort_AR))){
key = "Art education";
}
else if(key.equals(getString(R.string.sort_AT))){
key = "Family education";
}
else if(key.equals(getString(R.string.sort_aae))){
key = "Religion";
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onResume() {
super.onResume();
mAdapter.clear(); // error at .clear();
}
#Override
public void onItemClick(int position) {
} }
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
Here you are setting onClickListner on the same view twice. The Listener set in the onBindViewHolder will override the Listner set in the onCreateViewHolder method.