getting last item from list - onclicking add button on Recyclerview - android

I have added cart image in my Adapter class but whenever I click on the button always get the last element from the list. Here is my adapter class and activity class.
Details are perfectly fetched from firebase and Log file showing list of menu.
Here is my MenuAdapter.java class.
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private Context mCtx;
private List<Menu> menuList;
private ItemClickEvent itemclick;
public MenuAdapter(Context mCtx, List<Menu> menuList, ItemClickEvent itemclick) {
this.mCtx = mCtx;
this.menuList = menuList;
this.itemclick = itemclick;
}
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(mCtx).inflate(R.layout.menu_list, viewGroup, false);
return new MenuViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MenuViewHolder menuViewHolder, final int i) {
final Menu menu = menuList.get(i);
menuViewHolder.itemName.setText(menu.itemName);
menuViewHolder.itemPrice.setText(menu.itemPrice);
menuViewHolder.addCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemclick.imageClicked(menu);
}
});
}
#Override
public int getItemCount() {
return menuList.size();
}
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView itemName, itemPrice;
#SuppressLint("StaticFieldLeak")
ImageView addCart;
MenuViewHolder(#NonNull View itemView) {
super(itemView);
itemName = itemView.findViewById(R.id.itemName);
itemPrice = itemView.findViewById(R.id.itemPrice);
addCart = itemView.findViewById(R.id.menuAddCart);
//addCart.setOnClickListener(this);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}
and this MenuActivity.java class
public class MenuActivity extends AppCompatActivity implements ItemClickEvent
{
private ActionBar toolbar;
List<Menu> menuList;
RecyclerView recyclerView;
MenuAdapter adapter;
DatabaseReference databaseReference;
ProgressBar progressBar;
Menu menu;
int foodId = 1;
int cat;
String id,itemName, itemPrice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Intent intent = getIntent();
final String category = intent.getStringExtra("cat_id");
final String catName = intent.getStringExtra("cat_name");
toolbar = getSupportActionBar();
toolbar.setTitle(catName);
cat = Integer.parseInt(category) - 1;
menuList = new ArrayList<>();
recyclerView = findViewById(R.id.menu_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MenuAdapter(this, menuList,this);
recyclerView.setAdapter(adapter);
ImageView addTCart = findViewById(R.id.menuAddCart);
progressBar = findViewById(R.id.progressBarLoading);
databaseReference = FirebaseDatabase.getInstance().getReference("foods/" + cat + "/menu-items");
// fetchMenu(category);
progressBar.setVisibility(View.VISIBLE);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressBar.setVisibility(View.GONE);
if (dataSnapshot.exists()) {
for (DataSnapshot wallpaperSnapshot : dataSnapshot.getChildren()) {
id = wallpaperSnapshot.getKey();
itemName = wallpaperSnapshot.child("name").getValue(String.class);
itemPrice = wallpaperSnapshot.child("price").getValue(String.class);
menu = new Menu(id, itemName, itemPrice, category);
menuList.add(menu);
Log.d("FOOD-DETAIL", String.valueOf(menu));
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void imageClicked(Menu m) {
new Database(getApplicationContext()).addToCart(new Order(
Integer.parseInt(id),
menu.getItemName(),
"1",
menu.getItemPrice()
));
foodId += 1;
Toast.makeText(getBaseContext(), itemName+" added to cart", Toast.LENGTH_SHORT).show();
}
#Override
public void viewClicked() {
}
}

Hello try making these changes in imageClicked() in MenuActivity
#Override
public void imageClicked(Menu m) {
new Database(getApplicationContext()).addToCart(new Order(
m.getId(),
m.getItemName(),
"1",
m.getItemPrice()
));
foodId += 1;
Toast.makeText(getBaseContext(), itemName+" added to cart", Toast.LENGTH_SHORT).show();
}

There should be more efficient way to set listener. Just set that listener (same way as it is now) in constructor of MenuViewHolder and assign to this. And in method onClick - check R.id of view and if it is addCart instead of calling itemclick.imageClicked(menu) just call item.click.imageClicked(getAdapterPosition())
This because onBindViewHolder() is calling multiple times and you will still create new listener. But in constructor you create that listener only if you need new MenuViewHolder and use the actual position of adapter.

Related

About opening a new activity in respond to a click on a RecyclerView item which is inside of a fragment

I'm loading some data into a RecyclerView from Firebase Realtime Database. This RecyclerView is in a fragment and I want to open a new activity when an item is clicked. But when i add the onClickListener to an item from the adapter, my click doesn't even recognized by the app. I'm not sure what I'm doing wrong here because this method worked fine for a RecyclerView when it is inside of a normal activity.
This is a project for my university and I should submit it tomorrow. So I can really use some help.
This is the my data Adapter class,
public class Adapter_NoLimit extends RecyclerView.Adapter<Adapter_NoLimit.LViewHolder> {
Context context;
ArrayList<Helper> list_nl;
public Adapter_NoLimit(Context context, ArrayList<Helper> list_nl) {
this.context = context;
this.list_nl = list_nl;
}
#NonNull
#Override
public Adapter_NoLimit.LViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.itemlist, parent, false);
return new LViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull Adapter_NoLimit.LViewHolder holder, int position) {
//final Helper temp = list_nl.get(position);
String fname_txt = list_nl.get(position).getFname();
String catg_txt = list_nl.get(position).getSpin();
String prof_img = list_nl.get(position).getProfile_url();
holder.setUsers(fname_txt, catg_txt, prof_img);
holder.f_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) v.getContext();
Intent i = new Intent(activity, UserProfile_VV.class);
i.putExtra("full name", fname_txt);
activity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return list_nl.size();
}
public class LViewHolder extends RecyclerView.ViewHolder{
private TextView f_name, catG;
private ImageView profile_pic;
public LViewHolder(#NonNull View itemView) {
super(itemView);
f_name = itemView.findViewById(R.id.username_view);
catG = itemView.findViewById(R.id.category_view);
profile_pic = itemView.findViewById(R.id.userimage);
}
public void setUsers(String fname_txt, String catg_txt, String prof_img) {
f_name.setText(fname_txt);
catG.setText(catg_txt);
Picasso.get().load(prof_img).fit().into(profile_pic);
}
}
}
This is one of fragments,
public class Beauty_Frag extends Fragment {
RecyclerView recyclerView;
DatabaseReference reference, user_ref;
ArrayList<Helper> list;
Adapter adapter;
FirebaseAuth auth;
String uid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_beauty, container, false);
recyclerView = v.findViewById(R.id.beauty_recycler_frag);
reference = FirebaseDatabase.getInstance().getReference();
user_ref = reference.child("users");
auth = FirebaseAuth.getInstance();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//searchField = findViewById(R.id.search_field);
list = new ArrayList<>();
adapter = new Adapter(getContext(), list);
recyclerView.setAdapter(adapter);
user_ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull /*#org.jetbrains.annotations.NotNull*/ DataSnapshot snapshot) {
for (DataSnapshot key : snapshot.getChildren()) {
if( key.child("spin").getValue().toString().equals("Beauty")) {
Helper helper = key.getValue(Helper.class);
list.add(helper);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull /*#org.jetbrains.annotations.NotNull*/ DatabaseError error) {
}
});
return v;
}
}
You are very welcome if you have any solution.
Use below code for onClicklistner:
holder.f_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfile_VV.class);
i.putExtra("full name", fname_txt);
context.startActivity(i);
}
});

RecycerView always reset back to first position after inserting new Firebase data

My recyclerview always reset to first position after new data is inserted to firebase. In my TestAdapter class, I have an onClickListener which increments like on a post when clicked. Whenever I click on this "like" button, view is reset to first position. I believe this issue is related to setAdapter() being called on data changed. Please help!
MainActivity fetches "post" data from Firebase and populates it in TestAdapter class.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private TestAdapter testAdapter;
private ArrayList<Post> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
fetchPostFromDB();
}
private void fetchPostFromDB() {
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("Post");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postList = new ArrayList<>();
for (DataSnapshot snap : snapshot.getChildren()) {
String post = snap.child("post").getValue().toString();
Post post = new Post(post);
postList.add(post);
}
testAdapter = new TestAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(testAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
TestAdapter binds the data (postList) and has an onClickListener.
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.TestHolder> {
private List<Post> postList;
private Context context;
private DatabaseReference databaseReference;
public TestAdapter(Context ct, ArrayList<Post> postList) {
context = ct;
this.postList = postList;
}
#NonNull
#Override
public TestHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.post_item, parent, false);
final TestHolder holder = new TestHolder(view);
holder.ibLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String postID = postList.get(holder.getAdapterPosition()).getPostID();
databaseReference = FirebaseDatabase.getInstance().getReference("Posts").child(postID).child("likes");
int incrementLike = postList.get(holder.getAdapterPosition()).getLikes() + 1;
databaseReference.setValue(incrementLike);
}
});
return holder;
}
#Override
public void onBindViewHolder(#NonNull final TestHolder holder, final int position) {
holder.tvPost.setText(postList.get(position).getPost());
holder.tvVotes.setText(Integer.toString(postList.get(position).getLikes()));
}
#Override
public int getItemCount() {
return postList.size();
}
public static class TestHolder extends RecyclerView.ViewHolder {
TextView tvPost, tvLikes;
ImageButton ibLike;
public TestHolder(#NonNull View itemView) {
super(itemView);
tvPost = itemView.findViewById(R.id.tvPost);
tvLikes = itemView.findViewById(R.id.tvLikes);
ibLike = itemView.findViewById(R.id.ibLike);
}
}
Here need to initialize your adapter class from main activity. and then when data received just call adapter.notifiyDatasetChanged like:
onCreate():
postList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
testAdapter = new TestAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(testAdapter);
and from your fetchPostFromDB delete adapter initialization insted of this just put this line testAdapter.notifiyDataSetChanged()
And when click on text button you can update/handle like this:
holder.ibLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String postID = postList.get(holder.getAdapterPosition()).getPostID();
databaseReference = FirebaseDatabase.getInstance().getReference("Posts").child(postID).child("likes");
int incrementLike = postList.get(holder.getAdapterPosition()).getLikes() + 1;
postList.get(holder.getAdapterPosition()).setLikes(incrementLike);
databaseReference.setValue(incrementLike);
notifyDataSetChanged();
}
});

why does isChecked() method not working with my array

So my problem is that.. why does the isChecked method not working.
My first guess to my problem would be im declaring the wrong array?
My second guess would be I lack something to call or missing something out?
the goal of my code here is to create a collector in firebase and then record it in the database of the collector by which the user chose from the multiple selected job orders
public class MainActivity extends AppCompatActivity {
private List<Model> mModelList;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
Button mjobOrderBtn;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String jobId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclerview);
mjobOrderBtn = findViewById(R.id.jobOrderBtn);
mRecyclerView = findViewById(R.id.recycler_view);
mAdapter = new RecyclerViewAdapter(getListData());
LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setAdapter(mAdapter);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
jobId = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("job order").document(jobId);
mjobOrderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRecyclerView.isChecked()){
}
}
});
}
private List<Model> getListData() {
mModelList = new ArrayList<>();
mModelList.add(new Model("Flat Tire "));
mModelList.add(new Model("Towing "));
mModelList.add(new Model("Battery "));
mModelList.add(new Model("Empty Gas "));
return mModelList;
}
}
RecyclerViewAdaptor.java
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private List<Model> mModelList;
public RecyclerViewAdapter(List<Model> modelList) {
mModelList = modelList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_itemrow, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Model model = mModelList.get(position);
holder.textView.setText(model.getText());
holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setSelected(!model.isSelected());
holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
}
});
}
#Override
public int getItemCount() {
return mModelList == null ? 0 : mModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private View view;
private TextView textView;
private MyViewHolder(View itemView) {
super(itemView);
view = itemView;
textView = itemView.findViewById(R.id.text_view);
}
}
}
Also here's the model class
Model.java
public class Model {
private String text;
private boolean isSelected = false;
public Model(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
you need to create checkbox inside view item layout for each item in your array. Here is an example
you can get your order list with a defined method inside adapter class. Something like this:
public List<Model> getSelectedItems(){
List<Model> results = new ArrayList<Model>();
for(model: mModelList){
if(model.isSelected()){
results.add(model);
}
}
return results;
}
And inside button order click method, just get it out:
mjobOrderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<Model> orderList = mAdapter.getSelectedItems();
}
});

Adding item dynamically to recyclerview

I am building a notepad app. I am trying to add another item to the recyclerview as soon as the new note is saved by the user.
public class NotePad extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_pad);
final FloatingActionButton button =
(FloatingActionButton)findViewById(R.id.save_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveData();
}
});
}
// To Send Note Title to MainActivity
public void SendData() {
EditText editText = findViewById(R.id.textView3);
final String str = editText.getText().toString();
Log.d("Check","str:"+str);
Intent intent = new Intent(NotePad.this,MainActivity.class);
intent.putExtra(EXTRA_MESSAGE, str);
startActivity(intent);
}
// To Save Note Content
public void SaveData() {
FileOutputStream outputStream;
try {
EditText editText = findViewById(R.id.textView3);
final String str = editText.getText().toString();
String content = findViewById(R.id.textView).toString();
Log.d("Test","inside try block");
outputStream = openFileOutput(str, Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
Log.d("Test","save done");
SendData();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am saving a note and sending the title(str) that is to be displayed in recyclerview row to MainActivity as shown above.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<String> notes = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
String title = intent.getStringExtra(NotePad.EXTRA_MESSAGE);
Log.d("Check","title added"+title);
notes.add(title);
BuildRecyclerView();
}
public void BuildRecyclerView() {
recyclerView = (RecyclerView)findViewById(R.id.recycle_list);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(notes);
recyclerView.setAdapter(mAdapter);
}
But whenever I add a new note it overwrites the first entry in the recyclerview instead of occupying the next row of the recyclerview. This is my adapter code:
public class MyAdapter extends
RecyclerView.Adapter<MyAdapter.MyViewHolder> {
ArrayList<String> Notes_list = new ArrayList<String>();
public MyAdapter(ArrayList<String> notes) {
Notes_list = notes;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_items,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int
position) {
holder.mTextView.setText(Notes_list.get(position));
}
#Override
public int getItemCount() {
return Notes_list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.view_holder);
}
}
}
Because you pass last item to MainActivity and generate a new RecyclerView with passed item. You have to keep notes array on first class and pass whole array to MainActivity with intent.

wrong positions of two arrays after filter

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();
}}

Categories

Resources