Android onResume update list adapter

2019-03-24 19:21发布

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...

4条回答
劳资没心,怎么记你
2楼-- · 2019-03-24 19:55

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.

查看更多
做自己的国王
3楼-- · 2019-03-24 19:55

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.

查看更多
beautiful°
4楼-- · 2019-03-24 20:15

Use this code:

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

I think this will help you.

Thanks....

查看更多
【Aperson】
5楼-- · 2019-03-24 20:18

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);
查看更多
登录 后发表回答