How to pass id instead of position using recyclerView in android - java

I have pass position in recyclerView click but some kind of problem pass to position to display wrong data so how can i pass people id in recyclerView.
I m new in android programming
recyclerView Item Click
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
buildCustomAdapter = new BuildCustomAdapter(this, peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
buildCustomAdapter.notifyDataSetChanged();
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(buildCustomAdapter);
buildCustomAdapter.setOnItemClickListener(new BuildCustomAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
detailPeople(position);
}
});
private void detailPeople(int position) {
Intent intent = new Intent(this, AddDetail.class);
intent.putExtra("peopleID", position);
startActivity(intent);
}
Model.class
public class People implements Serializable {
private String peopleImage;
private String peopleName;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getPeopleName() {
return peopleName;
}
public void setPeopleImage(String peopleImage) {
this.peopleImage = peopleImage;
}
public String getPeopleImage() {
return peopleImage;
}
}
Adapter code
public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;
private ItemFilter mFilter = new ItemFilter();
private OnItemClickListener mOnItemClickListener;
private Context mContext;
public BuildCustomAdapter(Context context, List<People> buildList) {
mContext = context;
this.peopleList = buildList;
this.peopleListCopy = new ArrayList<>();
peopleListCopy.addAll(buildList);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.build_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
People people = peopleList.get(position);
byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivPeopleImage.setImageBitmap(decodedByte);
holder.tvPersonName.setText(people.getPeopleName());
holder.button.setSelected(people.getStatus() == 1);
holder.button.setOnClickListener(new onSelectListener(position));
}
#Override
public int getItemCount() {
return peopleList.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView tvPersonName;
public Button button;
public CircularImageView ivPeopleImage;
public MyViewHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
button = (Button) itemView.findViewById(R.id.addbn);
tvPersonName.setOnClickListener(this);
ivPeopleImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(v, getPosition());
}
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
private class ItemFilter extends Filter {
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<People> filterList = new ArrayList<>();
for (int i = 0; i < peopleListCopy.size(); i++) {
if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
People peopleName = peopleListCopy.get(i);
filterList.add(peopleName);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = peopleListCopy.size();
results.values = peopleListCopy;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
peopleList = (List<People>) results.values;
notifyDataSetChanged();
}
}
private class onSelectListener implements View.OnClickListener {
int mPosition;
public onSelectListener(int position) {
mPosition = position;
}
#Override
public void onClick(View view) {
People people = peopleList.get(mPosition);
view.setSelected(!view.isSelected());
people.setStatus(view.isSelected() ? 1 : 0);
notifyDataSetChanged();
}
}
}
Next Activity to get intent
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
int peopleID = bundle.getInt("peopleID");
peopleList.clear();
BuildDataa();
People peopleDetailsObj = peopleList.get(peopleID);
}

Please replace
#Override
public void onClick(View v) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(v, getPosition());
}
to
#Override
public void onClick(View v) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(v, peopleList.get(getPosition()).getId());
}
in your adapter. And change signature of method onItemClick from
onItemClick(View v, int position)
to
onItemClick(View v, String id)
and use this to get People according to ID
People peopleDetailsObj=null;
for(People ple:peopleList)
{
if(ple.getId().equals(peopleID)){
peopleDetailsObj=ple;
break;
}}

Take the id from position.
String id=peopleList.get(position).getId();
detailPeople(id);
Pass that id in your method and you are done.

Use position to get People object from ArrayList. Change detailPeople() method with below code.
private void detailPeople(int position) {
Intent intent = new Intent(this, AddDetail.class);
intent.putExtra("peopleID", peopleList.get(position).getId());
startActivity(intent);
}

intent.putExtra("id", peopleList.get(position).getId());

Related

Adapter of RecyclerView doesn't update data after changing the array

I have an abstract class "ListItem" with two subclasses - "Header"(Data) and "Event". Depending on the situation, the array should be displayed either as "Header" - "Events of this data", or just events.
The created object of the "Event" class is passed to the main fragment from a separate activity. If I only need to display events, I just write it to an array and update the adapter data, it works. If, after creating a class object, I need to display it and existing events in the form "Header" - "Events", then the adapter for some reason is not updated and the new event is not displayed. If you close the application and reopen it, the event appears in its normal form with a header.
Here's my RV Adapter
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final String TAG = "myLogs";
private ArrayList<ListItem> list;
final SparseBooleanArray selectedItems = new SparseBooleanArray();
private int currentSelectedPos;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM", myDateFormatSymbols);
public EventAdapter(ArrayList<ListItem> items){
list = items;
}
public ArrayList<ListItem> getItems(){
return list;
}
private EventAdapterListener itemClickListener;
public interface EventAdapterListener {
void onItemClick(int position);
void onItemLongClick(int position);
}
public void setListener(EventAdapterListener listener){
itemClickListener = listener;
}
private OnItemCheckedListener OnItemChecked;
public interface OnItemCheckedListener {
void onItemChecked(int position, boolean isImportant);
}
public void setOnItemCheckedListener (OnItemCheckedListener listener){
OnItemChecked = listener;
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public TextView TVtitle;
public TextView TVcomment;
public CheckBox CBimportance;
public TextView TVdate;
//public EventViewHolder(#NonNull View itemView, final EventAdapterListener listener) {
public EventViewHolder(#NonNull View itemView) {
super(itemView);
}
}
public void removeAllObjectsOf(Class<? extends ListItem> cls) {
Iterator itr = list.iterator();
while (itr.hasNext()) {
if (itr.next().getClass().equals(cls)) {
itr.remove();
}
}
notifyDataSetChanged();
}
Comparator<ListItem> dateComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).Date.compareTo(((Event)t1).Date);
}
};
Comparator<ListItem> importanceComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).IsImportant.compareTo(((Event)t1).IsImportant);
}
};
Comparator<ListItem> nameComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).Name.compareTo(((Event)t1).Name);
}
};
Comparator<ListItem> completenessComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).IsComplete.compareTo(((Event)t1).IsComplete);
}
};
public void sortBy(Comparator<ListItem> comparator, ArrayList<ListItem> list) {
removeAllObjectsOf(Header.class);
Collections.sort(list, comparator);
}
public void groupByDate()
{
ArrayList<ListItem> result = new ArrayList<>();
removeAllObjectsOf(Header.class);
sortBy(dateComparator, list);
ArrayList<Long> dates = new ArrayList<>();
for (ListItem event: list)
{
if (!(dates.contains(((Event)event).getDate())))
{
dates.add(((Event)event).getDate());
ArrayList<ListItem> ei = getItemsbyDate(list, ((Event)event).getDate());
Header header = new Header();
header.setHeader(String.valueOf(((Event)event).getDate()));
result.add(header);
result.addAll(ei);
}
}
list = result;
notifyDataSetChanged();
}
public ArrayList<ListItem> getItemsbyDate(ArrayList<ListItem> items, Long date){
ArrayList<ListItem> result = new ArrayList<>();
for (ListItem ci : items){
if (((Event)ci).getDate().equals(date)){
result.add(ci);
}
}
return result;
}
public void removeItem(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,list.size());
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return list.get(position) instanceof Header;
}
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
#Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
if (viewType == TYPE_HEADER){
View v = inflater.inflate(R.layout.group_layout, parent, false);
return new VHHeader(v);
} else {
View v = inflater.inflate(R.layout.list_item_cardview, parent, false);
return new VHItem(v);
}
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, final int position)
{
if (holder instanceof VHHeader){
Header currentItem = (Header) list.get(position);
VHHeader VHheader = (VHHeader) holder;
VHheader.txtTitle.setText(simpleDateFormat.format(Long.parseLong(currentItem.getHeader())));
} else if (holder instanceof VHItem) {
final Event event = (Event) list.get(position);
VHItem VHitem = (VHItem) holder;
VHitem.txtName.setText(event.getName());
VHitem.txtDate.setText(simpleDateFormat.format(event.getDate()));
VHitem.TVcomment.setText(event.getComment());
VHitem.CBimportance.setOnCheckedChangeListener(null);
VHitem.CBimportance.setChecked(event.getImportant());
VHitem.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
event.IsImportant = b;
OnItemChecked.onItemChecked(position, b);
}
});
VHitem.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectedItems.size() > 0 && itemClickListener != null){
itemClickListener.onItemClick(position);
}
}
});
VHitem.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (itemClickListener != null){
itemClickListener.onItemLongClick(position);
}
return true;
}
});
if (currentSelectedPos == position) currentSelectedPos = -1;
}
}
#Override
public int getItemCount() {
return (list == null) ? 0 : list.size();
}
void deleteEvents(){
List<ListItem> selectedEvents = new ArrayList<>();
for (ListItem item : list){
if (item instanceof Event){
if (((Event) item).getSelected()){
selectedEvents.add(item);
}
}
}
list.removeAll(selectedEvents);
//notifyDataSetChanged();
currentSelectedPos = -1;
deleteEmptyHeaders();
}
public int getCountofHeaderItems(Header header)
{
int k = 0;
for (ListItem item: list)
{
if (item instanceof Event){
if (((Event) item).Date.equals(Long.parseLong(header.getHeader()))){
k++;
}
}
}
return k;
}
void deleteEmptyHeaders(){
List<Header> headers = new ArrayList<>();
for (ListItem event : list){
if (event instanceof Header){
if (getCountofHeaderItems((Header)event) == 0){
headers.add((Header)event);
}
}
}
list.removeAll(headers);
}
void toggleSelection(int position) {
if (getItemViewType(position) == TYPE_ITEM){
currentSelectedPos = position;
if (selectedItems.get(position)) {
selectedItems.delete(position);
((Event)list.get(position)).setSelected(false);
} else {
selectedItems.put(position, true);
((Event)list.get(position)).setSelected(true);
}
notifyItemChanged(position);
}
}
class VHHeader extends EventAdapter.EventViewHolder {
TextView txtTitle;
public VHHeader(View itemView) {
super(itemView);
this.txtTitle = (TextView) itemView.findViewById(R.id.tvTitleGroup);
}
}
class VHItem extends EventAdapter.EventViewHolder {
TextView txtName;
TextView txtDate;
TextView TVcomment;
CheckBox CBimportance;
public VHItem(View itemView) {
super(itemView);
this.txtName = (TextView) itemView.findViewById(R.id.tvTitle);
this.txtDate = (TextView) itemView.findViewById(R.id.tvDate);
this.TVcomment = (TextView) itemView.findViewById(R.id.tvComment);
this.CBimportance = (CheckBox) itemView.findViewById(R.id.cbIconImportant);
}
}
}
Here's my MainFragment:
private final static String ONLY_EVENTS = "ONLY_EVENTS";
private final static String GROUP_EVENTS_BY_DATE = "GROUP_EVENTS_BY_DATE";
ArrayList<ListItem> events;
private String ShowMode = ONLY_EVENTS;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first_new, container, false);
events = read(this.getActivity(), PROCESSED_EVENTS);
if (events == null)
events = new ArrayList<ListItem>();
rvEvent = view.findViewById(R.id.recyclerview);
rvEvent.setHasFixedSize(true);
lmEvent = new LinearLayoutManager(this.getContext());
adapterEvent = new EventAdapter(events);
rvEvent.setLayoutManager(lmEvent);
rvEvent.setAdapter(adapterEvent);
ShowEvents(ShowMode);
initSwipe();
return view;
}
public void ShowEvents(String mode){
switch (mode){
case ONLY_EVENTS:
adapterEvent.removeAllObjectsOf(Header.class);
break;
case GROUP_EVENTS_BY_DATE:
adapterEvent.groupByDate();
break;
}
}
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
Event nd = (Event) data.getSerializableExtra("class");
events.add(nd);
write(this.getActivity(), events, PROCESSED_EVENTS);
if (ShowMode.equals(GROUP_EVENTS_BY_DATE))
adapterEvent.groupByDate();
adapterEvent.notifyDataSetChanged();
}
}
public static void write(Context context, ArrayList<ListItem> events, String Key) {
Gson gson = new Gson();
String jsonString = gson.toJson(events);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Key, jsonString);
editor.apply();
}
public static ArrayList<ListItem> read(Context context, String Key) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String jsonString = pref.getString(Key, "");
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Event>>() {
}.getType();
ArrayList<ListItem> list = gson.fromJson(jsonString, type);
return list;
}
This is how the Event is sent from the activity:
Intent intent = new Intent(NewEvent.this, FirstFragment.class);
//intent.putExtra("name", (String) etName.getText().toString());
objectEvent = new Event(etName.getText().toString(), date, etComment.getText().toString(), etType.getText().toString(), etNotif.getText().toString(), swIsComplete.isChecked(), false);
intent.putExtra("class", objectEvent);
setResult(RESULT_OK, intent);
finish();
UPD. In OnActivityResult after executing the line adapterEvent.groupByDate(); nothing changes. Changes take place in the array list in the adapter, but for some reason they do not go into the array that is used in the fragment. In the ShowEvents procedure, the same line of code works, and after it the array is changed.

behaviour on ViewHolder error while performing getFilter

so i want to set the color to red when stok <= limit, looks normal onbindviewholder. But when performing searching, the first row data when the search delete, it turns red. any solution?first load,search the text with red one,after searching, first data went red
Context context;
List<Obat> obatList;
List<Obat> obatTempList;
int limit, stok;
public ObatAdapter(Context context, List<Obat> TempList) {
this.obatList = TempList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.obat_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Obat obat = obatList.get(position);
holder.qty.setText(obat.getStok());
holder.nama.setText(obat.getNama());
holder.harga.setText("Rp. " + obat.getHarga());
holder.satuan.setText(obat.getSatuan());
limit = Integer.parseInt(obat.getLimit());
stok = Integer.valueOf(obat.getStok());
if (stok <= limit) {
holder.onklik.setBackgroundColor(Color.parseColor("#f44242"));
}
holder.onklik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, MainTouchMenu.class);
i.putExtra("nama", obat.getNama().toString());
i.putExtra("stok", obat.getStok().toString());
i.putExtra("harga", obat.getHarga().toString());
i.putExtra("satuan", obat.getSatuan().toString());
i.putExtra("limit", obat.getLimit().toString());
context.startActivity(i);
}
});
holder.onklik.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent i = new Intent(context, MainHoldMenu.class);
i.putExtra("nama", obat.getNama().toString());
i.putExtra("stok", obat.getStok().toString());
i.putExtra("harga", obat.getHarga().toString());
i.putExtra("satuan", obat.getSatuan().toString());
i.putExtra("limit", obat.getLimit().toString());
context.startActivity(i);
return false;
}
});
}
#Override
public int getItemCount() {
return obatList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final List<Obat> results = new ArrayList<Obat>();
if (obatTempList == null) {
obatTempList = obatList;
}
if (constraint != null) {
if (obatTempList != null & obatTempList.size() > 0) {
for (final Obat obat : obatTempList) {
if (obat.getNama().toLowerCase().contains(constraint.toString())) {
results.add(obat);
}
}
}
oReturn.values = results;
}
return oReturn;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
obatList = (List<Obat>) results.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView nama, harga, qty, satuan;
RelativeLayout onklik;
public MyViewHolder(View itemView) {
super(itemView);
nama = itemView.findViewById(R.id.nama);
harga = itemView.findViewById(R.id.harga);
qty = itemView.findViewById(R.id.qty);
onklik = itemView.findViewById(R.id.onklik);
satuan = itemView.findViewById(R.id.satuan);
}
}
try this way
int statuscolor = 0;
if (stok <= limit) {
statuscolor = Color.parseColor("#f44242");
}
then set the color in itemView Background
holder.itemView.setBackgroundColor(statuscolor);
I have not tested this code let me know if it works

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.

wrong recyclerview item position

my recyclerview is great in scrolling but when it contains more than two items and click on last item or the one before it gives me the wrong position this is
and throws a NullPointerException this is my whole code from adapter to the listener.
my code :
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
private List<ItemView> items;
private Context context;
public ListAdapter(List<ItemView> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_style, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemView i = items.get(position);
ViewHolder.setHeadText(i.getHead());
ViewHolder.setScoreText(i.getContent());
}
#Override
public int getItemCount() {
return items.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private RecyclerViewOnTouchItemListener.ClickListener clickListener;
private static TextView headText, urlText;
private ConstraintLayout itemLayout;
public ViewHolder(View itemView) {
super(itemView);
headText = (TextView) itemView.findViewById(R.id.list_item_header);
urlText = (TextView) itemView.findViewById(R.id.list_item_content);
itemLayout = (ConstraintLayout) itemView.findViewById(R.id.item_list);
// itemLayout.setOnClickListener(this);
}
public static void setHeadText(String headText) {
ViewHolder.headText.setText(headText);
}
public static void setScoreText(String scoreText) {
ViewHolder.urlText.setText(scoreText);
}
public static String getHeadText(){return headText.getText().toString();}
public static String getUrlText(){return urlText.getText().toString();}
}
class RecyclerViewOnTouchItemListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerViewOnTouchItemListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = 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 && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) { }
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { }
interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
and this is the activity that holds the recyclerview :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_list);
context = getApplicationContext();
database = new DatabaseHelper(context);
listOfUrl = (RecyclerView) findViewById(R.id.url_list);
find = (Button) findViewById(R.id.findBtn);
cancel = (Button) findViewById(R.id.cancelBtn);
makeItPopUp();
listOfUrl.setLayoutManager(new LinearLayoutManager(this));
listOfUrl.setHasFixedSize(true);
listOfUrl.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
adapter = new ListAdapter(fillList(), context);
listOfUrl.setAdapter(adapter);
adapter.notifyDataSetChanged();
selectedItems = new ArrayList<Boolean>(Arrays.asList(new Boolean[listOfUrl.getAdapter().getItemCount()]));
Collections.fill(selectedItems, Boolean.FALSE);
listOfUrl.addOnItemTouchListener(
new RecyclerViewOnTouchItemListener(this, listOfUrl
, new RecyclerViewOnTouchItemListener.ClickListener() {
#Override
public void onClick(View view, int position) {
if (selectedItems.get(position))
setItemSelectedState(false, position, Color.WHITE);
else
setItemSelectedState(true, position, Color.LTGRAY);
}
#Override
public void onLongClick(View view, int position) {}
private void setItemSelectedState(boolean isSelected, int position, int color) {
try {
listOfUrl.getChildAt(position).setBackgroundColor(color);
selectedItems.add(position, isSelected);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
})
);
find.setOnClickListener(this);
cancel.setOnClickListener(this); }
any on can tell me what i did wrong.
Simple solution, create interface class:
public interface ListListener {
void onClick(int pos);
void onLongClick(int pos);
}
Adjust the content of your RecyclerViewAdapter class:
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
private ListListener listener;
private List<ItemView> items;
private Context context;
public ListAdapter(List<ItemView> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_style, parent, false);
return new ViewHolder(view);
}
public ItemView getItem(int pos) {
return items.get(pos);
}
public void setListener(ListListener listener) {
this.listener = listener;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemView i = items.get(position);
holder.setHeadText(i.getHead());
holder.setScoreText(i.getContent());
holder.itemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
if (listener != null && pos != RecyclerView.NO_POSITION) {
listener.onClick(pos);
}
}
});
holder.itemLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = holder.getAdapterPosition();
if (pos != -1) {
if (listener != null) {
listener.onLongClick(getItem(pos));
}
}
return true;
}
});
}
And in your Activity class I edited some parts:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_list);
context = getApplicationContext();
database = new DatabaseHelper(context);
listOfUrl = (RecyclerView) findViewById(R.id.url_list);
find = (Button) findViewById(R.id.findBtn);
cancel = (Button) findViewById(R.id.cancelBtn);
makeItPopUp();
listOfUrl.setLayoutManager(new LinearLayoutManager(this));
listOfUrl.setHasFixedSize(true);
listOfUrl.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
adapter = new ListAdapter(fillList(), context);
adapter.setListener(new SelectCountryDialogListener() {
#Override
public void onClick(int pos) {
ItemView item = adapter.getItem(pos);
}
#Override
public void onLongClick(int pos) {
ItemView item = adapter.getItem(pos);
}
});
listOfUrl.setAdapter(adapter);
selectedItems = new ArrayList<Boolean>(Arrays.asList(new Boolean[listOfUrl.getAdapter().getItemCount()]));
Collections.fill(selectedItems, Boolean.FALSE);
find.setOnClickListener(this);
cancel.setOnClickListener(this);
}
I'm pretty sure, that now it is very easy for you. Just to implement the functionality in onClick and onLongClick methods.

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