I have used Spinner in Recyclerview.I have one button in Mainactivity. when i click that button, i need get all selected item from each row of recyclerview.getSelectedItem() method will return the selected item from spinner but i think only for single item it is working.
I think no need to use setOnItemSelectedListener.
My code is :
public class MainActivity extends AppCompatActivity {
RecyclerView recycler_view;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycler_view=findViewById(R.id.recycler_view);
button = findViewById(R.id.button);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recycler_view.setLayoutManager(mLayoutManager);
setAdapter();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
private void setAdapter( ) {
recycler_view.setVisibility(View.VISIBLE);
StudentsListAdapter studentsListAdapter = new StudentsListAdapter(this);
recycler_view.setAdapter(studentsListAdapter);
// runLayoutAnimation(recycler_view, mSelectedItem);
}
}
Adapter:
public class StudentsListAdapter extends RecyclerView.Adapter<StudentsListAdapter.MyViewHolder> {
String[] list={"Microbiology","Pharmacology","Microbiology","Forensic Medicine"};
String[] studentsName={"Student1","Student2","Studen3","Student4"};
Context ctx;
private ArrayAdapter<String> dataAdapter;
public class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.text_name)
TextView text_name;
#BindView(R.id.spinner1)
Spinner spinner1;
MyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public StudentsListAdapter(Context ctx ) {
this.ctx = ctx;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.student_list_item, parent, false);
return new MyViewHolder(itemView);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, #SuppressLint("RecyclerView") final int position) {
holder.text_name.setText(studentsName[position]);
dataAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner1.setAdapter(dataAdapter);
Log.d("Holder ",""+ holder.spinner1.getSelectedItem());
}
#Override
public int getItemCount() {
return studentsName.length;
}
}
I guess you need to add an checkbox to know which of the items are selected.
Arraylist selectedStudent = new Arraylist();
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, #SuppressLint("RecyclerView") final int position) {
holder.text_name.setText(studentsName[position]);
dataAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner1.setAdapter(dataAdapter);
Log.d("Holder ",""+ holder.spinner1.getSelectedItem());
//checkbox listener
holder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (isChecked){
selectedStudent.add(studentsName[position]);
}
}
});
}
In your activity, you can access your variable selectedStudent
StudentsListAdapter studentListAdapter;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < studentListAdapter.selectedStudent.size()-1 ; i++) {
Log.d("studentSelected".""+studentListAdapter.selectedStudent.get(i));
}
}
});
Use another List with the size of the Spinner list and add the default values of each spinner to the list. Whenever you change the value in the spinner change the value in the selected values list also.
now add a new method in the adapter to get the selected values list. and call that method on the button click
Related
I wish to set onClickListeners for buttons in a spinner which is furthur inside a recyclerView.
The following is what I have built(using spinner in my case):-
(https://i.stack.imgur.com/DmyJl.jpg)
Each of the items in my recyclerView has its own spinner which contains two options for every item: Update details and Delete.
How and in which class can I set onClickListeners for these buttons so that I may be able to retrieve that which button(Update details or delete) is clicked on which item of recyclerView, so that I may be able to update/delete that particular password in my database.
My code:-
PasswordsActivity.java:-
public class PasswordsActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton FAB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passwords);
recyclerView = (RecyclerView) findViewById(R.id.password_list);
FAB = (FloatingActionButton) findViewById(R.id.buttonAdd);
getSupportActionBar().setTitle("Saved Passwords");
DBHelper helper = new DBHelper(this);
ArrayList<PasswordModel> passwordModelArrayList = new ArrayList<>();
passwordModelArrayList.clear();
passwordModelArrayList = helper.readPasswords();
PasswordAdapter passwordAdapter = new PasswordAdapter(this, passwordModelArrayList );
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(passwordAdapter);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PasswordsActivity.this, AddPasswords.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
DBHelper helper = new DBHelper(this);
ArrayList<PasswordModel> passwordModelArrayList = new ArrayList<>();
passwordModelArrayList.clear();
passwordModelArrayList = helper.readPasswords();
PasswordAdapter passwordAdapter = new PasswordAdapter(this, passwordModelArrayList );
recyclerView.setAdapter(passwordAdapter);
}
PasswordAdapter.java:-
public class PasswordAdapter extends
RecyclerView.Adapter<PasswordAdapter.MyViewHolder>{
Context context;
ArrayList<PasswordModel> arrayList;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.passwords_list, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
TextView username;
TextView password;
TextView website;
username = holder.usernameView;
password = holder.passwordView;
website = holder.websiteView;
username.setText(arrayList.get(position).getSavedUsername());
password.setText(arrayList.get(position).getSavedPassword());
website.setText(arrayList.get(position).getSavedWebsite());
}
#Override
public int getItemCount() {
return arrayList.size();
}
#Override
public long getItemId(int position) {
return position;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView usernameView;
TextView websiteView;
TextView passwordView;
public MyViewHolder(final View itemView)
{
super(itemView);
this.passwordView = (TextView)itemView.findViewById(R.id.textPassword);
this.usernameView = (TextView)itemView.findViewById(R.id.textUsername);
this.websiteView = (TextView)itemView.findViewById(R.id.textWebsite);
Spinner spinner = (Spinner)itemView.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context.getApplicationContext(), R.array.options_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
public PasswordAdapter(Context context, ArrayList<PasswordModel> arrayList)
{
this.context = context;
this.arrayList = arrayList;
}
}
Please let me know if anything else is needed as well.
Welcome to SO!
Yeah you can do it. Can you Please try changing your adapter class as following:
!!!UPDATE!!!
package com.xxx.sample;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class PasswordAdapter extends
RecyclerView.Adapter<PasswordAdapter.MyViewHolder>{
Context context;
ArrayList<PasswordModel> arrayList;
ItemClickCallBack callback;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.passwords_list, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
PaaswordModel pwdModel = arrayList.get(position);
holder.bind(pwdModel);
}
#Override
public int getItemCount() {
return arrayList.size();
}
#Override
public long getItemId(int position) {
return position;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView usernameView;
TextView websiteView;
TextView passwordView;
public MyViewHolder(final View itemView)
{
super(itemView);
this.passwordView = (TextView)itemView.findViewById(R.id.textPassword);
this.usernameView = (TextView)itemView.findViewById(R.id.textUsername);
this.websiteView = (TextView)itemView.findViewById(R.id.textWebsite);
Spinner spinner = (Spinner)itemView.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context.getApplicationContext(), R.array.options_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void bind(PaaswordModel pwdModel) {
usernameView.setText(pwdModel.getSavedUsername());
passwordView.setText(pwdModel.getSavedPassword());
websiteView.setText(pwdModel.getSavedWebsite());
itemView.setOnClickListener(view -> {
callback.onItemClickCallBack(pwdModel);
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String value = getResources().getStringArray(R.id.<value_array>)[position];
callback.onSpinnerClickCallBack();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here or leave empty
}
});
}
}
public PasswordAdapter(Context context, ArrayList<PasswordModel> arrayList, ItemClickCallBack callback)
{
this.context = context;
this.arrayList = arrayList;
this.callback = callback;
}
public interface ItemClickCallBack {
void onItemClickCallBack(PasswordModel item);
void onSpinnerClickCallBack(String item);
}
}
After that, you might find an error to your activity class in the following line:
PasswordAdapter passwordAdapter = new PasswordAdapter(this, passwordModelArrayList, <argument missing>);
PasswordActivity:
public class PasswordsActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton FAB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passwords);
.....
PasswordAdapter passwordAdapter = new PasswordAdapter(this, passwordModelArrayList, new PasswordAdapter.ItemClickCallBack{
#Override
public void onItemClickCallBack(PasswordModel model) {
// do your code using this model
}
#Override
public void onSpinnerClickCallBack(String spinnerItem) {
// do your code using this model
}
});
Or you can pass this so that you might be able to implement the callback method inside your view class or activity class, and then you will be able to get the information from the 2 (two) overrides methods which are onItemClickCallBack (from item click) and onSpinnerClickCallBack (for spinner item click). Now you should be able to do your next work from here and on. Hopefully it will help you. Happy coding.
I am using Recyclerview. I added a menu with Recyclerview. I want to make a switch case in Recyclerview. So when I click on item 1, when I click on item 2, I click on step 3. When I click on my item .. I want to call a function. Currently I tried to read the position of the items with getAdapterPosition, but the output is always -1. For example, when I click on model, when I click on model2, I want to call a function.
Main2Activity
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView navRecyclerView;
LinearLayoutManager layoutManager;
ArrayList<NavigationDataModel> arrayList = new ArrayList<>();
NavigationAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView.setNavigationItemSelectedListener(this);
navRecyclerView = findViewById(R.id.navRecyclerView);
navRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
navRecyclerView.setLayoutManager(layoutManager);
DividerItemDecoration divider = new DividerItemDecoration(
navRecyclerView.getContext(),
DividerItemDecoration.VERTICAL
);
divider.setDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.diveder_recycler));
navRecyclerView.addItemDecoration(divider);
initArray();
adapter = new NavigationAdapter(this, arrayList);
navRecyclerView.setAdapter(adapter);
private void initArray() {
NavigationDataModel model = new NavigationDataModel();
model.setIcon(R.mipmap.avatar);
model.setTitle("Hesabım");
arrayList.add(model);
NavigationDataModel model2 = new NavigationDataModel();
model2.setIcon(R.mipmap.sss3);
model2.setTitle("S.S.S");
arrayList.add(model2);
}
NavigationAdapter
public class NavigationAdapter extends RecyclerView.Adapter<NavigationAdapter.ViewHolder> {
Context context;
ArrayList<NavigationDataModel> arrayList = new ArrayList<>();
public NavigationAdapter(Context context, ArrayList<NavigationDataModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.navigationrecyclerview_adapter11, parent, false);
final ViewHolder holder = new ViewHolder(view);
holder.navTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
System.out.println("asdasdadasd" + position);
}
});
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.navIcon.setImageResource(arrayList.get(position).getIcon());
holder.navIconNew.setImageResource(arrayList.get(position).getIcon());
holder.rootView.setBackgroundColor(arrayList.get(position).getColor());
holder.navTitle.setText(arrayList.get(position).getTitle());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView navIcon, navIconNew;
TextView navTitle;
LinearLayout rootView;
public ViewHolder(View itemView) {
super(itemView);
rootView = itemView.findViewById(R.id.rootView);
navIcon = itemView.findViewById(R.id.navIcon);
navIconNew = itemView.findViewById(R.id.navIconNew);
navTitle = itemView.findViewById(R.id.navTitle);
Toast.makeText(context, String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.navIcon.setImageResource(arrayList.get(position).getIcon());
holder.navIconNew.setImageResource(arrayList.get(position).getIcon());
holder.rootView.setBackgroundColor(arrayList.get(position).getColor());
holder.navTitle.setText(arrayList.get(position).getTitle());
holder.navTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use position herer
}
});
}
I am working with recyclerview and sqlite database. i want to place a button in cardview such that whenever user clicks on that button, the respective record should be deleted from the table.
This is my adapter class for recyclerview
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private Context mContext;
private Cursor mCursor;
private butttonsAdapetrListener mlistener;
private RecyclerView.ViewHolder v;
public CardAdapter(Context context, Cursor cursor ,butttonsAdapetrListener listener){
mContext=context;
mCursor=cursor;
mlistener=listener;
}
#NonNull
#Override
public CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.mycard,parent,false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CardViewHolder holder, int position) {
if(!mCursor.moveToPosition(position)){
return;
}
String name = mCursor.getString(mCursor.getColumnIndex("NAME"));
int total = mCursor.getInt(mCursor.getColumnIndex("TOTAL"));
int bunked = mCursor.getInt(mCursor.getColumnIndex("BUNK"));
int color = mCursor.getInt(mCursor.getColumnIndex("COLOR"));
long id= mCursor.getLong(mCursor.getColumnIndex("_id"));
holder.nameText.setText(name);
holder.totalText.setText(Integer.toString(total));
holder.bunkedText.setText(Integer.toString(bunked));
holder.colorText.setBackgroundColor(color);
holder.itemView.setTag(id);
v=holder;
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
public class CardViewHolder extends RecyclerView.ViewHolder{
public TextView nameText;
public TextView totalText;
public TextView bunkedText;
public TextView colorText;
public Button delete;
public CardViewHolder(#NonNull View itemView) {
super(itemView);
nameText= itemView.findViewById(R.id.name);
totalText = itemView.findViewById(R.id.total_num);
bunkedText = itemView.findViewById(R.id.bunked_num);
colorText= itemView.findViewById(R.id.color);
delete= itemView.findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mlistener.deleteOnClick(v,getAdapterPosition());
}
});
}
}
public interface butttonsAdapetrListener{
void deleteOnClick(RecyclerView.ViewHolder v,long position);
}
public void swapCursor(Cursor newCursor){
if(mCursor!=null){
mCursor.close();
}
mCursor=newCursor;
if(newCursor!=null){
notifyDataSetChanged();
}
}
}
This is my main activity code to delete record from database
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase db;
private CardAdapter mAdapter;
private long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteOpenHelper proBunkerDatabaseHelper = new ProBunkerDatabaseHelper(this);
db = proBunkerDatabaseHelper.getWritableDatabase();
RecyclerView recyclerView = findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new CardAdapter(this, getCursor(), new CardAdapter.butttonsAdapetrListener() {
#Override
public void deleteOnClick(RecyclerView.ViewHolder v, long position) {
id = (long)v.itemView.getTag();
db.delete("MYTABLE","_id="+id,null);
mAdapter.swapCursor(getCursor());
}
});
recyclerView.setAdapter(mAdapter);
FloatingActionButton b = findViewById(R.id.fab);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,AddSubject.class);
startActivity(intent);
}
});
}
public Cursor getCursor(){
return db.query("MYTABLE",null,null,null,null,null,"_id ASC");
}
}
The main problem is the when I click on the delete button in any item it is deleting the item which is last in the cursor.
there are no compilation errors and runtime issues only the records are not deleting in correct order.
Try it like this:
Your interface:
public interface butttonsAdapetrListener{
void deleteOnClick(int id,long adapterPos);
}
Inside your CardViewHolder:
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int id = (int)view.getTag();
mlistener.deleteOnClick(id,getAdapterPosition());
}
});
In onBindViewHolder
holder.delete.setTag(id);
In MainActivity onCreate
mAdapter = new CardAdapter(this, getCursor(), new CardAdapter.butttonsAdapetrListener() {
#Override
public void deleteOnClick(int id, long position) {
db.delete("MYTABLE","_id="+id,null);
mAdapter.swapCursor(getCursor());
}
});
Another alternative
If you want your activity to be clean and not handle data from within.
Keep it for the adapter to handle the data being deleted and notifying any change.
Just create a listener for the button in the onbindviewholder method.
I'm doing a RecyclerView example. The thing is that when I add the first item on the list it shows the item correctly on the recyclerview but the next items I add aren't showing on the recycle view.
Please help me.
Adapter code is:
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
private ArrayList<Person> mData;
LayoutInflater inflater;
public PersonAdapter() {
}
public PersonAdapter(Context context, ArrayList<Person> data) {
inflater = LayoutInflater.from(context);
update(data);
}
public void update(ArrayList<Person> data) {
mData = data;
notifyDataSetChanged();
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
PersonViewHolder holder = new PersonViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
Person person = mData.get(position);
holder.ivImagen.setImageResource(R.drawable.ic_action_android);
holder.tvNombre.setText(person.getName());
holder.tvApellido.setText(person.getLast_name());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
ImageView ivImagen;
TextView tvNombre;
TextView tvApellido;
public PersonViewHolder(View itemView) {
super(itemView);
ivImagen = (ImageView) itemView.findViewById(R.id.cr_iv_imagen);
tvNombre = (TextView) itemView.findViewById(R.id.cr_tv_name);
tvApellido = (TextView) itemView.findViewById(R.id.cr_tv_last_name);
}
}}
Main Activity Code is:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ArrayList<Person> persons = new ArrayList<>();
EditText et_name;
EditText et_last_name;
RecyclerView rv_names;
PersonAdapter adapter;
Button btAgregar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.tv_name);
et_last_name = (EditText) findViewById(R.id.tv_last_name);
btAgregar = (Button) findViewById(R.id.bt_agregar);
rv_names = (RecyclerView) findViewById(R.id.rv_nombres);
LinearLayoutManager manager = new LinearLayoutManager(this);
rv_names.setLayoutManager(manager);
adapter = new PersonAdapter(this, persons);
rv_names.setAdapter(adapter);
btAgregar.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Person person = new Person(et_name.getText().toString(), et_last_name.getText().toString());
persons.add(person);
Toast.makeText(this, "Items: " + String.valueOf(persons.size()), Toast.LENGTH_SHORT).show();
} }
Try this code for onClick function
#Override
public void onClick(View v) {
Person person = new Person(et_name.getText().toString(), et_last_name.getText().toString());
persons.add(person);
adapter.update(persons);
Toast.makeText(this, "Items: " + String.valueOf(persons.size()), Toast.LENGTH_SHORT).show();
}
UPDATE:
In Adapter code, try the following changes..
public void update(ArrayList<Person> data) {
mData.clear();
mData.addAll(data)
notifyDataSetChanged();
}
In the onClick you are adding a person, but you are not passing the updated list to the adapter by calling the adapter's update method. Might this be the reason?
i just added called adapter.notifyDataSetChanged();
i made a onClickListener for my recyclerView but it just didn't work.
When i click an item from the recyclerView the log doesnt appear, the commands i put in the OnClickListener arent called ,i spend already 2-3 days to find the problem but i didn't see something wrong in my code it should cost the problem, probably its a small stupid mistake
but pls if anyone can help me get the problem i will be very happy.
In my adapter class i assigned the onClick to check and uncheck a checkbox
and in the MainActivity i assigned to save it in the dataBase
this is in my main activity
private void setUpGUI() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cardView = (CardView) findViewById(R.id.cardView);
recyclerView = (RecyclerView) findViewById(R.id.recylerView);
adapter = new ItemAdapter(new ItemAdapter.ItemClickListener() {
#Override
public void onItemClicked(TodoItem item) {
Log.d(TAG, "on item click");
Uri uri = Uri.parse(TodoItemsContentProvider.CONTENT_URI + "/" + item.getId());
getContentResolver().update(uri, item.toContentValues(), null, null);
}
});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAddItemPopup();
}
});
this is my adapter class
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private static final String TAG = "item adapter";
private List<TodoItem> items = new ArrayList<>();
private ItemClickListener itemClickListener;
public ItemAdapter(ItemClickListener listener) {
itemClickListener = listener;
}
public void addItem(TodoItem item) {
if (!items.contains(item)) {
items.add(item);
Collections.sort(items);
notifyItemInserted(items.indexOf(item));
}
}
public void addItems(Collection<TodoItem> newItems) {
for (TodoItem item : newItems) {
if (!items.contains(item)) {
items.add(item);
}
}
Collections.sort(items);
notifyDataSetChanged();
}
public TodoItem getItem(int position) {
return items.get(position);
}
public void removeItem(int position) {
items.remove(position);
notifyItemRemoved(position);
}
// This listener listens for clicks to the viewholder. The viewholder passes back the position it is.
private final ClickListener clickListener = new ClickListener() {
#Override
public void onItemClicked(int position) {
Log.d(TAG, "on click adapter");
// Get the item that was clicked
TodoItem item = items.get(position);
// Set the completed state
item.setCompleted(!item.isCompleted());
//Update the UI
notifyItemChanged(position);
// Pass the item back the the itemclicklistener
itemClickListener.onItemClicked(item);
}
};
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_list_item, parent, false);
return new ViewHolder(v, clickListener);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
TodoItem item = items.get(position);
holder.textView.setText(item.getText());
holder.subTextViewA.setText(item.getSubText());
holder.checkBox.setChecked(item.isCompleted());
//holder.backgroundLayout.setBackgroundColor(Color.parseColor("#ec48e418"));
}
#Override
public int getItemCount() {
return items.size();
}
// The view holder listens to clicks on the
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// private RelativeLayout backgroundLayout;
final TextView textView, subTextViewA;
final CheckBox checkBox;
final ClickListener clickListener;
public ViewHolder(View itemView, ClickListener clickListener) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
subTextViewA = (TextView) itemView.findViewById(R.id.subTextViewA);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBox);
//backgroundLayout = (RelativeLayout) itemView.findViewById(R.id.backgroundLayout);
itemView.setOnClickListener(this);
this.clickListener = clickListener;
}
#Override
public void onClick(View v) {
clickListener.onItemClicked(getAdapterPosition());
}
}
// Private listener fot the adapter to know about view clicks
private interface ClickListener {
void onItemClicked(int position);
}
// Public listener to pass the item back to the activity
public interface ItemClickListener {
void onItemClicked(TodoItem item);
}
}
When you click on your checkox, itemView.OnClickListener does not invoke. http://screencast.com/t/moP30Lfc49X
You can set click listener for checkbox and save (or remove) items from database like that http://screencast.com/t/Iw1K3Ld8nna
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(item, holder.checkBox.isChecked());
}
});
public interface OnItemClickListener {
void onItemClick(MainActivity.Item item, boolean save);
}
In your activity:
adapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
#Override
public void onItemClick(Item item, boolean save) {
if (save) {
// Save
} else {
// Remove from db
}
}
});