How to edit RecyclerView data - android

I have a RecyclerView which displays two pieces of data in each row.
Both are from a List Players.
What I need is to update the second piece of data (which is a counter, an int) each time an element is clicked.
Basically I have this players List modified, but don't know how to put it back in to the RecyclerView edited.
My Adapter Code
TextView name;
TextView counter;
CoursesViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
name = (TextView) itemView.findViewById(R.id.textName);
counter = (TextView) itemView.findViewById(R.id.textCounter);
}
[...]
#Override
public void onBindViewHolder(CoursesViewHolder holder, int position) {
Player player = mArrayCourses.get(position);
holder.name.setText(player.getName());
holder.counter.setText(String.valueOf(player.getCount()));
}
What I've tried
adapter = new CoursesAdapter(players);
myList.setAdapter(adapter);
myList.invalidate();
Edit:
// Piece of code of the activity where my RecyclerView is
myList = (RecyclerView) findViewById(R.id.playersVote);
myList.setLayoutManager(new LinearLayoutManager(this));
adapter = new CoursesAdapter(players);
myList.setAdapter(adapter);
// RecyclerView with a click listener
CoursesAdapter clickAdapter = new CoursesAdapter(players);
clickAdapter.setOnEntryClickListener(new CoursesAdapter.OnEntryClickListener() {
#Override
public void onEntryClick(View view, int position) {
// Let each player vote (ghosts too)
Player player = players.get(position);
player.incrementCount();
//Toast.makeText(ListPlayersVote.this, String.valueOf(player.getCount()), Toast.LENGTH_SHORT).show();
votes++;

Every time that your data change you should notify those changes in the adapter, using notifyDataSetChanged()
notifyDataSetChanged(): Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.
like this:
adapter = new CoursesAdapter(players);
myList.setAdapter(adapter);
....
....
adapter.notifyDataSetChanged();

Use the below code to change the particular Item in a recyclerview
public void updatedelivact(String value,int index) {
ChatMessage chatMessage = getItem(index);
Collection<Integer> readIds = chatMessage.getDeliveredIds();
readIds.add(userid);
chatMessage.setReadIds(readIds);
//To change the perticular item
notifyItemChanged(index);
}

Related

How to update recyclerview the simplest way using notifyDataSetChanged

I'm trying to update my recyclerview using notifyDataSetChanged() but it doesn't work. I am setting the adapter to the recyclerview like this:
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(ctx, LinearLayoutManager.VERTICAL, false);
lstSong.setLayoutManager(mLayoutManager);
lstSong.setItemAnimator(new DefaultItemAnimator());
lstSong.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(0), true));
arrSong = new ArrayList<Song>();
arrSong = kFunc.getAllSong();
songAdapter = new SongAdapter(ctx, arrSong);
lstSong.setAdapter(songAdapter);
This lines of code displays the data. But when i add a new data and refresh the recyclerview with songAdapter.notifyDataSetChanged(); the data won't show up. I know i can display it by using setAdapter() but i want to do it properly.
I add the data before I make the refresh. This is the code:
kFunc = new Function(ctx);
Song song = new Song();
song.setTitle(title);
song.setArtist(artist);
song.setYear_released(yearReleased);
song.setAlbum(album);
song.setGenre(genre);
song.setDuration(duration);
song.setCode(code);
song.setLyrics(lyrics);
kFunc.addSong(song);
dialog.dismiss();
arrSong = kFunc.getAllSong();
songAdapter.notifyDataSetChanged();
Create a method inside adapter like
public updateItems(ArrayList<Song> songs){
arrSong=songs;
}
And while getting new values in your class call the method using adapdter object
lstSong.updateItems(arrSong);
notifyDataSetChanged();
I don't know where you added new item to RecyclerView.Adapter. This is a sample code to add and set a item. More detail Sample RecyclerViewAdapter
#Override
public void addItem(M item) {
items.add(item);
notifyItemInserted(items.size() - 1);
}
#Override
public void addItem(int position, M item) {
items.add(position, item);
notifyItemInserted(position);
}
#Override
public void addAllItems(List<M> items) {
this.items.addAll(items);
notifyDataSetChanged();
}
#Override
public void setItems(List<M> items) {
this.items = items;
notifyDataSetChanged();
}
You should try by updating the list of the songs before you notify the adapter.
for example
arraySongs = <retrive updated data of the song>;
adapter.notifyDataStateChanged()
if you are in ListView which you are not but for you information only.
adapter.lstSong =<updated songs List>;
adapter.notifyDataStteChanged();
try this this worked for me.
happy coding. :)

How to update the query reference of a firebase recycler adapter when button is clicked?

I have a RecyclerView bound to a FirebaseRecyclerAdapter. I need to update the data displayed based on a value set by the user using Edittext and called function using button. data is only updated when i resume activity from recents.
Something like this:
public void refreshadappter(String url)
{
adapter = new FirebaseRecyclerAdapter<Home,HomeViewHolder>(
Home.class,
R.layout.home_card,
HomeViewHolder.class,
mDatabaseReference.orderByChild("name").equalTo(url)
) {
#Override
protected void populateViewHolder(HomeViewHolder viewHolder,
Home model, final int position) {
viewHolder.name.setText(model.getName());
viewHolder.religion.setText(model.getReligion());
}
};
mRecyclerView.setAdapter(adapter);
}

New arraylist item overwrites previous listview item

Currently I'm trying to send intent data from user input to display onto my custom adapter. The intent data from user input from the detailspage.java class will be sent to the listview page with custom Arrayadapter. However each time i add a new item it overwrites my previous entries. Hope some kind souls can help someone new to android.
Below are snippets of my code.
// Set a click listener on that button
btnAddData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveExercise(exerciseName);
}
});
}
private void saveExercise(String name) {
// Read from input fields
// Use trim to eliminate leading or trailing white space
String setString = mSetEditText.getText().toString().trim();
String repString = mRepEditText.getText().toString().trim();
String nameString = name;
Intent intent = new Intent(ExerciseDetailActivity.this, WorkoutSetActivity.class);
intent.putExtra("name", nameString);
intent.putExtra("set", setString);
intent.putExtra("rep", repString);
startActivity(intent);
}
The intent data will be sent to the activity page to initiate the custom ArrayAdapter.
public class WorkoutSetActivity extends AppCompatActivity {
ArrayList<WorkoutSet> workout = new ArrayList<WorkoutSet>();
/** Adapter for the ListView */
WorkoutSetAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise_list);
adapter = new WorkoutSetAdapter(this, workout);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
Intent intent = this.getIntent();
String name = intent.getExtras().getString("name");
String set = intent.getExtras().getString("set");
String rep = intent.getExtras().getString("rep");
adapter.add(new WorkoutSet(name,set,rep));
Toast.makeText(WorkoutSetActivity.this, "Workout added.", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}
Lastly the custom ArrayAdapter code. This is where I set the custom listview.
public class WorkoutSetAdapter extends ArrayAdapter<WorkoutSet> {
public WorkoutSetAdapter(Activity context, ArrayList<WorkoutSet> workout) {
super(context, 0, workout);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.activity_workout_set, parent, false);
}
WorkoutSet currentWorkout = getItem(position);
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) listItemView.findViewById(R.id.workout_name);
TextView setTextView = (TextView) listItemView.findViewById(R.id.workout_set);
TextView repTextView = (TextView) listItemView.findViewById(R.id.workout_rep);
nameTextView.setText(currentWorkout.getName());
setTextView.setText("Sets: "+ currentWorkout.getSet());
repTextView.setText("Reps: "+ currentWorkout.getRep());
return listItemView;
}
}
each time i add a new item it overwrites my previous entries
There are no "previous entries". startActivity loads an empty adapter each time and you only add one element.
What you want is a SQLite database (or any persistent storage layer, but SQLite is provided without more libraries).
On the plus side, your Intent and Adapter code look fine.
Every time,you call startActivity (), you open a new WorkoutSetActivity, it's a new WorkoutSetActivity object instance, so the arrayAdapter is also new one, it will only display the data you send this time.
If you want to display all the data, you must save the previous data to database or file. At WorkoutSetActivity onCreate (), you should get the previous data, put them and current data to the adapter.

Recyclerview not updating rows correctly when removing data from arraylist?

my RecyclerView contains Text and Delete Button when delete is clicked specific row will be deleted from ArrayList
pending.remove(p);// pending is arraylist
after this updating RecyclerView by calling this function which is inside Adapter
swap(pending);
public void swap(ArrayList<DownloadingActivity.scheduleListType> newList) {
if (pendingList != null) {
pendingList.clear();
pendingList.addAll(newList);
} else {
pendingList = newList;
}
notifyDataSetChanged();
}
but the problem is that correct item deleted successfully from ArrayList pending but on RecyclerView wrong update is displayed.
if i delete second item from array list pending but in RecyclerView updated
deleted item is last
when activity is reloaded then values in RecyclerView are showing correctly
searched lot of about it but did not found any way to solve
Instaead of using swap() to delete the item from your array list and adding them back into diffrent array list, I will suggest that you use notifyItemRemoved in your adapter. So, your adapter will look like below.
RecyclerViewAdapter.java :
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
DownloadingActivity.scheduleListType> p = pendingList.get(position);
//....
//....
holder.deleteBnt.setOnClickListner(new View.OnClickListener() {
#Override
public void onClick(View view) {
pendingList.remove(p);
notifyItemRemoved(position)
}
})
}

recyclerView ClickListener return null after notifyDataSetChanged()

i am using a recyclerView and loading the data from database.The recyclerView item have 2 buttons. The recyclerView loads fine and clicks work fine for the following code.
allData=db.getCatData(CATEGORYLIST_CIDD,1);
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
later i rearrange the adapter data for displaying the data in descending order by using this code
db=new DatabaseHandler(getActivity().getApplicationContext());
allData=db.getCatData(CATEGORYLIST_CIDD,order_id);
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
textlistadapter.notifyDataSetChanged();
Now the items are rearranged on the recyclerView, but the onShareButtonClickListener returns null, here is the code of the adapter.
private OnShareButtonClickListener onShareButtonClickListener;
public interface OnShareButtonClickListener {
void onItemClick(View view, Pojo obj, int position);
}
public void setOnShareButtonClickListener(final OnShareButtonClickListener onShareButtonClickListener) {
this.onShareButtonClickListener = onShareButtonClickListener;
}
the click listener code is here
holder.bt_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Share Clicked", Snackbar.LENGTH_SHORT).show();
if (onShareButtonClickListener != null) {
onShareButtonClickListener.onItemClick(view, c, position);
}
}
});
The click does not work since the onShareButtonClickListener is null.
The same code works well for the first time and once i change the order then the click events are not working, all other functions are working well.
you should only need to do this once:
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
later on, if you want to update/change the data, then you should do something like this:
textlistadapter.setListItems(allData);
textlistadapter.notifyDataSetChanged();
Where setListItems() is a public method in your adapter, an example like this:
public void setListItems(List<> allData) {
this.data.clear();
this.data.addAll(allData);
}
It's easy to understand what you are doing wrong. You populate an array which will feed your adapter with data, that meaning that, after setting the adapter, if you want it's data to change, you only need to change the array you populated the data with, and notify the adapter for the data change.
For example:
myData = db.getData();
myAdapter = new MyAdapter(this,myData);
recyvlerview.setAdapter(myAdapter);
Now every time you want to change the data, you only need to change your myData and notifity the adapter
myAdapter.notifyDataSetChange();
Basically instead of doing this:
db=new DatabaseHandler(getActivity().getApplicationContext());
allData=db.getCatData(CATEGORYLIST_CIDD,order_id);
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
textlistadapter.notifyDataSetChanged();
This should suffice
db=new DatabaseHandler(getActivity().getApplicationContext());
allData=db.getCatData(CATEGORYLIST_CIDD,order_id);
textlistadapter.notifyDataSetChanged();

Categories

Resources