Reload recyclerview - java

I am new to android and I am having a problem reloading (rebuilding) as recyclerview after the activity is active. The activity with the recyclerview is a second activity started as an intent on the main activity. I can load it up, and show a list of items. When one of the items is clicked a third activity is launched. The problem is sometimes there are too many items on the list. I want to add a way of selecting an item more easily. I added a spinner on the same activity as the recyclerview. When an item is selected on the spinner, I want to reload a shorter version of the list, based on the spinner selection. However, I can't find a way to achieve that. Any help or suggestions pointing me in the right direction will be greatly appreciated.

as #bink said without code it's hard to help, but the idea in general is that on your spinner.setOnItemSelectedListener() you populate your recyclerView, so everytime you change the selection you get a new list depending on the choosed value.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayList<> arrayList = new ArrayList<>();
// add your items based on item spinner.itemSelected
// for(---)
adapter = new MyAdapter(context, arrayList );
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
});
You can also add a filter to your recycler view (https://medium.com/android-news/filterable-recyclerview-in-android-the-how-to-a9ade9cd26)
If you dont want to recreate all the recycler view and the list itselft, use adapter.notifyDataSetChanged();

Related

How to refresh recyclerview adapter when data changes in other fragment?

First fragment
private void initRecyclerView() {
Main.musicList = Main.songs.songs;
if ((Main.musicList != null) && (!Main.musicList.isEmpty())) {
// Connects the song list to an adapter
// (Creates several Layouts from the song list)
allSongsAdapter = new AllSongsAdapter(getActivity(), Main.musicList);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerViewSongs.setLayoutManager(linearLayoutManager);
recyclerViewSongs.setHasFixedSize(true);
recyclerViewSongs.setAdapter(allSongsAdapter);
}
}
In the first fragment i have a recyclerview which displays a list with all songs found on the device and i have an option to delete a song which changes the data in my arraylist Main.musicList by rescanning all songs on the device.
So all my other arraylists in my app still have a reference to that deleted song.
So how can i call notifySetDataChanged on all recyclerview adapters in other fragments when i delete an item in the first fragment?
Use ViewModel in your Activity which holds these fragments.
Wrap your song list in LiveData object. This can be observed by all
of your fragments depending on their lifecycle (when the fragment is
in OnResumed state, it will be automatically notified when your list
has changed)
In related fragment start to observe LiveData and on
change update your adapter.
Related topics:
https://developer.android.com/topic/libraries/architecture/livedata
https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54
Hope I could help you.
The easy way will be to use BroadcastReceiver. try this answer
You can use EventBus to trigger the method, by which reyclcer view adapter will be notified

How to get information of an Item in RecyclerView CardView Android

I have a RecyclerView which is constructed by inflating CardView Layout. This is acheived by onCreateViewHolder method. I am passing a ArrayList of data to the RecyclerView.
My requirement is, on clicking the list item, I have to load a new page which shows the details of the item clicked. For this, I need to get the id of the item clicked which is not showed in the view. In the view I have only Name and email of the item.
Let's say, the ArrayList I am passing is of type Person and Person has member variables id,name,email,education,location.
In the RecyclerView onBindViewHolderfunction, I am setting only name and email.
I need to get the id of the item, then only I can do a db command and get details of the particular person.
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.recyclerList);
rv.setAdapter(new NGOViewHolder(ArrayList()));
rv.addOnItemTouchListener( // and the click is handled
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getActivity(),NGODetails.class);
intent.putExtra("ID", (IDOfTheItemClicked));
}));
I requirement is IDOfTheItemClicked, that is passing in the above
Intent(getActivity(),NGODetails.class);
intent.putExtra("ID", (IDOfTheItemClicked));
should be the id of the item that is in the ArrayList that I have passed initially.
How can I get to send the id of the Person object which is currently showing in the view, to the next screen, on clicking the list item.
set position for each item using setTag inside onCreateViewHolder method after that when you'll click then inside onclick you get a view reference from there, get that tag and convert to int( this will give you position of view)
onCreateViewHolder(............){
View view;
view.setTag(id, position);
view.setOnTouch or Onclick(View v){
String position = v.getTag(),toString();
// get your id using this position
}
}
If you don't change the order of the items in your adapter, simply call yourArrayList.get(position).yourgetIDOfTheItemClickedMethod in the onClick.

Using custom layout rows producing unexpected errors

I am currently learning android and working on a few projects...in this one I have a list view and when I click it I pass the name of the row I click and a value from a database to my NEXT activity and that works 100%.
This is part of my main Activity on create code. where I populate the listview from my database here and other stuff.
lvUsers = (ListView)findViewById(id.lvUsers);
List<String> listUsers = dbHeplper.getAllUsers();
if(listUsers != null){
adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1, android.R.id.text1,listUsers);
// adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.test, id.movie_title,listUsers);
lvUsers.setAdapter(adapter);
lvUsers.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String product= ((TextView)view).getText().toString();
// String product= String.valueOf((TextView)findViewById(id.movie_title));
// Toast.makeText(getBaseContext(),product,Toast.LENGTH_LONG).show();
Intent x = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
x.putExtra("product", product);
startActivity(x);
}
});
This code works fine, but I have attempted to style my row myself if you look at this line. (which is commented in the main view)
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.test, id.movie_title,listUsers);.
Adding this threw the error of relativelayout cannot be cast to android widget textview on the line
String product= ((TextView)view).getText().toString();
So I took that to mean it does not know which textview I am referring to anymore. so I edited that line to
String product= String.valueOf((TextView)findViewById(id.movie_title));
because movie_title is the ID of the textview in the test layout.
The then disappeared but now when I click the row instead of getting that data I expected like row name and data from database. the textview in my second activity is displaying
"android.widget.TextView{176f155.v.Ed (more random numbers) app:id/movie_title}
(Some of the code from second activity
Intent i=getIntent();
String name = i.getStringExtra("product");
txtName.setText(name);
Like I said all these errors are occurring from me trying to implement my owned custom rows. So If anyone could point out where I went wrong while doing this I would be grateful .
Have you tried creating a custom adapter and making it extend ArrayAdapter ? You can do this easily and then inside your getView() of your custom adapter you can inflate your textview with your appropriate text . Check this : https://stackoverflow.com/a/8166802/1497188
Also String product= String.valueOf((TextView)findViewById(id.movie_title)); , this line is getting the ID of the view and not the text inside the view. The appropriate view to do it is that from inside your onItemClick() you would convert/cast your view into a textview and then do the getText().toString() on that view. Just Search online how to create custom adapters and onItemClick Listener for Adapter
EDIT:
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String data=(String)adapterView.getItemAtPosition(arg2);
This will atleast help you get the string from inside your onItemClick()

Adding custom data to ListView & ArrayAdapter items

I'm creating an Android application. Inside a Fragment I have a ListView that is populated using an ArrayAdapter and an ArrayList. I'm using android.R.layout.simple_list_item_1 for the layout for the list items. I want to have an OnItemClickListener, so that when an item is clicked it will show another Activity based on its data.
The problem is, there may be items with the same name. I'd like to attach an ID value to each of the elements, so that my code can distinguish them from each other.
My items that I use to populate the list are of a custom class to hold their data, but the important fields here are the ID and the name (which is shown in the ListView).
My code for populating the ListView:
List<String> items;
ArrayAdapter<String> adapter;
List<MyCustomDataObject> listOfDataObjects;
...
// Get the ListView
ListView list = (ListView) layoutRootView.findViewById(R.id.listView1);
// Create the item List and the ArrayAdapter for it
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
// Set the list adapter
list.setAdapter(adapter);
// Add the data items
for (MyCustomDataObject obj : listOfDataObjects) {
items.add(obj.name);
}
items.add(getResources().getString(R.string.no_items));
// Create the item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Open the Activity based on the item
}
});
How could I add an ID to the list items for identifying each item?
The solution is quite simple actually.
You're populating the ListView from a List. The List is an ordered collection of items, so when adding it as the datasource for the ListView you will always know the index of each item.
So when selecting an item from the ListView you get the position of the View clicked. This position will correspond to the position in your List.
You won't really need the id field of your MyCustomDataObject, but of course when you populate the List of MyCustomDataObject you could use a normal for-loop (not enhanced) and use the index to set the id of each MyCustomDataObject.
Lookup the position in listOfDataObjects to find the ID:
// Create the item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==listOfDataObjects.size()) { .... no_items clicked ... }
else {
MyCustomDataObject obj = listOfDataObjects.get(position);
... // Open the Activity based on the item
}
}
});

Detect click on checkbox in custom ListView layout?

I know there's tons of other threads around about this same topic, but none of them seem to work with my scenario and I couldn't get my listview to work with their code. Basically, I'm using a SimpleCursorAdapter to populate a listview with items from the database. Each listview row uses a custom layout which consists of a checkbox and a line of simple text. How do I detect a click on the checkbox? I know I need to use OnItemClickListener, but I don't know how to incorporate that into my code. Here's my code:
remindersCursorAdapter = new SimpleCursorAdapter(this,
R.xml.view_reminders_item_layout,
remindersCursor, new String [] { RemindersDAO.NAME },
new int[] { R.id.view_reminders_item_text } );
viewRemindersListView.setAdapter(remindersCursorAdapter);
R.xml.view_reminders_item_layout is the custom listview layout file. How do I capture the checkbox from this file and set a click listener to it? Thanks for all your help!
If you want to check the checkbox when a item is clicked, you can do it by setting checked status of Checkbox in onItemClick method.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// now get the checkbox view. Then set the checked status.
CheckBox checkbox = (CheckBox) view.findViewById(R.id.check_box);
checkBox.setChecked(!checkbox.isChecked());
}
If you want to detect the click on only checkbox then set the focusable true in xml.
// in your custom list view item. It takes the current view focus.
<Checkbox>
android:focusable="true"
</Checkbox>

Categories