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();
}
});
Related
I tried several ways but always get a NPE due to difference in lifecycles etc
This is my MainActivity where I need to transfer a new Contact to the adapter
public class MainActivity extends AppCompatActivity {
private TextInputEditText textInputLastName;
private TextInputEditText textInputFirstName;
private TextInputEditText textInputMiddleName;
private TextInputEditText textInputAge;
private int age;
private TextInputLayout lastNameWrapper;
private TextInputLayout ageWrapper;
private ViewGroup parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastNameWrapper = findViewById(R.id.last_name_wrapper);
ageWrapper = findViewById(R.id.age_wrapper);
textInputLastName = findViewById(R.id.text_input_last_name);
textInputFirstName = findViewById(R.id.text_input_first_name);
textInputMiddleName = findViewById(R.id.text_input_middle_name);
textInputAge = findViewById(R.id.text_input_age);
addButtonMainActivity();
}
private void addButtonMainActivity() {
final Button buttonSendData = findViewById(R.id.button_send);
buttonSendData.setOnClickListener(view -> {
startActivity(new Intent(this, ShowDatabaseActivity.class));
if (textInputLastName.getText().toString().isEmpty()) {
lastNameWrapper.setError("Enter your Last Name");
return;
} else if (TextUtils.isEmpty(textInputAge.getText())) {
ageWrapper.setError("Enter your Age");
return;
}
age = Integer.parseInt(String.valueOf(textInputAge.getText()));
final Handler handler = new Handler();
Thread backgroundThread = new Thread(new Runnable() {
#Override
public void run() {
String lastName = textInputLastName.getText().toString();
String firstName = textInputFirstName.getText().toString();
String middleName = textInputMiddleName.getText().toString();
int age = Integer.parseInt(textInputAge.getText().toString());
Contact contact = new Contact(lastName, firstName, middleName, age);
AppDatabase.getINSTANCE(MainActivity.this).contactDao().insert(contact);
AppDatabase.getINSTANCE(MainActivity.this).contactDao().getAll();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addContact(contact);
}
});
}
});
backgroundThread.start();
});
}}
the line in question (this line is red now), where I need to transfer data to the adapter is
adapter.addContact(contact);
this is my 2nd activity that is used to initiated adapter's object and recycler view (and that is used to display database)
public class ShowDatabaseActivity extends AppCompatActivity {
private List<Contact> allContacts = new ArrayList<>();
public ContactsListAdapter adapter;
private ViewGroup parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_database);
setupToolbar();
initRecyclerView();
}
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recycler_view);
adapter = new ContactsListAdapter(allContacts, ShowDatabaseActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapter);
getTableData();
}
And this is my adapter class
public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ContactViewHolder> {
private Context context;
private List<Contact> contacts;
private LayoutInflater inflater;
public LayoutInflater getInflater() {
return inflater;
}
public ContactsListAdapter(#NonNull List<Contact> contacts, Context context) {
this.contacts = contacts;
this.context = context;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.recycler_view, parent, false);
return new ContactViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ContactViewHolder holder, int position) {
Contact currentContact = contacts.get(position);
if (currentContact != null) {
holder.contactLastNameView.setText(currentContact.getLastName());
holder.contactFirstNameView.setText(currentContact.getFirstName());
holder.contactMiddleNameView.setText(currentContact.getMiddleName());
holder.contactAgeView.setText(Integer.toString(currentContact.getAge()));
} else {
holder.contactLastNameView.setText("No information");
holder.contactFirstNameView.setText("No information");
holder.contactMiddleNameView.setText("No information");
holder.contactAgeView.setText("No information");
}
}
#Override
public int getItemCount() {
return contacts.size();
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
private final TextView contactLastNameView;
private final TextView contactFirstNameView;
private final TextView contactMiddleNameView;
private final TextView contactAgeView;
public TextView getContactLastNameView() {
return contactLastNameView;
}
public TextView getContactFirstNameView() {
return contactFirstNameView;
}
public TextView getContactMiddleNameView() {
return contactMiddleNameView;
}
public TextView getContactAgeView() {
return contactAgeView;
}
public ContactViewHolder(View itemView) {
super(itemView);
contactLastNameView = itemView.findViewById(R.id.last_name_text_view);
contactFirstNameView = itemView.findViewById(R.id.first_name_text_view);
contactMiddleNameView = itemView.findViewById(R.id.middle_name_text_view);
contactAgeView = itemView.findViewById(R.id.age_text_view);
}
}
public void addContact(Contact contact) {
contacts.add(contact);
notifyDataSetChanged();
}
}
I would be really grateful for any help
You can't access adapter from your MainActivity, send you Contact data to the other Activity by using Intent's(putExtra) and use adapter.addContact() there.
Create a method in your activity like
public void showData(List<Contact> allContacts) {
//here you can show the data received from main activity
this.addContacts.addAll(allContacts);
adapter.notifyDataSetChanged();
}
you can call this method from MainActivity when you have data
I have this RecyclerView that doesn't want to show the item at position 0 anymore, after enough items are added to make the RecyclerView scrollable. Instead it seems to stick to the bottom item and scroll down with this one, although the other items are added at position 0.
public class hauptseite extends AppCompatActivity {
private ArrayList<ExampleItem> mExampleList;
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ImageButton btnInput;
private EditText editTextInput;
private int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
createExampleList();
buildRecyclerView();
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
btnInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editTextInput.getText().toString();
insertItem(name);
}
});
}
public void insertItem(String name) {
mExampleList.add(position, new ExampleItem(name));
mAdapter.notifyItemInserted(position);
editTextInput.setText("");
}
public void removeItem(int position) {
mExampleList.remove(position);
mAdapter.notifyItemRemoved(position);
}
public void createExampleList() {
mExampleList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerName);
mRecyclerView.setHasFixedSize(false);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener(){
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
And the adapter
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public TextView mTextView1;
public ImageView mDeleteName;
public ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.name_added);
mDeleteName = itemView.findViewById(R.id.delete_name);
mDeleteName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onDeleteClick(position);
}
}
}
});
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mTextView1.setText(currentItem.getName1());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
So what do I need change when I want my RecyclerView to stay at the item in position 0 unless I start scrolling down?
You can scroll to the desired position on the insert:
mLayoutManager.scrollToPosition(yourPosition)
there is easy way to fix that.
do not add item at position 0 ... just reverse the default order of your recyclerView
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
yourRecyclerView.setLayoutManager(linearLayoutManager);
I see two good ways of solving this:
One: Don't hold position in your activity, but use the size of the ArrayList
public void insertItem(String name) {
mExampleList.add(new ExampleItem(name));
mAdapter.notifyItemInserted(mExampleList.size() - 1);
editTextInput.setText("");
}
Two: Move the example list and its methods into your adapter. This way you can also remove the interface for deletion and let the adapter handle it all. I also added a method to retrieve the current list of items from the adapter incase you need that data outside of the adapter.
Activity:
public class hauptseite extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ImageButton btnInput;
private EditText editTextInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
buildRecyclerView();
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
btnInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editTextInput.getText().toString();
mAdapter.insertItem(name);
}
});
}
public void removeItem(int position) {
mAdapter.notifyItemRemoved(position);
}
public void createExampleList() {
mExampleList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerName);
mRecyclerView.setHasFixedSize(false);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter();
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
And the adapter:
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public insertItem(String name) {
mExampleList.add(name);
this.notifyItemAdded(mExampleList.size() -1)
}
public removeItem(int position) {
mExampleList.remove(position);
this.notifyItemRemoved(position);
}
public ArrayList<ExampleItems> getItems() {
return mExampleList();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public TextView mTextView1;
public ImageView mDeleteName;
public ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.name_added);
mDeleteName = itemView.findViewById(R.id.delete_name);
mDeleteName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
removeItem(position);
}
}
}
});
}
}
public ExampleAdapter() {
mExampleList = new ExampleList();
}
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.
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();
}}
I am trying to reuse firebase adapter in two activities with different onClick Listener behaviors depending on both activities.
Here is the code:
public class ProductListAdapter {
private Query mQuery;
private Context mContext;
private FirebaseRecyclerAdapter<Product,ProductViewHolder> mAdapter;
public ProductListAdapter(Query query,Context context) {
mQuery = query;
mContext = context;
Update();
}
public void Update(){
mAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(
Product.class,
R.layout.list_item_product,
ProductViewHolder.class,
mQuery
){
#Override
protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
viewHolder.mProductTitle.setText(model.getProductTitle());
viewHolder.mProductDescription.setText(model.getProductDescription());
Product product = getItem(position);
viewHolder.bindView(product);
Picasso.with(mContext)
.load(model.getPhotoUrl())
.into(viewHolder.mThumbnail);
}
};
}
public RecyclerView.Adapter getAdapter(){
return mAdapter;
}
public static class ProductViewHolder extends RecyclerView.ViewHolder{
Product mProduct;
TextView mProductTitle;
TextView mProductDescription;
ImageView mThumbnail;
public ProductViewHolder(View itemView) {
super(itemView);
mProductTitle = (TextView) itemView.findViewById(R.id.product_title);
mProductDescription = (TextView) itemView.findViewById(R.id.product_description);
mThumbnail = (ImageView) itemView.findViewById(R.id.list_image);
}
public void bindView(Product product){
mProduct = product;
}
}
And This is the code in calling activity which calls the firebaseadapter class, The class is returning an adapter using getAdapter Method and which is given to recycler view:
ProductListAdapter productListAdapter =
new ProductListAdapter(query,getActivity());
RecyclerView.Adapter adapter = productListAdapter.getAdapter();
mRecyclerView.setAdapter(adapter);
You can set onClickListinner() in any element inside your viewHolder
Try something like that:
if (condition) {
viewHolder.mThumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
... doStuff
}
});
} else {
viewHolder.mThumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
... doOtherStuff
}
});
}
About the reuse, it is best to creat a class which extends FirebaseRecyclerAdapter, and them inside it define the method populateViewHolder, having this condition for each OnClickListener.
As a example:
public class RecipeAdapter extends FirebaseRecyclerAdapter<Product, ProductViewHolder>{
private static final String TAG = RecipeAdapter.class.getSimpleName();
private Context context;
public RecipeAdapter(Class<Product> modelClass, int modelLayout, Class<ProductViewHolder> viewHolderClass, DatabaseReference ref, Context context) {
super(modelClass, modelLayout, viewHolderClass, ref);
this.context = context;
}
#Override
protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
...
}
}
And then set the adapter:
mAdapter = new RecipeAdapter<Product, ProductViewHolder>(
Product.class,
R.layout.list_item_product,
ProductViewHolder.class,
mQuery,
this
)