Twice data in RecyclerView - java

How can i fix twice data error.
After scrolling inside the RecyclerView, I am having a issue which is twice data.
Here is my Activity:
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<Contacts>> call = apiInterface.chat(getUserLogin,friendId);
call.enqueue(new Callback<List<Contacts>>() {
#Override
public void onResponse(Call<List<Contacts>> call, Response<List<Contacts>> response) {
contacts = response.body();
CustomAdapterOfChat adapter = new CustomAdapterOfChat(contacts, ChatActivity.this);
recyclerView.setAdapter(adapter);
size = String.valueOf(contacts.size());
}
#Override
public void onFailure(Call<List<Contacts>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Error\n"+t.toString(), Toast.LENGTH_LONG).show();
}
});
My customAdapter ViewHolder
public class CustomAdapterOfChat extends RecyclerView.Adapter<CustomAdapterOfChat.MyViewHolder> {
private List<Contacts> contacts;
private Context context;
String getUserLogin;
public CustomAdapterOfChat(List<Contacts> contacts, Context context) {
this.contacts = contacts;
this.context = context;
}
#Override
public CustomAdapterOfChat.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_of_chat, parent, false);
return new CustomAdapterOfChat.MyViewHolder(view);
}
#Override
public void onBindViewHolder(CustomAdapterOfChat.MyViewHolder holder, final int position) {
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =context.getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");
Log.d("USER_ID",getUserLogin);
Log.d("FRIEND_ID",contacts.get(position).getFriendId());
holder.time.setText(contacts.get(position).getDateAndTime());
if(getUserLogin.equals(contacts.get(position).getFriendId())) {
holder.msg_of_me.setVisibility(View.INVISIBLE);
holder.msg_of_them.setText(contacts.get(position).getMessage());
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra("id",contacts.get(position).getFriendId());
context.startActivity(intent);
}
});
Glide.with(context)
.load(Constant.BASE_URL+"y_chat/sign_up/"+contacts.get(position).getFriendName()+"/profile.png")
.error(R.drawable.error)
.into(holder.img);
}else{
holder.img.setVisibility(View.INVISIBLE);
holder.msg_of_them.setVisibility(View.INVISIBLE);
holder.msg_of_me.setText(contacts.get(position).getMessage());
}
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView msg_of_me,msg_of_them,time;
ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
msg_of_me = itemView.findViewById(R.id.message_text1);
msg_of_them = itemView.findViewById(R.id.message_text);
img = itemView.findViewById(R.id.img_of_them);
time = itemView.findViewById(R.id.message_time);
}
}
}

You are getting data from SharedPreferences which is time consuming task however you can edit your code this way and check the output.
public class CustomAdapterOfChat extends RecyclerView.Adapter {
private List<Contacts> contacts;
private Context context;
String getUserLogin;
public CustomAdapterOfChat(List<Contacts> contacts, Context context) {
this.contacts = contacts;
this.context = context;
//get user Id here.
SharedPreferences sharedPreferences;
sharedPreferences =context.getSharedPreferences(Constant.SHARED_PREF_NAME,
Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");
}
#Override
public CustomAdapterOfChat.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_of_chat, parent, false);
return new CustomAdapterOfChat.MyViewHolder(view);
}
#Override
public void onBindViewHolder(CustomAdapterOfChat.MyViewHolder holder, final int position) {
Log.d("USER_ID",getUserLogin);
Log.d("FRIEND_ID",contacts.get(position).getFriendId());
holder.time.setText(contacts.get(position).getDateAndTime());
if(getUserLogin.equals(contacts.get(position).getFriendId())) {
holder.msg_of_me.setVisibility(View.INVISIBLE);
holder.msg_of_them.setText(contacts.get(position).getMessage());
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra("id",contacts.get(position).getFriendId());
context.startActivity(intent);
}
});
Glide.with(context)
.load(Constant.BASE_URL+"y_chat/sign_up/"+contacts.get(position).getFriendName()+"/profile.png")
.error(R.drawable.error)
.into(holder.img);
}else{
holder.img.setVisibility(View.INVISIBLE);
holder.msg_of_them.setVisibility(View.INVISIBLE);
holder.msg_of_me.setText(contacts.get(position).getMessage());
}
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView msg_of_me,msg_of_them,time;
ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
msg_of_me = itemView.findViewById(R.id.message_text1);
msg_of_them = itemView.findViewById(R.id.message_text);
img = itemView.findViewById(R.id.img_of_them);
time = itemView.findViewById(R.id.message_time);
}
}

Related

How to block particular Position in Adapter class ANDROID JAVA

I have an adapter class Where i Want to show a BLOCK USER dialog on particular position.
for example if i want to block position 1 of recyclerView .
So can any one help me porgrammatically?
Given below is the Code Of adapter Please check
I want to block user profile based on Recycler View position
if someone could help me in it please;
public class TableProfileAdapter extends RecyclerView.Adapter<TableProfileAdapter.MyViewHolder> {
Context context;
Activity getActivity;
List<TableProfile> profileUser;
OnRecItemClick onRecItemClick;
private boolean isScaleAnimationDone = false;
private boolean isTimerTextViewActionUpCalled = false;
public TableProfileAdapter(List<TableProfile> profileUser, Context context) {
this.profileUser = profileUser;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.profile_item, parent, false);
return new MyViewHolder(view, onRecItemClick);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
TableProfile data = profileUser.get(position);
holder.tvUserName.setText(data.getProfileName());
Bitmap image = BitmapManager.byteToBitmap(data.getProfileImage());
holder.profilePic.setImageBitmap(image);
if (context instanceof AccessProfileManagementActivity) {
context.startActivity(new Intent(context,HomeActivity.class));
} else if (context instanceof ProfileManagement) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProfileDetailsActivity.class);
TableProfile model = profileUser.get(holder.getAdapterPosition());
intent.putExtra("DATA", model);
context.startActivity(intent);
notifyDataSetChanged();
((Activity) context).finish();
}
});
}
}
#Override
public int getItemCount() {
return profileUser.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircleImageView profilePic;
TextView tvUserName, birthday;
OnRecItemClick onRecItemClick;
RelativeLayout relativeLayout;
public MyViewHolder(#NonNull View itemView, OnRecItemClick onRecItemClick) {
super(itemView);
profilePic = itemView.findViewById(R.id.profileImage);
tvUserName = itemView.findViewById(R.id.userName);
relativeLayout = itemView.findViewById(R.id.relTop);
this.onRecItemClick = onRecItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onRecItemClick.onItemClick(getAdapterPosition());
}
}
public interface OnRecItemClick {
void onItemClick(int position);
}
}

How to open a new activity from the adapter?

It turns out the code has the following form:
#Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, int position) {
final Phone phone = phones.get(position);
holder.imageView.setImageResource(phone.getImage());
holder.nameView.setText(phone.getName());
holder.companyView.setText(phone.getCompany());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("click: ", phone.getClickbutton());
startActivity(new Intent(this, Information.class));
}
});
}
Respectively:
startActivity(new Intent(this, Information.class));
She doesn’t want to work here.
I give the full adapter code:
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private LayoutInflater inflater;
private List<Phone> phones;
public DataAdapter(Context context, List<Phone> phones) {
this.phones = phones;
this.inflater = LayoutInflater.from(context);
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, int position) {
final Phone phone = phones.get(position);
holder.imageView.setImageResource(phone.getImage());
holder.nameView.setText(phone.getName());
holder.companyView.setText(phone.getCompany());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("click: ", phone.getClickbutton());
startActivity(new Intent(this, Information.class));
}
});
}
#Override
public int getItemCount() {
return phones.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final ImageView imageView;
final TextView nameView, companyView;
final Button button;
ViewHolder(View view){
super(view);
imageView = (ImageView)view.findViewById(R.id.image);
nameView = (TextView) view.findViewById(R.id.name);
companyView = (TextView) view.findViewById(R.id.company);
button = (Button) view.findViewById(R.id.button);
}
}
}
List item
That is the actual question. How can I open a new activity from the adapter ... Thank you.
Don't dispose passed context to your adapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private LayoutInflater inflater;
private List<Phone> phones;
private Context context;
public DataAdapter(Context context, List<Phone> phones) {
this.context = context;
this.phones = phones;
this.inflater = LayoutInflater.from(context);
}
// Remainder code
}
Then use context to start new activity
#Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, int position) {
final Phone phone = phones.get(position);
holder.imageView.setImageResource(phone.getImage());
holder.nameView.setText(phone.getName());
holder.companyView.setText(phone.getCompany());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("click: ", phone.getClickbutton());
context.startActivity(new Intent(this, Information.class));
}
});
}

How can i pass a string value from recyclerview adapter to fragment

I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.

Clicked item updates other items in the recyclerview?

I have a recycler view which contains a checkbox on click of the check
box I update the value for quantity.The problem is if I select the
first checkbox in my recycler view for some instances even the 5th
check box gets auto checked.
Following is my code for onActivityResult where I call updateBooks which is responsible for handling the click event.
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mAdapter.notifyDataSetChanged();
search_info.clear();
book_type.clear();
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
getBookData(data);
if (books_list.size() > 0) {
books_list.clear();
mAdapter.swap(prepareData());
mAdapter.notifyDataSetChanged();
}
updateBooks(recyclerView);
mAdapter.notifyDataSetChanged();
}
}
}
Following is the code for updateBooks.
private void updateBooks(RecyclerView recyclerView) {
mAdapter = new DataAdapter(getApplicationContext(), prepareData(), recyclerView, qty, new DataAdapter.OnItemCheckListener() {
#Override
public void onItemCheck(BooksInfo item, DataAdapter.ViewHolder viewHolder) {
if (qty.equals("") || qty.equals(null)) {
viewHolder.tv_qty.setText("0");
} else {
viewHolder.tv_qty.setText(qty);
}
}
#Override
public void onItemUncheck(BooksInfo item, DataAdapter.ViewHolder viewHolder) {
viewHolder.tv_qty.setText("0");
}
});
recyclerView.setAdapter(mAdapter);
}
And this is my Adapter code.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<BooksInfo> books;
private Context ctx;
private String qty;
private RecyclerView recyclerView;
public DataAdapter()
{
}
#NonNull
public OnItemCheckListener onItemCheckListener;
public DataAdapter(Context context, ArrayList<BooksInfo> books, RecyclerView recyclerView,String qty, OnItemCheckListener onItemCheckListener) {
this.books = books;
this.ctx = context;
this.qty = qty;
this.onItemCheckListener =onItemCheckListener;
this.recyclerView = recyclerView;
}
public interface OnItemCheckListener {
void onItemCheck(BooksInfo item,ViewHolder viewHolder);
void onItemUncheck(BooksInfo item,ViewHolder viewHolder);
}
public void swap(ArrayList<BooksInfo> datas){
datas = new ArrayList<>();
recyclerView.removeAllViews();
books.clear();
books.addAll(datas);
notifyDataSetChanged();
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final DataAdapter.ViewHolder viewHolder, int i) {
final BooksInfo booksInfo = (BooksInfo) books.get(i);
viewHolder.tv_title.setText(booksInfo.getTitle());
viewHolder.tv_price.setText(booksInfo.getPrice());
viewHolder.tv_vol_no.setText(booksInfo.getVol_no());
viewHolder.tv_status.setText(booksInfo.getStatus());
viewHolder.tv_isbn.setText(booksInfo.getISBN());
viewHolder.tv_book_id.setText(booksInfo.getBook_id());
viewHolder.tv_brand.setText(booksInfo.getBrand());
viewHolder.tv_sku.setText(booksInfo.getSku());
viewHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.cb_selection.setChecked(!(viewHolder.cb_selection.isChecked()));
if (viewHolder.cb_selection.isChecked()){
onItemCheckListener.onItemCheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText(qty);
}else{
onItemCheckListener.onItemUncheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText("0");
}
}
});
}
public void updateNotes(ArrayList notesList) {
books = notesList;
}
public void updateQty(String q)
{
qty =q;
}
#Override
public int getItemCount() {
return books.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView tv_title,tv_price,tv_vol_no,tv_status,tv_isbn,tv_book_id,tv_brand,tv_sku,tv_qty;
public CheckBox cb_selection;
View itemView;
public ViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
tv_title = (TextView)itemView.findViewById(R.id.tv_title);
tv_price = (TextView) itemView.findViewById(R.id.tv_price);
tv_vol_no = (TextView) itemView.findViewById(R.id.tv_volno);
tv_status = (TextView) itemView.findViewById(R.id.tv_status);
tv_isbn = (TextView) itemView.findViewById(R.id.tv_isbn);
tv_book_id = (TextView) itemView.findViewById(R.id.tv_bookid);
tv_brand = (TextView) itemView.findViewById(R.id.tv_brand);
cb_selection = (CheckBox) itemView.findViewById(R.id.cb_selection);
cb_selection.setClickable(false);
tv_sku = (TextView) itemView.findViewById(R.id.tv_sku);
tv_qty = (TextView) itemView.findViewById(R.id.tv_qty);
}
public void setOnClickListener(View.OnClickListener onClickListener) {
itemView.setOnClickListener(onClickListener);
}
}
}
Views in RecyclerView are reusable and you must store checked state outside the view. Add boolean field to your BookInfo class like public boolean isCkecked. And change some code inside onBindViewHolder:
viewHolder.cb_selection.setChecked(booksInfo.isChecked);
viewHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
booksInfo.isChecked = !booksInfo.isChecked;
viewHolder.cb_selection.setChecked(booksInfo.isChecked);
if (booksInfo.isChecked){
onItemCheckListener.onItemCheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText(qty);
}else{
onItemCheckListener.onItemUncheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText("0");
}
}
});

onClickListener in RecyclerView.ViewHolder

I've got a RecyclerView.ViewHolder and RecyclerView.Adapter, I need after click on item and then send information about this item to another Activity.
PlacesAdapter.java
public class PlacesAdapter extends RecyclerView.Adapter<PlacesViewHolder> {
private PlacesActivity placesActivity;
Context context;
private int position;
List<Places> places;
public PlacesAdapter(List<Places> places) {
this.places = places;}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PlacesViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.places_view, viewGroup, false);
PlacesViewHolder pvh = new PlacesViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PlacesViewHolder personViewHolder, int i) {
personViewHolder.name.setText(places.get(i).name);
personViewHolder.address.setText(places.get(i).address);
Picasso.with(personViewHolder.itemView.getContext())
.load(places.get(i).photo)
.into(personViewHolder.getPhoto());
}
#Override
public int getItemCount() {
return places.size();
}
}
PlacesViewHolder.java
In this line "intent.putExtra(PlacesDetail.PLACES_NAME,);" How can I send name?
public class PlacesViewHolder extends RecyclerView.ViewHolder {
CardView cv;
public TextView name;
public TextView address;
public ImageView photo;
public PlacesViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
name = (TextView)itemView.findViewById(R.id.person_name);
address = (TextView)itemView.findViewById(R.id.person_age);
photo = (ImageView)itemView.findViewById(R.id.person_photo);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, PlacesDetail.class);
intent.putExtra(PlacesDetail.PLACES_NAME,);
context.startActivity(intent);
}
});
}
public TextView getAddress() {
return address;
}
public TextView getName() {
return name;
}
public ImageView getPhoto() {
return photo;
}
}
This is the complete example of custom Adapter where i'm able to get the details of particular items. In MainActivity you need to set the adapter :
adapter = new MyAdapter(getApplicationContext(), account_no, title, aFN1, aLN1,aFN2, aLN2,aFN3, aLN3,isavilable,waitlist,flag);
adapter.notifyDataSetChanged();
mRecyclerView.setAdapter(adapter);
Now see the code for the custom Adapter :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
String TAG = "MyAdapter";
Context context;
private String[] accountNo;
private String[] title;
private String[] afn1;
private String[] aln1;
private String[] afn2;
private String[] aln2;
private String[] afn3;
private String[] aln3;
private String[] isAvailable;
private String[] waitlist;
private int flag;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView account_no,title,afn1,afn2,aln1,aln2,color,is_available;
private ImageView img_android;
CardView cardView;
public ViewHolder(CardView v) {
super(v);
account_no = (TextView)v.findViewById(R.id.acctno);
title = (TextView)v.findViewById(R.id.title);
afn1 = (TextView) v.findViewById(R.id.afn1);
cardView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(Context context, String[] accountNo,String[] title,String[] afn1,String[] aln1,String[] afn2,String[] aln2,String[] afn3,String[] aln3,String[] isAvailable, String[] waitlist,int flag) {
this.context = context;
this.accountNo = accountNo;
this.title = title;
this.afn1 = afn1;
this.aln1 = aln1;
this.afn2 = afn2;
this.aln2 = aln2;
this.afn3 = afn3;
this.aln3 = aln3;
this.isAvailable = isAvailable;
this.waitlist = waitlist;
this.flag = flag;
Log.d(TAG,afn1.toString() +aln1+afn2+aln2+afn3+aln3.toString()+waitlist);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(cv);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final CardView cardView = holder.cardView;
final TextView accountno = (TextView)cardView.findViewById(R.id.acctno);
accountno.setText(accountNo[position]);
final TextView titletxt = (TextView)cardView.findViewById(R.id.title);
titletxt.setText(title[position]);
final TextView afn1txt = (TextView) cardView.findViewById(R.id.afn1);
afn1txt.setText(afn1[position]+" "+aln1[position]);
Log.d(TAG,waitlist[position]);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = getItemViewType(position);
SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.MYPREFERENCE,Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(Constant.ACCOUNT,accountNo[position]);
edit.putString(Constant.TITLE,title[position]);
edit.putString(Constant.AFN1,afn1[position]);
edit.putString(Constant.ALN1,aln1[position]);
edit.putString(Constant.AFN2,afn2[position]);
edit.putString(Constant.ALN2,aln2[position]);
edit.putString(Constant.AFN3,afn3[position]);
edit.putString(Constant.ALN3,aln3[position]);
edit.putBoolean(Constant.IS_AVAILABLE, Boolean.parseBoolean(isAvailable[position].toUpperCase()));
edit.putString(Constant.WAITLIST,waitlist[position]);
Log.d("WaitingNo2 :",""+String.valueOf(waitlist[position]));
edit.commit();
Intent intent = new Intent(v.getContext(), DetailsActivity.class);
v.getContext().startActivity(intent);
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return accountNo.length;
}
}
After All that get the value from sharedPreferences in the Activity which is called on Card Click:
preferences = getSharedPreferences("myshared", Context.MODE_PRIVATE);
AccountNo = sharedPreferences.getString(Constant.ACCOUNT,null).toUpperCase();
title = sharedPreferences.getString(Constant.TITLE,null).toUpperCase();
afn1 = sharedPreferences.getString(Constant.AFN1,null).toUpperCase();
aln1 = sharedPreferences.getString(Constant.ALN1,null).toUpperCase();
afn2 = sharedPreferences.getString(Constant.AFN2,null).toUpperCase();
aln2 = sharedPreferences.getString(Constant.ALN2,null).toUpperCase();
afn3 = sharedPreferences.getString(Constant.AFN3,null).toUpperCase();
aln3 = sharedPreferences.getString(Constant.ALN3,null).toUpperCase();
isAvailable = sharedPreferences.getBoolean(Constant.IS_AVAILABLE,isAvailable);
waitlist = sharedPreferences.getString(Constant.WAITLIST,waitlist);
Now do whatever you want and enjoy the code.
You can achieve this by creating an interface inside your adapter for an itemclicklistener and then you can set onItemClickListener from your PlacesActivity.
Somewhere inside your PlacesAdapter you would need the following:
private onRecyclerViewItemClickListener mItemClickListener;
public void setOnItemClickListener(onRecyclerViewItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public interface onRecyclerViewItemClickListener {
void onItemClickListener(View view, int position, String places_name);
}
Then inside your ViewHolder (which I've added as an inner class inside my adapter), you would apply the listener to the components you'd like the user to click, like so:
class PlacesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
PlacesViewHolder(View view) {
super(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClickListener(v, getAdapterPosition(), PlacesDetail.PLACES_NAME);
}
}
}
This example shows an onClickListener being applied to the view inside PlacesViewHolder.
recyclerView.setAdapter(adapter);// set adapter on recyclerview
adapter.notifyDataSetChanged();// Notify the adapter
adapter.setOnItemClickListener(new PlacesAdapter.onRecyclerViewItemClickListener() {
#Override
public void onItemClickListener(View view, int position, String places_name) {
//perform click logic here (places_name is passed)
}
});
To implement this code, you would setOnItemClickListener to your adapter inside PlacesActivity as shown above.
try this , it's work with me correctly
Create a new class and this code
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}
And in your Activity add this to your adapter implementation
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// do something
}
}
}
#Override
public void onLongItemClick(View view, int position) {
// do whatever
}
})
);

Categories