2012-03-19 61 views
0

这是我的代码:adapter.notifyDataSetChange()犯规更新我的适配器

public class ListasCompra extends ListActivity { 

private ArrayList<Lista> listaCompras = null; 
private ListaAdapter adaptador = null; 

private static ListasCompra instancia = null; 
private static Context context = null; 

private Button aceptar = null; 
private Button nueva = null; 

@Override 
public void onCreate(Bundle savedInstanceState){ 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.lista_de_listas); 

    listaCompras = LocalService.getDbListas().getListas(); 

    aceptar = (Button)findViewById(R.id.aceptarlistas); 
    aceptar.setOnClickListener(new OnClickListener(){ 
     @Override 
     public void onClick(View v) { 
      finish(); 
     } 
    }); 

    nueva = (Button)findViewById(R.id.nuevalistas); 
    nueva.setOnClickListener(new OnClickListener(){ 
     @Override 
     public void onClick(View v) { 
      startActivity(new Intent(context, NuevaLista.class)); 
      //finish(); 
     } 
    }); 

    if(listaCompras!=null){ 
     adaptador = new ListaAdapter(this, listaCompras); 
     setListAdapter(adaptador); 
    }else{ 
     listaCompras = new ArrayList<Lista>(); 
     adaptador = new ListaAdapter(this, listaCompras); 
     setListAdapter(adaptador); 
    } 

    context = this; 
    instancia = this; 
} 

/** 
* Ciclo Vida de Actividad 
*/ 

@Override 
public void onDestroy(){ 
    super.onDestroy(); 
} 

@Override 
public void onResume(){ 
    super.onResume(); 
    listaCompras = LocalService.getDbListas().getListas(); 
    adaptador = new ListaAdapter(context, listaCompras); 
    adaptador.notifyDataSetChanged(); 
} 

我想要的,是更新,每次它获取的方法“的onResume”,这是每次活动重新适配器出现的用户......

我的问题是,它不更新使用这种方法,任何人都知道为什么?

谢谢!

+0

如果onResume方法真的按照预期调用,你检查了Log吗? – dan 2012-03-19 17:35:02

+0

分享代码ListaAdapter – Blackbelt 2012-03-19 17:42:50

回答

1

每次恢复活动时都不要创建适配器。在onCreate()中创建一次,然后在onResume()中调用notifyDataSetChanged()

但是,你最大的问题是,你正在onResume()中创建一个新的适配器,并且从不将它附加到ListView!如果你必须保持你的代码IS,再加入setListAdapter(adaptador)您创建onResume()

+0

谢谢!我不知道这是以这种方式工作........现在我要改变我所有的代码来按照你的意思去做。 – zapotec 2012-03-19 17:47:02

1

新的适配器后,在你做这个onCreate(...) ...

adaptador = new ListaAdapter(this, listaCompras); 
setListAdapter(adaptador); 

在这样做时,你传递给一个参考ListView - 该参考文件是,由致电new...创建。

在你做这个onResume() ...

adaptador = new ListaAdapter(context, listaCompras); 
adaptador.notifyDataSetChanged(); 

...现在adaptador有一个新的参照新ListAdapterListView本身仍保持为您在onCreate(...)实例化的第一ListAdapter参考。

最简单的办法是从onCreate(...)中完全删除代码,并简单地让onResume()处理创建ListAdapter并调用setListAdapter(...)

+0

每次应用程序恢复时创建一个nwe适配器是相当浪费。你只需要创建一次 – Mimminito 2012-03-19 20:35:46

+0

@Mimminito:好的 - 我说错了。我总是在'onResume()'中检查一下适配器是否为null,如果需要的话,创建并设置ListView来使用它。我的观点是数据可能经常变化,所以最好在'onResume()'而不是'onCreate(...)'中做这种事情。 – Squonk 2012-03-19 20:49:57

+0

当然,有一张支票是很好的做法。我只是确保人们没有得到创建新资源的印象,每次应用程序恢复时都是很好的实践,谢谢澄清。 – Mimminito 2012-03-19 20:51:52