Android如何在Fragment上刷新ListView

时间:2013-12-04 19:00:06

标签: android listview android-fragments

我有一个应用程序,其中navigatoin标签处理为碎片。我的一个片段包含一个列表视图。但是,listview不会刷新。 DatabaseManager具有添加或游标操作。 DatabaseManager和Gelirler不同的类。

DatabaseManager.java

public class DatabaseManager {

  private DatabaseHelper helper;
  @SuppressWarnings("unused")
  private Context context;
  private Gelirler gelir;

public DatabaseManager(Context context) {
    this.context = context;
    helper = new DatabaseHelper(context);

}

public Cursor sorgulaGelirler() {
    SQLiteDatabase db = helper.getReadableDatabase();
    Cursor cursor = db.query(DatabaseContract.Gelir.TABLE_NAME, DatabaseContract.Gelir.FULL_PROJECTION, null, null, null, null, null);
    return cursor;
}

public void ekleGelir(float tutar, String aciklama) {

    SQLiteDatabase db = helper.getWritableDatabase();   

    ContentValues satir = new ContentValues();
    satir.put("tutar", tutar);
    satir.put("aciklama", aciklama);

    db.insert(DatabaseContract.Gelir.TABLE_NAME, null, satir);

    //presumably here refresh code. Example;
    //Gelirler gelirler = new Gelirler();
    //gelirler.refresh();
    }
}

Gelirler.java

public class Gelirler extends Fragment{


private DatabaseManager manager;
public SimpleCursorAdapter adapterGelir;
private Cursor cursorGelir;
private DatabaseHelper helper;


private ViewGroup root;

public static Fragment newInstance(Context context) {
    Gelirler f = new Gelirler();
    return f;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {  
    root = (ViewGroup) inflater.inflate(R.layout.gelirler, null);


    String[] from_gelir = DatabaseContract.Gelir.from_gelir;
    int[] to_list = DatabaseContract.Gelir.to_list;

    manager = new DatabaseManager(this.getActivity());
    cursorGelir = manager.sorgulaGelirler();

    adapterGelir = new SimpleCursorAdapter(this.getActivity().getApplicationContext(),R.layout.list, cursorGelir, from_gelir, to_list, 0);

    ListView listGelir = (ListView) root.findViewById(R.id.hadi);
    listGelir.setAdapter(adapterGelir);

    return root;
}

@SuppressWarnings("deprecation")
public void refresh(){
    //manager = new DatabaseManager(this.getActivity());
    //cursorGelir = manager.sorgulaGelirler();
    //cursorGelir.requery();
    adapterGelir.notifyDataSetChanged();

}

2 个答案:

答案 0 :(得分:0)

执行任何数据库操作后:

ekleGelir(); //database operation
Cursor cursor = manager.sorgulaGelirler();
adapterGelir.changeCursor(cursor);

答案 1 :(得分:0)

尝试重新查询并将该数据再次设置为适配器内部刷新方法。

public void refresh(){manager = new DatabaseManager(this.getActivity()); cursorGelir = manager.sorgulaGelirler(); adapterGelir = new SimpleCursorAdapter(this.getActivity()。getApplicationContext(),R.layout.list,cursorGelir,from_gelir,to_list,0); ListView listGelir =(ListView)root.findViewById(R.id.hadi); listGelir.setAdapter(adapterGelir); }