当用户关闭一个活动并返回到上一个活动时,我遇到列表刷新问题.我发现这个问题很常见,但我无法解决. 我重写了onResume方法: @Overridepublic void onResume() { super.onResume(); populateList();} popu
我重写了onResume方法:
@Override public void onResume() { super.onResume(); populateList(); }
populateList()是一个方法,我用字符串列表填充listView:
arrayAdapter = new CustomArrayAdapter(this, R.layout.symbol_item,list); listView.setAdapter(arrayAdapter);
问题是,当第二个活动关闭时,新项目将再次添加到ListView中,因此我将每个项目加倍.喜欢它没有刷新.
如果我在onResume()中放置notifyDataSetChanged(),它会抛出nullPointerException,因为当第一次启动活动时,第一次启动活动时没有初始化适配器.
我不知道如何处理这个问题.
public class testActivity extends Activity { private int id=1; private ListView listView; private CustomArrayAdapter arrayAdapter; private ArrayList<String> list = new ArrayList<String>(); ArrayList<Item> objectList = new ArrayList<Item>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); } @Override public void onResume() { super.onResume(); populateList(); } private void populateList() { try { objectList = new GetAsyncTask(id).execute(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); } int size = objectList.size(); String name; for (int i = 0; i < size; i++) { name = objectList.get(i).getName(); list.add(name); } arrayAdapter = new CustomArrayAdapter(this, R.layout.symbol_item, list); listView.setAdapter(arrayAdapter); } }好吧,你可以轻松地用一个简单的条件语句敲掉它,只有当适配器不为空时才执行命令:
if (adapter != null) { adapter.notifyDataSetChanged(); }
但在我看来,在更深层次上,您的代码可能会在某种程度上重新考虑,以提高效率,但不一定更具功能性.
像这样做:
private int id = 1; private ListView listView; private CustomArrayAdapter arrayAdapter; private ArrayList<String> list = new ArrayList<String>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); } @Override public void onResume() { super.onResume(); populateList(); } private void populateList() { ArrayList<Item> objectList; try { objectList = new GetAsyncTask(id).execute(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } list.clear(); for (int i = 0; i <objectList.size(); i++) { String name = objectList.get(i).getName(); list.add(name); } if (arrayAdapter == null) { arrayAdapter = new CustomArrayAdapter(this, R.layout.symbol_item, list); listView.setAdapter(arrayAdapter); } else { arrayAdapter.notifyDataSetChanged(); } }