Cardview with editText and Recyclerview - android

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.

Related

Putting data from a subcollection in a second Layout with FirebaseUI

I want to open the data of a Firebase subcollection in a new RecyclerView. The Main Activity has a RecyclerView filled with the data from the first collection and a second activity should be opened through a click on one of the items.This second activity would have the second RecyclerView. My main Activity works fine and I can see all my data. But when I click on one of the items, my app crashes.
This is my MainActivity
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef = db.collection("Notebook");
private KisteAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton buttonAddKiste = findViewById(R.id.button_add_kiste);
buttonAddKiste.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, NewKisteActivity.class));
}
});
setUpRecyclerView();
}
private void setUpRecyclerView(){
Query query = notebookRef.orderBy("priority", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Kiste> options = new FirestoreRecyclerOptions.Builder<Kiste>()
.setQuery(query, Kiste.class)
.build();
adapter = new KisteAdapter(options);
final RecyclerView recyclerView = findViewById(R.id.recycler_view_kiste);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT |ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
adapter.deleteKiste(viewHolder.getAdapterPosition());
final DocumentReference docRef = adapter.getSnapshots().getSnapshot(viewHolder.getAdapterPosition()).getReference();
final Kiste kiste = adapter.getSnapshots().getSnapshot(viewHolder.getAdapterPosition()).toObject(Kiste.class);
Snackbar.make(recyclerView, "Item deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
docRef.set(kiste);
}
}).show();
}
#Override
public void onChildDraw(#NonNull Canvas c, #NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
.addBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent))
.addActionIcon(R.drawable.ic_delete_)
.create()
.decorate();
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}).attachToRecyclerView(recyclerView);
adapter.setOnKisteClickListen(new KisteAdapter.onItemClickListener() {
#Override
public void onKisteClick(DocumentSnapshot documentSnapshot, int position) {
final DocumentReference docRef = documentSnapshot.getReference();
final CollectionReference colRef = documentSnapshot.getReference().collection("A");
final Intent intent = new Intent(MainActivity.this,SecondaryActivity.class);
colRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (queryDocumentSnapshots.isEmpty()){
colRef.add(new Item("DFB","SGRDG",5));
/*intent.putExtra("Document Reference",docRef.getId());
intent.putExtra("Collection Reference",colRef.getId());*/
startActivity(intent);
}
else {
startActivity(intent);
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
this is the Class Kiste, which the first RecyclerView gets
public class Kiste {
private String title;
private int priority;
public Kiste(){
}
public Kiste(String title, int priority){
this.title= title;
this.priority = priority;
}
public String getTitle() {
return title;
}
public int getPriority() {
return priority;
}
}
And this is the adapter
public class KisteAdapter extends FirestoreRecyclerAdapter<Kiste, KisteAdapter.KisteHolder> {
private onItemClickListener listener;
public KisteAdapter(#NonNull FirestoreRecyclerOptions<Kiste> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull KisteHolder holder, int position, #NonNull Kiste model) {
holder.textViewTitle.setText(model.getTitle());
holder.textViewPriority.setText(String.valueOf(model.getPriority()));
}
#NonNull
#Override
public KisteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.kiste_item,parent,false);
return new KisteHolder(v);
}
public void deleteKiste(int position){
getSnapshots().getSnapshot(position).getReference().delete();
}
class KisteHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewPriority;
public KisteHolder(#NonNull View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.text_view_title);
textViewPriority = itemView.findViewById(R.id.text_view_priority);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener!= null){
listener.onKisteClick(getSnapshots().getSnapshot(position),position);
}
}
});
}
}
public interface onItemClickListener {
void onKisteClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnKisteClickListen (onItemClickListener listener) {this.listener = listener;}
}
Since that worked for me, I tried doing the same with the subcollection (As I was still testing if it would work, I just used one DocumentPath that I knew existed ) but as I said above the app keeps crashing.
Here is the secondActivity
public class SecondaryActivity extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference colRef = db.collection("Notebook").document(
"JGBzWBwCASivfAjuF8xE").collection("A");
private ItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondary);
FloatingActionButton buttonAddItem = findViewById(R.id.button_add_item);
setupRecyclerView();
}
private void setupRecyclerView(){
Query query2 = colRef.orderBy("priority", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Item> options = new FirestoreRecyclerOptions.Builder<Item>()
.setQuery(query2, Item.class)
.build();
adapter = new ItemAdapter(options);
final RecyclerView recyclerView = findViewById(R.id.recycler_view_item);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
the Class Item:
public class Item {
//private Bitmap imageItem;
private String itemName;
private String itemQuantity;
private int priority;
public Item(){
}
public Item( String itemName, String itemQuantity, int priority){
//this.imageItem = imageViewItem;
this.itemName = itemName;
this.itemQuantity = itemQuantity;
this.priority = priority;
}
/*public Bitmap getImageItem() {
return imageItem;
}*/
public String getItemName() {
return itemName;
}
public String getItemQuantity() {
return itemQuantity;
}
public int getPriority() {
return priority;
}
}
and the adapter :
public class ItemAdapter extends FirestoreRecyclerAdapter<Item, ItemAdapter.ItemHolder> {
public ItemAdapter(#NonNull FirestoreRecyclerOptions<Item> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ItemHolder holder, int position, #NonNull Item model) {
//holder.imageViewItem.setImageBitmap(model.getImageItem());
holder.textViewTitle.setText(model.getItemName());
holder.textViewQuantity.setText(model.getItemQuantity());
holder.textViewPriority.setText(String.valueOf(model.getPriority()));
}
#NonNull
#Override
public ItemHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_item,parent,false);
return new ItemHolder(v);
}
class ItemHolder extends RecyclerView.ViewHolder{
//ImageView imageViewItem;
TextView textViewTitle;
TextView textViewQuantity;
TextView textViewPriority;
public ItemHolder(#NonNull View itemView){
super(itemView);
//imageViewItem.findViewById(R.id.image_view_item);
textViewTitle.findViewById(R.id.text_view_item_name);
textViewQuantity.findViewById(R.id.text_view_item_quantity);
textViewPriority.findViewById(R.id.text_view_priority2);
}
}
}
I would really appreciate it if someone could help me figure out what the problem is.
Thanks for pointing out the error in the console, now it's much easier for us to see where the problem is without the need of reading your whole code :D
You're getting an error in line 47 of your ItemAdapter class. I can't see exactly which line it is, but I'm certain the error is inside your ViewHolder.
class ItemHolder extends RecyclerView.ViewHolder{
//ImageView imageViewItem;
TextView textViewTitle;
TextView textViewQuantity;
TextView textViewPriority;
public ItemHolder(#NonNull View itemView){
super(itemView);
//imageViewItem.findViewById(R.id.image_view_item);
THESE LINES OF CODE -----------------------------------------------------------------
textViewTitle.findViewById(R.id.text_view_item_name);
textViewQuantity.findViewById(R.id.text_view_item_quantity);
textViewPriority.findViewById(R.id.text_view_priority2);
-------------------------------------------------------------------------------------
}
}
replace them with:
this.textViewTitle = (TextView) itemView.findViewById(R.id.text_view_item_name); // and so on...
You can check out this example:
https://www.javatpoint.com/android-recyclerview-list-example

Problem with indexing in RecyclerView Adapter. How to do it in a good way?

I have some problems with RecyclerView Adapter. I want to do the list with id index: 1,2,3... When an item is removed it should set every next item position to position-1. Like this: (for example delete number 3)
1|2|3|4|5 -> 1|2|3|4
It works perfectly when:
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
But this causes other errors with notifyItemRemoved().
When I set:
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getItemViewType(int position) {
return 0;
}
It has problems with item order after scrolling, with repeatability of numbers etc.
I'm stuck.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private DatabaseHelper databaseHelper;
private EditText editText;
private Button showButton,saveButton;
private RecyclerView mainListRecyclerView;
private ArrayList<String>arrayList;
private MainListAdapter mainListAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
showButton = (Button) findViewById(R.id.showButton);
saveButton = (Button) findViewById(R.id.saveButton);
mainListRecyclerView = (RecyclerView) findViewById(R.id.listView);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>(20);
layoutManager = new LinearLayoutManager(this);
mainListRecyclerView.setLayoutManager(layoutManager);
mainListAdapter = new MainListAdapter(arrayList,this);
mainListAdapter.setHasStableIds(false);
mainListRecyclerView.setAdapter(mainListAdapter);
mainListAdapter.notifyDataSetChanged();
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinalListActivity.class);
intent.putExtra("productList",arrayList);
MainActivity.this.startActivity(intent);
}
});
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId==EditorInfo.IME_ACTION_DONE) {
addItem();
}
return true;
}
});
}
public void addData(String newItem){
boolean insertData = databaseHelper.addData(newItem);
if(insertData){
toastMessage("Item successfully inserted!");
}
else {
toastMessage("Something is wrong");
}
}
public void removeData(String itemToRemove){
boolean removeData = databaseHelper.removeData(itemToRemove);
if(removeData){
toastMessage("Item successfully deleted!");
}
else {
toastMessage("Something is wrong");
}
}
public void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
public void addItem(){
String newItem = editText.getText().toString();
if(newItem.length()!=0) {
addData(newItem);
arrayList.add(newItem);
editText.setText("");
editText.requestFocus();
mainListAdapter.notifyItemInserted(arrayList.size()-1);
}
else{
toastMessage("You must put something in the text field");
}
}
public void removeItem(int position){
if(mainListAdapter.getItemCount()!=0){
removeData(arrayList.get(position));
arrayList.remove(position);
mainListAdapter.notifyItemRemoved(position);
}
}
}
Adapter class
public class MainListAdapter extends
RecyclerView.Adapter<MainListAdapter.MyViewHolder> {
private ArrayList<String> mDataset;
private MainActivity mainActivity;
public MainListAdapter(ArrayList<String> mDataset, MainActivity
mainActivity) {
this.mDataset = mDataset;
this.mainActivity = mainActivity;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getItemCount() {
return mDataset.size();
}
#Override
public void onBindViewHolder(final MyViewHolder holder,final int position) {
holder.listTextView1.setText(holder.getAdapterPosition()+"");
holder.listTextView2.setText(mDataset.get(position));
holder.listButtonViewDel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int currentPosition = holder.getAdapterPosition();
if(currentPosition!=-1)
mainActivity.removeItem(currentPosition);
}
});
}
public class MyViewHolder extends RecyclerView.ViewHolder {
final public TextView listTextView1;
final public TextView listTextView2;
final public Button listButtonViewDel;
public MyViewHolder(View view) {
super(view);
listTextView1 = (TextView) view.findViewById(R.id.listTextView1);
listTextView2 = (TextView) view.findViewById(R.id.listTextView2);
listButtonViewDel = (Button) view.findViewById(R.id.listButtonViewDel);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_list_layout, parent, false);
return new MyViewHolder(view);
}
}
Add this lines To removeItem function in MainActivity.java
public void removeItem(int position){
if(mainListAdapter.getItemCount()!=0){
removeData(arrayList.get(position));
arrayList.remove(position);
mainListAdapter.notifyItemRemoved(position);
arrayList.remove(position); // add this line
mainListAdapter.update(arrayList); // add this line
}
}
And add update function to your MainListAdapter.java like this
public void update(ArrayList<String> mDataset){
this.mDataset = mDataset
notifyDataSetChanged();
}
For show animation try this function (I suggest you to set all function about adapter in adapter)
public void update(ArrayList<String> mDataset,int position){
this.mDataset = mDataset
notifyItemRangeChanged(position,mDataset.size);
}
In your removeItem() method,
You have mainListAdapter.notifyItemRemoved(position); and it will only inform the item is removed.
You need to put a line inside this method at end as mainListAdapter.notifyDataSetChanged().
It reminds adapter to reset the list on every change.
you can set null to mainListRecyclerVie wadapter and bind again when remove items !
mainListRecyclerVie.setAdapter(null);
and bind again

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 to set onClick in the RecyclerView?

I have created a RecyclerView Adapter but now i'm struggling to do the onClick to open new activity.
This is my RecyclerView Adapter class:
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {
private ArrayList<HashMap<String, String>> mDataset;
Context ctx;
public RecycleAdapter(ArrayList<HashMap<String, String>> mDataset) {
this.mDataset = mDataset;
this.ctx = ctx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_procedure, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.getId().setText(mDataset.get(position).get("id"));
holder.getItemname().setText(mDataset.get(position).get("name"));
//holder.getIvImage().setBackground(mDataset.get(position).get("icon"));
}
#Override
public int getItemCount() {
return mDataset.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private CardView cardView;
private TextView itemId;
private TextView tvName;
private ImageView ivImage;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemId = itemView.findViewById(R.id.tvProfileItemName);
tvName = itemView.findViewById(R.id.tvProfileItemAge);
ivImage = itemView.findViewById(R.id.imageView3);
}
public TextView getId() {
return itemId;
}
public TextView getItemname() {
return tvName;
}
public ImageView getIvImage() {
return ivImage;
}
#Override
public void onClick(View v) {
}
}
}
My Main Activity just display the data inside of a recycler view
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
R.layout.list_item, new String[]{"id", "name", "icon"},
new int[]{R.id.id, R.id.name, R.id.icon});
mAdapter = new RecycleAdapter(contactList);
mRecyclerView.setAdapter(mAdapter);
}
use interface
in recycler view adapter class
public interface recClick{
void onClickRec(int p);
}
private recClick rc;
public void setRecClick(recClick rc){
this.rc = rc
}
in recycler view holder class
#Override
public void onClick(View v) {
rc.onClickRec(getAdapterPosition());
}
in MainActivity use Interface
class MainActivity implements AdapterClass.recClick{
mAdapter.setRecClick(this);
#Override
public onClickRec(int p)
{
// do someting
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final int pos =position;
holder.getId().setText(mDataset.get(position).get("id"));
holder.getItemname().setText(mDataset.get(position).get("name"));
//holder.getIvImage().setBackground(mDataset.get(position).get("icon"));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,NewActivity.class);
intent.putExtra("yourValue", String.valueOf(mDataset.get(position).get(pos)));
ctx.startActivity(intent);
}
});
}
Remember to give reference to your cardview
cardView = (CardView)itemView.findViewById(R.id.cardview);

Cardview click event is not working on android?

I show list of data in card view successfully but now i want to open another activity and show details of clicked data.
I have three class MainActivity, ContactAdapter, Contact.
Main Activity Code:
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
String[] name,email;
ArrayList<Contact> list = new ArrayList<Contact>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = getResources().getStringArray(R.array.person_name);
email = getResources().getStringArray(R.array.person_email);
int count = 0;
for (String Name : name)
{
Contact contact = new Contact(Name,email[count]);
count++;
list.add(contact);
}
recyclerView= (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter=new ContactAdapter(list);
recyclerView.setAdapter(adapter);
i tried but it's not working.
Adapter Code:
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
ArrayList<Contact> contacts = new ArrayList<Contact>();
public ContactAdapter(ArrayList<Contact> contacts) {
this.contacts = contacts;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_layout, parent, false);
ContactViewHolder contactViewHolder = new ContactViewHolder(view);
return contactViewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
Contact CON = contacts.get(position);
holder.person_name.setText(CON.getName());
holder.person_email.setText(CON.getEmail());
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
TextView person_name, person_email;
public ContactViewHolder(View view) {
super(view);
person_name = (TextView) view.findViewById(R.id.person_name);
person_email = (TextView) view.findViewById(R.id.person_email);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "OnClick Version :",
Toast.LENGTH_SHORT).show();
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(v.getContext(), "OnLongClick Version :",
Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
}
In your adapter do this:
public class ProdutoAdapter extends RecyclerView.Adapter<ProdutoAdapter.ProdutoViewHolder>{
private static ProdutoAdapter.ClickListener clickListener; //this is important
private List<Produto> produtos; //this is my list of beans
public ProdutoAdapter(List<Produto> produtos) {
this.produtos = produtos;
}
#Override
public ProdutoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_produtos, parent, false);
ProdutoViewHolder mvh = new ProdutoViewHolder(v);
return mvh;
}
#Override
public void onBindViewHolder(ProdutoViewHolder holder, int position) {
//holder.nome.setText(this.produtos.get(position).getNome());
holder.img.setImageDrawable(produtos.get(position).getImgDrawable());
holder.nome.setText(produtos.get(position).getNome());
holder.preco.setText(String.valueOf(produtos.get(position).getPreco()));
}
#Override
public int getItemCount() {
return this.produtos.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class ProdutoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
Produto produto;
CardView cardView;
TextView nome;
TextView preco;
ImageView img;
ProdutoViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
cardView = (CardView) itemView.findViewById(R.id.cardviewProduto);
nome = (TextView) itemView.findViewById(R.id.nome);
preco = (TextView) itemView.findViewById(R.id.preco);
img = (ImageView) itemView.findViewById(R.id.foto);
}
public void setItem(Produto produto){
this.produto = produto;
}
public Produto getItem(){
return this.produto;
}
//this is what you'll need in your activity
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
#Override
public boolean onLongClick(View v) {
clickListener.onItemLongClick(getAdapterPosition(), v);
return false;
}
}
public void setOnItemClickListener(ClickListener clickListener){
ProdutoAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
void onItemLongClick(int position, View v);
}
}
and in your activity:
public static ProdutoAdapter mAdapter;
myActivity.mAdapter.setOnItemClickListener(new ProdutoAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
//do what you want
}
#Override
public void onItemLongClick(int position, View v) {
}
});
myActivity.mRecyclerView.setAdapter(mAdapter);

Categories

Resources