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

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.

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.

Not printing the position of recyclerView in logcat

I'm trying to print the position of RecyclerView in logcat when I click on the list of recyclerView, but it's not printing anything. Actually in this app, if I click on a position of the recyclerview, that should take me to new activity and grab all the details of that position on which I clicked.
Here is my ImageAdapter.java class
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<UserDetails> mUploads;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ImageAdapter(Context context, List<UserDetails> uploads) {
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.user_display, viewGroup, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder imageViewHolder, int i) {
UserDetails currentItem = mUploads.get(i);
UserDetails userDetails = mUploads.get(i);
imageViewHolder.requestId.setText("Request Id : " + userDetails.getMobileNumber());
imageViewHolder.customerName.setText(userDetails.getName());
imageViewHolder.customerMobile.setText("Mobile : " + userDetails.getMobileNumber());
imageViewHolder.customerAddress.setText(userDetails.getAddress());
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView requestId, customerName, customerAddress, customerMobile, serviceType, date;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
requestId = itemView.findViewById(R.id.requestId);
customerName = itemView.findViewById(R.id.customerName);
customerAddress = itemView.findViewById(R.id.customerAddress);
customerMobile = itemView.findViewById(R.id.customerMobile);
serviceType = itemView.findViewById(R.id.serviceType);
date = itemView.findViewById(R.id.date);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
and here is the recyclerView class
public class requestList extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
RecyclerView recyclerView;
DatabaseReference databaseReference;
List<UserDetails> downloadDataArray;
ImageAdapter adapter;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request_list);
progressBar = findViewById(R.id.progressBar);
Toolbar toolbar = findViewById(R.id.roServiceToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Requests");
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(requestList.this, customerRequests.class));
}
});
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
downloadDataArray = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("Service Request/RO Service");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
downloadDataArray.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
UserDetails userDetails = postSnapshot.getValue(UserDetails.class);
downloadDataArray.add(userDetails);
}
adapter = new ImageAdapter(requestList.this, downloadDataArray);
getSupportActionBar().setTitle("Requests" + "(" +adapter.getItemCount()+ ")");
recyclerView.setAdapter(adapter);
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
Log.i("Position", String.valueOf(position));
}
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
//print log message
}
}
}
});
Because you are not assigning the value of mListener. Add this line after initialize adapter object.
adapter.setOnItemClickListener(this)

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.

Search bar using RecyclerView with Firebase(OnClick)

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.

Cardview with editText and Recyclerview

I'm not very good in android programming. I'm able to do this layout with cardview and recyclerview.
But I need to have a 2 listener for each card with editText. An OnFocusChange listener and a OnTextChange listener. And I have to get the text of each editText.
What have I to done?
This is my current code:
Object:
public class unitObject {
private String mtitle;
private String mhint;
unitObject(String title, String hint){
mtitle=title;
mhint=hint;
}
public String getMtitle() {
return mtitle;
}
public String getMhint() {
return mhint;
}
public void setMtitle(String mtitle) {
this.mtitle = mtitle;
}
public void setMhint(String mhint) {
this.mhint = mhint;
}
}
Recycler adapter:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<unitObject> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView title;
TextView ET_hint;
String content;
public DataObjectHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textView);
ET_hint = (TextView) itemView.findViewById(R.id.editText);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public MyRecyclerViewAdapter(ArrayList<unitObject> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_row, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.title.setText(mDataset.get(position).getMtitle());
holder.ET_hint.setHint(mDataset.get(position).getMhint());
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
The class
public class classic_conversion extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classic_conversion_layout);
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
}
private ArrayList<unitObject> getDataSet() {
ArrayList results = new ArrayList<unitObject>();
results.add(new unitObject("Title 1","hint 1"));
results.add(new unitObject("Title 2","hint 2"));
results.add(new unitObject("Title 3","hint 3"));
return results;
}
}
Thanks in advance!
For listener editText:
yourEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//BEFORE TEXT CHANGED
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// WHILE TEXT IS CHANGE
}
#Override
public void afterTextChanged(Editable editable) {
//AFTER TEXT CHANGED (LIKE YOU PRESS ENTER AFTER TYPING)
}
});
For listener focus change.
yourEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus){
//DO WHAT YOU NEED WHEN editText HAS FOCUS
}
else {
//DO WHAT YOU NEED WHEN editText HAS NO FOCUS
}
}
});
I really hope this helps you, and sorry for the late reply.

Categories

Resources