Android onResume update list adapter

2019-03-24 19:23发布

问题:

I'm using a list adapter to show different stores, when someone selects a store it takes them to a new activity where they can add the store to favorite on that screen.

There is a Back button on that calls finish(); that goes back to the screen with the listview.

Now the problem is the listview isn't updated (ie. doesn't show that the store is added to favorite already). I tried this code but no luck:

@Override
public void onResume() {
    super.onResume();
    list.setAdapter(null);      
    updateMyList();
    adapter=new LazyAdapter(this, ((String[])names.toArray(new String[0])), 
        ((String[])status.toArray(new String[0])));
    list.setAdapter(adapter);
}

updateMyList() calls the server API and updates the names and status arrays.

With this code the list doesn't really update...

回答1:

You should setAdapter in your onCreate() only, inside onResume() you just had to call adapter.notifyDataSetChanged() with the new collection of data. This will refresh your ListView with the new collection of data.



回答2:

Use this code:

myList.clear();
myList.add("your array list items");            
setListAdapter(adapter);
adapter.notifyDataSetChanged();

I think this will help you.

Thanks....



回答3:

First of all u need to add the list of stores to the arraylist, submit this array list to the ADAPTER then add it to the list view

 list.setAdapter(adapter);

it will display the stores list; take onListItemClick click there u will get listItem Id; by using the list item ID u can give intent like this

Intent intent=new Intent(getApplicationContext(),------.class);
  startActivityForResult(intent);

Take a java bean /setter and getter methods class; take getter method as static, set the store name what you have created in the child activity; override method called onBackPressed(); inside of that method write

setResult(RESULT_OK);
finish();

take a method onActivityForResult() in the parent class; inside of that method

 arraylist.add(javabeanClassname.getName());

add that arraylist to the Adapter and write the code

 list.setAdapter(adapter);


回答4:

Before adding new View to listView remove all previous view

listView.removeAllViews(); 

and then add adapter class with new values. One thing make sure that your values are updated while you returning from second activity, and this code is calling.