根据datepicker更改从DB重新加载ListView内容

时间:2012-10-23 13:49:39

标签: android listview filter android-cursorloader

首先,我要说这是一个由两部分组成的问题。我有一个带有3个按钮和列表视图的活动。一个按钮打开带有日期选择器的对话框,按钮文本显示所选日期。其他2个按钮可让您分别转到上一天/下一天。 ListView应显示与所选日期对应的记录。

目前,加载活动时,按钮显示今天的日期,列表视图显示今天的数据库记录。我已经设法创建一个方法来重新启动加载器并在前一个/下一个按钮内调用它,所以当一次导航一天时,listview会更新以显示正确的记录,但是当我通过调用datepicker更改日期时对话框,我似乎找不到让它正确更新的方法 - 这是问题的第一部分。

第二部分有点难以解释。当我选择一个有4条记录的日期(列表视图中的4行)时,所有4条记录都会显示,但是例如,如果我去第二天只有2条记录(列表视图中有2条线),它将正确显示第一条记录2条记录,但接下来的2行仍显示上一日期的数据。为了更好地解释这一点,我们假设列表视图中的每一行都显示了DB记录_id号。在日期1(有4条记录)我有ID 1,2,3,4显示,但是当更改为日期2(有2条记录)时,它显示ID 5,6,3,4。

我假设通过合并一个完全清除listview内容然后重新填充新日期的方法,我可以立即解决这两个问题。我只是不确定如何做到这一点。我的代码如下:

public class FuncLogbook extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {        

Button btn_logbook_date;

LogDateDialogFragment fragDate;
Calendar now;
Date nowD, newD, PrevDate, NextDate;

int lMonth;
String strDate;

private SimpleCursorAdapter adapter;        

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView (R.layout.dash_logbook);     
    this.getListView().setDividerHeight(2);         

    ListView list = getListView();
    list.setOnItemClickListener(this);

    btn_logbook_date = (Button) findViewById(R.id.btn_logbook_date);
    now = Calendar.getInstance();
    nowD = now.getTime();

    SimpleDateFormat dFormatter = new SimpleDateFormat("dd MMM yyyy");
    strDate = dFormatter.format(nowD);
    btn_logbook_date.setText(strDate);              

    fillData();             
}       

public void modifyDate(View v) {
    int id = v.getId ();
    switch (id) {
    case R.id.btn_logbook_date :
        showDialogDate();
        break;
    case R.id.btn_logbook_prev :
        updateDatePrev();
        break;
    case R.id.btn_logbook_next :
        updateDateNext();
        break;
    }   
}

public interface LogDateDialogFragmentListener {
    public void logbookChangedDate(int year, int month, int day);
}

public void showDialogDate() {
    FragmentTransaction ftLogDate = getFragmentManager().beginTransaction();
    fragDate = LogDateDialogFragment.newInstance(this, new LogDateDialogFragmentListener() {
        public void logbookChangedDate(int year, int month, int day) {          
            now.set(Calendar.YEAR, year);
            now.set(Calendar.MONTH, month);
            now.set(Calendar.DAY_OF_MONTH, day);
            newD = now.getTime();
            SimpleDateFormat newDFormatter = new SimpleDateFormat("dd MMM yyyy");
            strDate = newDFormatter.format(newD);
            btn_logbook_date.setText(strDate);
        }}, now);
    fragDate.show(ftLogDate, "DateDialogFragment");     
}

public void updateDatePrev() {
    String prevVar[] = btn_logbook_date.getText().toString().split(" ");

    if (prevVar[1].equalsIgnoreCase("Jan")) {
        lMonth = 0;
    } else if (prevVar[1].equalsIgnoreCase("Feb")) {
        lMonth = 1;
    } else if (prevVar[1].equalsIgnoreCase("Mar")) {
        lMonth = 2;
    } else if (prevVar[1].equalsIgnoreCase("Apr")) {
        lMonth = 3;
    } else if (prevVar[1].equalsIgnoreCase("May")) {
        lMonth = 4;
    } else if (prevVar[1].equalsIgnoreCase("Jun")) {
        lMonth = 5;
    } else if (prevVar[1].equalsIgnoreCase("Jul")) {
        lMonth = 6;
    } else if (prevVar[1].equalsIgnoreCase("Aug")) {
        lMonth = 7;
    } else if (prevVar[1].equalsIgnoreCase("Sep")) {
        lMonth = 8;
    } else if (prevVar[1].equalsIgnoreCase("Oct")) {
        lMonth = 9;
    } else if (prevVar[1].equalsIgnoreCase("Nov")) {
        lMonth = 10;
    } else if (prevVar[1].equalsIgnoreCase("Dec")) {
        lMonth = 11;
    }

    int lYear = Integer.parseInt(prevVar[2]);
    int lDay = Integer.parseInt(prevVar[0]);
    now = Calendar.getInstance();
    now.set(Calendar.YEAR, lYear);
    now.set(Calendar.MONTH, lMonth);
    now.set(Calendar.DAY_OF_MONTH, lDay - 1);
    PrevDate = now.getTime();
    SimpleDateFormat prevDFormatter = new SimpleDateFormat("dd MMM yyyy");
    strDate = prevDFormatter.format(PrevDate);
    btn_logbook_date.setText(strDate);

    refillData();       
}

public void updateDateNext() {
// Same as updateDatePrev() method, but moves forward 1 day, instead of backward
}

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
}

private void fillData() {       
    String[] from = new String[] { AddDBHelper.KEY_BGL, AddDBHelper.KEY_ROWID,
            AddDBHelper.KEY_CATEG, AddDBHelper.KEY_TIME };
    int[] to = new int[] {R.id.logBGL, R.id.logRowID, R.id.logCateg, R.id.logTime };

    getLoaderManager().initLoader(0, null, this);
    adapter = new SimpleCursorAdapter(this, R.layout.logbook_item, null, from, to, 0);

    setListAdapter(adapter);
}

private void refillData() { 
    getLoaderManager().restartLoader(0, null, this);        
}

public Loader<Cursor> onCreateLoader(int id, Bundle args) { 
     String selection = AddDBHelper.KEY_DATE + "=?";
     String[] selectionArgs = { String.valueOf(btn_logbook_date.getText().toString()) };

    CursorLoader cl = new CursorLoader(this, DBProvider.CONTENT_URI,
            null, selection, selectionArgs, null);
    return cl;
}

public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    adapter.swapCursor(data);
}

public void onLoaderReset(Loader<Cursor> loader) {
    // data is not available anymore; delete reference
    adapter.swapCursor(null);
}
}

更新

显示来自ContentProvider的查询信息:

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {

    // Using SQLiteQueryBuilder instead of query() method
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();     

    // Set the DB table to query
    queryBuilder.setTables(AddDBHelper.DB_TABLE);

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
    case DBAllEntries:
        //no filter or WHERE clause
        break;
    case DBSingleEntry:
        //add ROWID filter when selecting individual item
        queryBuilder.appendWhere(AddDBHelper.KEY_ROWID + "="
                + uri.getLastPathSegment());
        break;      
    default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }

    SQLiteDatabase sqlDB = mDBP.getWritableDatabase();
    Cursor cursor = queryBuilder.query(sqlDB, projection, selection,
            selectionArgs, null, null, sortOrder);
    // Ensure potential listeners are getting notified
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
}

更新

以下对refillData()的调用与第一次更改日期有关,但无效。重新启动模拟器并再次尝试后,我能够看到2个单独日期更改的记录,但之后它不会再次更改数据。

public void showDialogDate() {
    FragmentTransaction ftLogDate = getFragmentManager().beginTransaction();
    fragDate = LogDateDialogFragment.newInstance(this, new LogDateDialogFragmentListener() {
        public void logbookChangedDate(int year, int month, int day) {          
            now.set(Calendar.YEAR, year);
            now.set(Calendar.MONTH, month);
            now.set(Calendar.DAY_OF_MONTH, day);
            newD = now.getTime();
            SimpleDateFormat newDFormatter = new SimpleDateFormat("dd MMM yyyy");
            strDate = newDFormatter.format(newD);
            btn_logbook_date.setText(strDate);

            refillData();

        }}, now);
    fragDate.show(ftLogDate, "DateDialogFragment");     
}

通过以下调用,数据在更改日期后不会更改,但是当我按下按钮再次打开日期选择器时,我可以在后台(对话框片段后面)更新列表视图。例如,我选择日期2,数据不会更改。我打开对话框后面的日期选择器和日期2数据显示。我将datepicker设置为日期3,但listview仍然显示日期2的数据。如果再次打开日期选择器,则日期3的数据将加载到对话框片段后面的背景中。

如果我在refillData()行之后或FragDate.show(...)行之前致电FragmentTransaction ftLogDate...,我会得到相同的结果。

public void showDialogDate() {
    FragmentTransaction ftLogDate = getFragmentManager().beginTransaction();
    fragDate = LogDateDialogFragment.newInstance(this, new LogDateDialogFragmentListener() {
        public void logbookChangedDate(int year, int month, int day) {          
            now.set(Calendar.YEAR, year);
            now.set(Calendar.MONTH, month);
            now.set(Calendar.DAY_OF_MONTH, day);
            newD = now.getTime();
            SimpleDateFormat newDFormatter = new SimpleDateFormat("dd MMM yyyy");
            strDate = newDFormatter.format(newD);
            btn_logbook_date.setText(strDate);              
        }}, now);
    refillData();
    fragDate.show(ftLogDate, "DateDialogFragment");     
}

1 个答案:

答案 0 :(得分:1)

FuncLogbook活动实现日期设置事件的监听器LogDateDialogFragmentListener

public class FuncLogbook extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener, LogDateDialogFragmentListener {

//...

然后,您需要在活动中实施logbookChangedDate

@Override
public void logbookChangedDate(int year, int month, int day) {          
            now.set(Calendar.YEAR, year);
            now.set(Calendar.MONTH, month);
            now.set(Calendar.DAY_OF_MONTH, day);
            newD = now.getTime();
            SimpleDateFormat newDFormatter = new SimpleDateFormat("dd MMM yyyy");
            strDate = newDFormatter.format(newD);
            btn_logbook_date.setText(strDate);
            refillData();
}

显示对话框的方法是:

public void showDialogDate() {
    FragmentTransaction ftLogDate = getFragmentManager().beginTransaction();
    fragDate = LogDateDialogFragment.newInstance(this, now);
    fragDate.show(ftLogDate, "DateDialogFragment");     
}

然后,您可以在LogDateDialogFragment回调中的onAttach或其他setter方法中将该活动注册为听众。