Here is the Adapter (RVAdapter_Reminders.java)
static List<DatabaseModel> dbList;
static Context context;
DBHelper dbHelper;
private int position;
public RVAdapter_Reminders(Context context, List<DatabaseModel> dbList) {
this.dbList = new ArrayList<DatabaseModel>();
this.context = context;
this.dbList = dbList;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
#Override
public RVAdapter_Reminders.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_reminder_template, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(final RVAdapter_Reminders.ViewHolder holder, final int position) {
holder.title.setText(dbList.get(position).getTitle());
holder.description.setText(dbList.get(position).getDescription());
holder.address.setText(dbList.get(position).getAddress());
holder.buttonViewOptions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.buttonViewOptions);
//inflating menu from xml
popup.inflate(R.menu.reminder_rv_menu);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
setPosition(holder.getAdapterPosition());
return false;
}
});
popup.show();
}
});
}
#Override
public void onViewRecycled(ViewHolder holder) {
holder.itemView.setOnClickListener(null);
super.onViewRecycled(holder);
}
#Override
public int getItemCount() {
return dbList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public TextView title, description, address, buttonViewOptions;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.task_title);
description = (TextView) itemView.findViewById(R.id.desc_title_text_tv);
address = (TextView) itemView.findViewById(R.id.address_title_text_tv);
buttonViewOptions = (TextView) itemView.findViewById(R.id.buttonViewOptions);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, R.id.menu_delete_option,
Menu.NONE, R.string.delete_menu_text);
}
}
Here is the Activity where the adapter is inflating data inside the RecyclerView
Reminders.java
FloatingActionButton fab;
DBHelper dbHelper;
List<DatabaseModel> dbList;
RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminders);
fab = (FloatingActionButton) findViewById(R.id.fab);
try {
getSupportActionBar().setTitle("Reminders");
} catch (Exception e) {
e.printStackTrace();
}
dbHelper = new DBHelper(this);
dbList = new ArrayList<DatabaseModel>();
dbList = dbHelper.getDataFromDB();
mRecyclerView = (RecyclerView) findViewById(R.id.rv_reminders);
mRecyclerView.setHasFixedSize(true);
// using a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
//specifying an adapter
mAdapter = new RVAdapter_Reminders(this, dbList);
mRecyclerView.setAdapter(mAdapter);
registerForContextMenu(mRecyclerView);
}
public void addReminder(View view) {
Intent intent = new Intent(Reminders.this, NewReminder.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Reminders.this, MainActivity.class);
startActivity(intent);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int position = -1;
try{
position = ((RVAdapter_Reminders)mRecyclerView.getAdapter()).getPosition();
}catch (Exception e) {
Log.d(String.valueOf(this), e.getLocalizedMessage(), e);
return super.onContextItemSelected(item);
}
switch (item.getItemId()){
case R.id.menu_delete_option:
onReminderDelete(dbList.get(position).getTitle());
break;
}
return super.onContextItemSelected(item);
}
private void onReminderDelete(String title){
dbHelper.deleteARow(title);
mRecyclerView.setAdapter(mAdapter);
}
DeleteRow function in the DBHelper class:
public void deleteARow(String title) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(REMINDERS_TABLE, RemindersContract.TITLE + " = " + title, null);
Log.d(String.valueOf(this), title + " deleted");
db.close();
}
and finally, RemindersContract class:
public static final String TITLE = "title";
your mAdapter has still the values with deleted value. You must update your dbList to have current values.
private void onReminderDelete(String title){
dbHelper.deleteARow(title);
dbList.remove(/* value that you want remove*/);
mAdapter.notifyDataSetChanged();
}
Related
I want display pictures from firebase realtime database. (with Encryted image(String))
like Encrypted Image is "photo"
I run this app recyclerview didn't appear with error code
No adapter attached; skipping layout
ItemObject.java
public class ItemObject {
private String title;
private String Photo;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPhoto() {
return Photo;
}
public void setPhoto(String photo){
this.Photo=photo;
}
public ItemObject(String title, String photo) {
this.title = title;
this.Photo=photo;
}
public ItemObject() {}
}
Recyclerview adpater MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.RecyclerViewHolders> {
private Context context;
private ArrayList<ItemObject> mItem;
private AdapterView.OnItemClickListener mListener = null;
public class RecyclerViewHolders extends RecyclerView.ViewHolder
implements View.OnCreateContextMenuListener {
TextView title;
ImageView imageView;
// private CardView cardView;
public RecyclerViewHolders(#NonNull View itemView) {
super(itemView);
this.title = itemView.findViewById(R.id.title_listitem);
this.imageView = itemView.findViewById(R.id.photo_listitem);
//
itemView.setOnCreateContextMenuListener(this);
}
private final MenuItem.OnMenuItemClickListener onEditMenu = new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case 1001:
mItem.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(), mItem.size());
break;
}
return true;
}
};
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuItem Delete = menu.add(Menu.NONE,1001,1,"삭제");
Delete.setOnMenuItemClickListener(onEditMenu);
}
}
public MyAdapter(ArrayList<ItemObject> item){
this.context = context;
this.mItem = item;
}
#NonNull
#Override
public RecyclerViewHolders onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.listitem,viewGroup,false);
RecyclerViewHolders viewHolders=new RecyclerViewHolders(view);
return viewHolders;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolders holder, int position) {
/* Glide.with(context)
.load(mItem.get(position).getPhoto())
.into(holder.imageView);
*/
ItemObject itemObject = mItem.get(position);
String photo = itemObject.getPhoto();
holder.title.setTextSize(TypedValue.COMPLEX_UNIT_SP,10);
holder.title.setGravity(Gravity.CENTER);
holder.title.setText(itemObject.getTitle());
holder.imageView.setImageURI(Uri.parse(photo));
// Glide.with(this.context).load(mItem.get(position).getPhoto()).centerCrop().into(holder.imageView);
}
public void setmItem(ArrayList<ItemObject> mItem) {
this.mItem = mItem;
}
public void deleteItem(int position) {
mItem.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return mItem.size();
}
}
MainUpload.java
mRecyclerView = findViewById(R.id.recyclerview_main_list);
int numberOfColumns = 3;
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getApplication(),numberOfColumns);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mRecyclerView.setHasFixedSize(true);
reference = FirebaseDatabase.getInstance().getReference();
mItem = new ArrayList<>();
//clearAll();
loadPhoto();
DividerItemDecoration dividerItemDecoration=new DividerItemDecoration(mRecyclerView.getContext(),mGridLayoutManager.getOrientation());
mRecyclerView.addItemDecoration(dividerItemDecoration);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
ItemObject itemObject = mItem.get(position);
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("title",itemObject.getTitle());
intent.putExtra("photo",itemObject.getPhoto());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
function loadPhoto()
private void loadPhoto() {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String key = FirebaseDatabase.getInstance().getInstance().getReference("users")
.child(currentUser.getUid()).child("Object").getKey();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users")
.child(currentUser.getUid()).child("Object").child(key);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mRecyclerView = findViewById(R.id.recyclerview_main_list);
int numberOfColumns = 3;
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getApplication(),numberOfColumns);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mRecyclerView.setHasFixedSize(true);
ItemObject itemObject = new ItemObject();
//여기서 에러
String En1 = snapshot.child("photo").getValue().toString();
byte []En2 = En1.getBytes();
AESCoderAndriod aesCoderAndriod = new AESCoderAndriod();
try {
byte []Dn1 = aesCoderAndriod.decrypt(seed,En2);
Bitmap Dn2 = byteArrayToBitmap(Dn1);
Uri Dn3 = getImageUri(getApplicationContext(),Dn2);
itemObject.setPhoto(Dn3.toString());
itemObject.setTitle(snapshot.child("title").getValue().toString());
mItem.add(itemObject);
} catch (Exception e) {
e.printStackTrace();
}
// itemObject.setPhoto(snapshot.child("Photo").getValue().toString());
}
//myAdapter= new MyAdapter(getApplicationContext(),mItem);
// mRecyclerView.setAdapter(myAdapter);
myAdapter = new MyAdapter(mItem);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
what is the problem? I connect adapter and recyclerview, and set gridmanager.
You should set your adapter at first, Start with empty recycler view, when data loads you should notify your adapter about the change.
mRecyclerView.setLayoutManager(mGridLayoutManager);
mRecyclerView.setHasFixedSize(true);
mItem = new ArrayList<>();
myAdapter = new MyAdapter(mItem);
mRecyclerView.setAdapter(myAdapter);
loadPhoto();
You function already include notify data change method. You don't need to set new layout manager on data load method
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ItemObject itemObject = new ItemObject();
//여기서 에러
String En1 = snapshot.child("photo").getValue().toString();
byte []En2 = En1.getBytes();
AESCoderAndriod aesCoderAndriod = new AESCoderAndriod();
try {
byte []Dn1 = aesCoderAndriod.decrypt(seed,En2);
Bitmap Dn2 = byteArrayToBitmap(Dn1);
Uri Dn3 = getImageUri(getApplicationContext(),Dn2);
itemObject.setPhoto(Dn3.toString());
itemObject.setTitle(snapshot.child("title").getValue().toString());
mItem.add(itemObject);
} catch (Exception e) {
e.printStackTrace();
}
// itemObject.setPhoto(snapshot.child("Photo").getValue().toString());
}
myAdapter.notifyDataSetChanged();
}
I created a recyclerview that takes data from Firebase. I have two arrays that are sent to the adapter to be used in the items. I've implemented a search filter. This works for the first array, but the second one is always in the starting position. How can I get the second array in the same position as the first filter? Thank you
MainActivity
public class FriendActivity3 extends AppCompatActivity
//implements FriendHoldAdapter3.ItemClickListener{
FriendHoldAdapter3 adapter;
RecyclerView recyclerView;
ArrayList<FriendItem> username;
ArrayList<String> uid, url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friend2);
SearchView search = (SearchView) findViewById(R.id.ciao);
recyclerView = (RecyclerView) findViewById(R.id.friend_list2);
//recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
final DatabaseReference mPostReference = FirebaseDatabase.getInstance().getReference().child("user-profile");
mPostReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
username = new ArrayList<>();
uid = new ArrayList<String>();
url = new ArrayList<String>();
for (DataSnapshot data : dataSnapshot.getChildren()){
final FriendItem friendItem = data.getValue(FriendItem.class);
final String friendItem2 = data.getKey();
username.add(friendItem);
uid.add(friendItem2);
adapter = new FriendHoldAdapter3(getApplicationContext(), username, uid, url);
//adapter.setClickListener(FriendActivity3.this);
recyclerView.setAdapter(adapter);
/**
adapter = new FriendHoldAdapter2(FriendActivity2.this, username, uid);
adapter.setClickListener(FriendActivity2.this);
recyclerView.setAdapter(adapter);
**/
final List<FriendItem> filteredModelList = filter(username, " ");
adapter.setFilter(filteredModelList);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.equals("")){
newText = " ";
}
if (newText.equals("View All")){
newText = "";
}
final List<FriendItem> filteredModelList = filter(username, newText);
adapter.setFilter(filteredModelList);
return true;
}
});
private List<FriendItem> filter(List<FriendItem> models, String query) {
query = query.toLowerCase();final List<FriendItem> filteredModelList = new ArrayList<>();
for (FriendItem model : models) {
final String text = model.username.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}}
Adapter
public class FriendHoldAdapter3 extends RecyclerView.Adapter<FriendHoldAdapter3.ViewHolder> {
private List<FriendItem> mData_username = Collections.emptyList();
private List<String> mData_uid = Collections.emptyList();
private List<String> mData_url = Collections.emptyList();
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public FriendHoldAdapter3(Context context, List<FriendItem> data_username, List<String> data_uid, List<String> data_url) {
this.mInflater = LayoutInflater.from(context);
this.mData_username = data_username;
this.mData_uid = data_uid;
this.mData_url = data_url;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.friend_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
// binds the data to the textview in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FriendItem username = mData_username.get(position);
String uid = mData_uid.get(position);
holder.myTextView.setText(username.username);
holder.uid_txt.setText(uid);
}
// total number of rows
#Override
public int getItemCount() {
return mData_username.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView myTextView, uid_txt;
public ViewHolder(final View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.friend_item_name);
uid_txt = (TextView) itemView.findViewById(R.id.friend_item_uid);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(),mData_uid.get(getAdapterPosition()), Toast.LENGTH_SHORT).show();
if (uid_txt.getText().toString()!=null | !uid_txt.getText().toString().equals("") ){
Intent intent = new Intent(itemView.getContext(), AccountPubblic.class);
//MANDARE TESTO A AccountPubblic
intent.putExtra(AccountPubblic.EXTRA_UID, uid_txt.getText().toString());
itemView.getContext().startActivity(intent);
}
}
});
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public FriendItem getItem(int id) {
return mData_username.get(id);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
public void setFilter(List<FriendItem> countryModels) {
mData_username = new ArrayList<>();
mData_username.addAll(countryModels);
notifyDataSetChanged();
}}
Fragment_bookmovie2.java
public class Fragment_bookmovie2 extends android.support.v4.app.Fragment implements View.OnClickListener {
private static final String TAG ="Fragment_bookmovie2" ;
ArrayList<String> moviename= new ArrayList<>();
ArrayList<String> movieyear= new ArrayList<>();
ArrayList<String> moviebanner= new ArrayList<>();
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
Movie_listAdapter2 adapter ;
LinearLayout progress;
RelativeLayout ll;
public Fragment_bookmovie2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.e(TAG,"reched on create");
// first step - retrieve object
Backendless.Persistence.of(Booking.class).find(new AsyncCallback<BackendlessCollection<Booking>>() {
#Override
public void handleResponse(BackendlessCollection<Booking> response) {
for(Booking booking : response.getData()) {
if(!moviename.contains(booking.getMovie().get(0).getMovie_Name())) {
moviename.add(booking.getMovie().get(0).getMovie_Name());
movieyear.add(booking.getMovie().get(0).getYear());
moviebanner.add("https://api.backendless.com/" + BackendSetting.APPLICATION_ID + "/" + BackendSetting.VERSION + "/files/mypics/" + booking.getMovie().get(0).getImage());
}
}
adapter.notifyDataSetChanged();
ll.removeView(progress);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), fault.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
moviename.add("haha");
movieyear.add("hello");
moviebanner.add("http://www.w3schools.com/css/trolltunga.jpg");
// Inflate the layout for this fragment
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_bookmovie2, container, false);
progress = (LinearLayout) ll.findViewById(R.id.progress_bookingFrag);
recyclerView = (RecyclerView) ll.findViewById(R.id.recycle_movielist);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new Movie_listAdapter2(getActivity(),moviename,movieyear,moviebanner);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return ll;
}
#Override
public void onClick(View view) {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onButtonClickListnerProceed(Integer pos) {
Intent booking_screen_redirect = new Intent(getActivity(), BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(pos));
this.onPause();
startActivity(booking_screen_redirect);
getActivity().overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}*/
}
Movie_listAdapter2.java
public class Movie_listAdapter2 extends RecyclerView.Adapter<Movie_listAdapter2.Movie_cards>{
final static String TAG="Movie_listAdapter2";
Context context_external;
ArrayList<String> moviename=new ArrayList<>();
ArrayList<String> movieyear=new ArrayList<>();
ArrayList<String> banner=new ArrayList<>();
public Movie_listAdapter2(Context context,ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
//set the context and the format of the layout inside the list item
//i.e R.layout.movie_list_adapter
//also the resource i.e the item names in an ArrayList
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
this.context_external=context;
Log.e(TAG,"size = "+movieyear.size()+" "+moviename.size());
}
public static class Movie_cards extends RecyclerView.ViewHolder {
CardView cv;
TextView movie_name;
TextView movie_year;
Button proceed;
ImageView movie_banner;
public Movie_cards(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.movie_list_card);
movie_name = (TextView)itemView.findViewById(R.id.tv_card_moviename);
movie_year = (TextView)itemView.findViewById(R.id.tv_card_movieyear);
movie_banner = (ImageView)itemView.findViewById(R.id.card_moviebanner);
proceed = (Button) itemView.findViewById(R.id.b_card_proceed);
}
}
#Override
public Movie_cards onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_card, parent, false);
Movie_cards pvh = new Movie_cards(v);
return pvh;
}
public void updateData(ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final Movie_cards holder, final int position) {
holder.movie_name.setText(moviename.get(position));
holder.movie_year.setText(movieyear.get(position));
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.networkPolicy(NetworkPolicy.OFFLINE)
.error(R.drawable.placeholder)
.fit()
.into(holder.movie_banner, new Callback() {
#Override
public void onSuccess() {
//i.e image was loaded from cache
}
#Override
public void onError() {
//image was downloaded as it wasn't available in cache
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.error(R.drawable.warning)
.fit()
.into(holder.movie_banner);
}
});
holder.proceed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent booking_screen_redirect = new Intent(context_external, BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(position));
context_external.startActivity(booking_screen_redirect);
//overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
});
}
#Override
public int getItemCount() {
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
the fragment displays empty and no items appear even though i have added the data to arraylists and passed to the adapter. please help . thanks in advance
Problem is in below code you are returning 0 that's why its not showing any item
#Override
public int getItemCount() {
return 0;
}
You should return your list's size here either moviename.size(); or movieyear.size()
I would like to know how to handle position of the row if the adapter is changed - for example if I write something to SearchView - adapter has changed and position is different. I have done this (below), but it shows the item before changed position.
My issue is with Recycler view item click.
Could you help me with that?
Adapter
public class ContactsRecyclerAdapter extends RecyclerView.Adapter<ContactsRecyclerAdapter.BindingHolder> {
private static OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(View itemView, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
private List<Contact> mContacts;
private List<Contact> mContactsFiltered;
SearchViewFilter filter;
Context mContext;
public ContactsRecyclerAdapter(Context context, List<Contact> contact) {
this.mContext = context;
this.mContacts = contact;
this.mContactsFiltered = contact;
filter = new SearchViewFilter(mContacts, this);
}
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(itemView, getLayoutPosition());
}
});
}
public ViewDataBinding getBinding() {
return binding;
}
}
#Override
public BindingHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_contact, parent, false);
BindingHolder holder = new BindingHolder(view);
return holder;
}
#Override
public void onBindViewHolder(BindingHolder holder, int position) {
final Contact contact = mContactsFiltered.get(position);
holder.getBinding().setVariable(BR.contact, contact);
holder.getBinding().executePendingBindings();
}
Fragment
public class ContactListFragment extends Fragment implements View.OnClickListener {
FloatingActionButton fabButton;
SearchView searchView;
RecyclerView recyclerView;
String name, number, email;
private List<Contact> mContact = new ArrayList<>();
private ContactsRecyclerAdapter mAdapter;
public static ContactListFragment newInstance() {
Bundle args = new Bundle();
ContactListFragment fragment = new ContactListFragment();
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
searchView = (SearchView) view.findViewById(R.id.search_view);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mContact = SugarRecord.listAll(Contact.class);
mAdapter = new ContactsRecyclerAdapter(getActivity(), mContact);
recyclerView.setAdapter(mAdapter);
//item click
mAdapter.setOnItemClickListener(new ContactsRecyclerAdapter.OnItemClickListener() {
#Override
public void onItemClick(View itemView, int position) {
Contact contact = SugarRecord.findById(Contact.class, (long) position + 1);
name = contact.getName();
number = contact.getNumber();
email = contact.getEmail();
showAlertDialog();
}
});
searchFilter();
return view;
}
public void sortList() {
if(mContact.size() > 0) {
if (!isSort) {
Collections.sort(mContact, new Comparator<Contact>() {
#Override
public int compare(Contact contact1, Contact contact2) {
return contact1.getName().compareToIgnoreCase(contact2.getName());
}
});
}
else {
Collections.reverse(mContact);
isSort = false;
}
}
mAdapter.notifyDataSetChanged();
Click listener does not work with a RecyclerView. use OnItemTouchListener()
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
#Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);
you have to overide onclick in BindingHolder class. Inside onclick method invoke a callback method of object passed via constructor etc
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
public void onClick(View view) {
//call a callback method here
}
}
public ViewDataBinding getBinding() {
return binding;
}
}
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);