How to reload listview on a activity? - android

I have 2 activity.
In activity 1, i have a listview show data from database and button Insert
Activity 2 use to add something to database.
When I click button ADD in activity 2, i call method finish() and return to activity 1.
So, somebody can show me how to reload listview in activity 1 please?

Recreating the adapter should help, because you need to get a new dataset as Kaaaarll said.
So for example you have something like this in your code:
MyData data = database.getData();
MyAdapter adapter = new MyAdapter(data);
ListView list = new ListView();
list.setAdapter(adapter);
and in the next run, in the onResume(), get fresh data and reapply the adapter:
MyData data = database.getData();
MyAdapter adapter = new MyAdapter(data);
list.setAdapter(adapter);

You can re-query the database to get the latest data and then repopulate your listview's adapter.

Notify the dataset in the onResume() method activity 1. It should be something like listViewAdapter.notifyDataSetChanged();. Don't forget to check whether they are null or not.
Let me know if it worked.
EDIT:
Something like this should do the work (in activity 1):
#Override
protected void onResume() {
super.onResume();
if (listViewAdapter != null) {
listViewAdapter.notifyDataSetChanged();
}
}

Related

Refresh listview data from custom ArrayAdapter which is populated by SQLite Database

I have a custom ArrayAdapter which is set to a listview with data from database:
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, database.getAll());
listview.setAdapter(adapter);
Now, I want when the user deletes a database item the listview should refresh.
Until now, I can successfully delete the item from the database, but it remains in the listview. In the ArrayAdapter class I call refresh() method from a new class same to adapter's parent class
public void refresh(){
ParentClass class_par = new ParentClass();
class_par.refreshfromParent();
}
And in the ParentClass I have a new method: refreshfromParent()
public void refreshfromAlarm(){
DatabaseHandler database = new DatabaseHandler(myview.getContext());
listview.setAdapter(new CustomAdapter(myview.getContext(), -1, database.getAll())); // here I change listview adapter, and populate it with new database data, but I get NullPointerException
}
So, how can I refresh listview items? Please, DO NOT mention notifyDataSetChanged(), it DOES NOT work.
here you making en error
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, database.getAll());
listview.setAdapter(adapter);
//so first you should make an arrayList and define it globally like
// ArrayList <yourType>list = new ArrayList<>();
//then initialize your adapter like this
list.addAll(databse.getAll());
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, list);
listview.setAdapter(adapter);
// now when you want to delete an item
// delete it from your list like list.remove(location)
// and also delete same item from your datebase
// after that just call this
notifyDataSetChanged();
I realized that notifyDataSetChanged is a big trouble, so I decided to close and reload my fragment which contains my listview. Thus, the result looks the same with DataSetChanged and there is no difference in the users' eyes. I suggest everyone who reaches in this question do the same.

Update bundle data of tabs frgament onResume

i can't solve this problem.
I have one activity : PdvActivity with a viewPager.
This activity gets a list of data and set this data to the TabsPagerAdapter.
TabsPagerAdapter create 3 tabs fragments and pass the data in their bundle.
The first tab has a gridView with items from the list he received from the bundle.
I click on an item and an activity start ... when activity finish i need to refresh this grid.
I did :
PdvActivity onResume : i read the fresh data, i set the data in the adapter and i set again the adapter to the pager
Panel[] panels = DB.getPdvPanels(pdv.id, true, activity_list);
Company company = DB.getCompany(panels[0].attivita.company_id);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
mAdapter.setPdv(pdv);
mAdapter.setActivities(panels);
mAdapter.setCompany(company);
viewPager.setAdapter(mAdapter);
In the first Tab onResume :
#Override
public void onResume() {
super.onResume();
Panel[] array_panel = (Panel[])getArguments().getParcelableArray("attivita");
gridview = (GridView)rootView.findViewById(R.id.gridView);
gridview.setAdapter(new AttivitaPdvAdapter(getActivity(), array_panel));
gridview.invalidateViews();
}
PdvActivity gets the fresh data, but the grid refresh itself with old data from bundle. And nothing change.
What i am missing ?
Thanks in advice
I could not find a way to update the bundle.
So i changed my code in a way that i think is a workaround.
Instead of refresh data in the main activity i moved that piece into the fragment.
Now in the bundle i pass only the arguments needed to do the query and i instantiate the DB inside the fragment to do the query.
#Override
public void onResume() {
super.onResume();
Panel[] array_panel = (Panel[])getArguments().getParcelableArray("attivita");
gridview = (GridView)rootView.findViewById(R.id.gridView);
gridview.setAdapter(new AttivitaPdvAdapter(getActivity(), array_panel));
gridview.invalidateViews();
}
to that :
#Override
public void onResume() {
super.onResume();
ArrayList<Attivita> activity_list = (ArrayList<Attivita>)getArguments().get("attivita");
panels = DB.getPdvPanels(pdv.id, true, activity_list);
gridview = (GridView)rootView.findViewById(R.id.gridView);
gridview.setAdapter(new AttivitaPdvAdapter(getActivity(), panels));
gridview.invalidateViews();
}
I dont know if is a good solution, or if there is a better way.
But it works, and it seems ok for me.
Hope it will helps you.

ListView items not getting populated when activity is launched

Here is my scenario:
I have a MainActivity and a CustomListViewActivity. In my MainActivity, I have 1 button and 1 spinner. On click of the button, I pass the selected spinner value to the CustomListViewActivity via Bundle and using Intents.
Now, in my CustomListViewActivity, I have a ListView that uses ArrayAdapter for populating it. I send a ArrayList from MainActivity, say for example
items = [abc]
In my CustomListViewActivity, I receive the same and use it to populate my ListView. The first time I do this, my value gets populated. The second time I do the same, the value existing is now replaced with the new one and the ListView shows one item instead of showing two.
So basically the problem is that the ListView is not updating and not showing both the items. Instead it shows me a single item always.
Here are snippets of my code
MainActivity.java
//code inside button click
..
{
items.add(spinner1.getSelectedItem().toString());
Bundle bundle =new Bundle();
bundle.putStringArrayList("data",items);
Intent i = new Intent(MainActivity.this,MyListViewActivity.class);
i.putExtras(bundle);
startActivity(i);
finish();
}
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
Log.i("App","onSave");
icicle.putStringArrayList("data",items);
}
#Override
protected void onRestoreInstanceState(Bundle icicle2) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(icicle2);
Log.i("App","onRestore");
icicle2.putStringArrayList("data",items);
}
MyListViewActivity.java
private ArrayList<String> myItems;
private static String[] titles;
CustomListViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
listView = (ListView) findViewById(R.id.list1);
rowItems = new ArrayList<RowItem>();
adapter = new CustomListViewAdapter(this,R.layout.list_item, rowItems);
listView.setAdapter(adapter);
b=getIntent().getExtras();
if(b!=null)
{
myItems=b.getStringArrayList("data");
titles= new String[myItems.size()];
titles = myItems.toArray(myItems);
}
...
int i=0;
while(i<titles.length) {
item = new RowItem(titles[i]);
//rowItems.add(item);
Log.i("ROW", ""+rowItems.size());
i++;
adapter.add(item);
listView.setAdapter(adapter);
}
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
}
}
How to make the ListView maintain the current data as well reflect the added data?
Thanks in advance
EDIT : Forgot to mention one more thing. In my MyListViewActivity class I have a button above the ListView that on clicked takes me to my MainActivity so that I can add a new Item again. So when I go back to MainActivity and try and add a new Item , it's the new Item that get displayed rather than showing both the previous and the new one
You need to persist and restore your items list in MainActivity's onSaveInstanceState and onRestoreInstanceState methods.
You also probably don't need to close the MainActivity by calling finish() every time you start the ListView activity but that depends on your application.
Basically, the problem you are having is that items is being recreated with each new instance of MainActivity. Since you finish MainActivity, a new instance is used every time you access that activity (and I assume you thought that items would just keep getting items added to it).

Android adapter notifyDataSetChanged() doesn't clear previous list

I saw that there were many problems regarding notifyDataSetChanged(). I've looked through many of them and none of the solutions worked for me.
I am using ArrayList to set my list, and after my ArrayList is updated, i ran notifyDataSetChanged(). The new list is added onto the previous one.
lets say first list is a,b and new list is a,b,c. what i get in the end is a,b,a,b,c.
and each time updating this happens again with the new list.
I've tried other such as invalidate(), adapter clear(), refreshDrawableState() etc and nothing worked.
Thank you in advance.
Here is the simplified code, a note that changing MainActivity extends Activity to ListActivity crashes the program even after i change the code in .xml file.
public class MainActivity extends Activity
{
ArrayList<String> names = new ArrayList<String>();
ArrayAdapter arrayAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv1 = (ListView) findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, names);
lv1.setAdapter(arrayAdapter);
}
//code here to edit the ArrayList names.
public void onResume()
{
super.onResume(); // Always call the superclass method first
//the activity need to be updated everytime it resumes.
arrayAdapter.notifyDataSetChanged();
}
}
Seems like you are not properly updating the array list. Please try logging the array list contents after updating.

How to add more item in a list view without refreshing the previous item

I have a listview in which i am adding some data after fixed interval.but I don't want to set the adapter again as it will refresh the complete list.Is there any method to add item without refreshing the complete list.
Thanks in advance.
You probably want to use the following (in RecycleView not ListView):
notifyItemInserted(0);//NOT notifyDataChanged()
recyclerViewSource.scrollToPosition(0);
//Scroll up, to use this you'll need an instance of the adapter's RecycleView
You can call adapter.notifyDataSetChanged() to just update the list.
Adapter's getView() is called at different times and there is no particular pattern. So your views are updated whenever ListView wants it to be updated.
But as far as I see it, you are looking for adapter.notifyDataSetChanged. The workflow should be something like this.
Set adapter to ListView
Add data to adapter`
Call notifyDataSetChanged() on adapter.
It will at least prevent your list to bounce back to first item on the list.
Hope that helps.
you can use this .notifyDataSetChanged()
However notifyDataSetChanged() only works For an ArrayAdapter,if you use the add, insert, remove, and clear functions on the Adapter.
You can use
adapter.add(<new data item>); // to add data to your adapter
adapter.notifyDatasetChanged(); // to refresh
For eg.
ArrayAdapter<String> adapter;
public void onCreate() {
....
....
ArryList<String> data = new ArrayList<String>();
for(int i=0; i<10; i++) {
data.add("Item " + (i+1));
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
setListAdapter(adapter);
}
Now whenever you have new data to be added to list you can do following
private void appendToList(ArrayList<String> newData) {
for(String data : newData)
adapter.add(data);
adapter.notifyDatasetChanged();
}

Categories

Resources