2012-03-19 130 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