Android游标循环通过列

时间:2013-07-05 03:25:25

标签: android sqlite

我正在尝试更改名为“date”的列中的每个值。这基本上需要的是循环通过列并将每个条目更改为最新的一天差异。问题是我的代码不断将所有内容更改为相同的值。所以基本上即使每个条目的“剩余天数”应该是不同的,它们都归结为相同的数字。这是我的代码。

String[] projection = { HabitTable.COLUMN_ENDDATE, HabitTable.COLUMN_ID };
        //Get end date from database
        Cursor mCursor = getContentResolver().query(MyHabitContentProvider.CONTENT_URI, projection,
                null, null, null);
        //Store end date in array
        if(mCursor != null){
            do{
                endDate = mCursor.getString(mCursor.getColumnIndexOrThrow(HabitTable.COLUMN_ENDDATE));

                //Whole bunch of code to calculate days left
                String[] eDate = endDate.split("-");
                int eDay = Integer.parseInt(eDate[0]);
                int eMonth = Integer.parseInt(eDate[1]);
                eMonth--;
                int eYear = Integer.parseInt(eDate[2]);
                Calendar cNow = Calendar.getInstance();
                Calendar cEnd = Calendar.getInstance();
                cEnd.set(Calendar.DAY_OF_MONTH, eDay);
                cEnd.set(Calendar.MONTH, eMonth);
                cEnd.set(Calendar.YEAR, eYear);
                long diff = cEnd.getTimeInMillis() - cNow.getTimeInMillis();
                long days = diff / (24 * 60 * 60 * 1000);
                if(days <= 0){
                    days = 0;
                }

                String y = String.valueOf(days);

                ContentValues values = new ContentValues();
                values.put(HabitTable.COLUMN_DAYSLEFT, y);
                getContentResolver().update(MyHabitContentProvider.CONTENT_URI,values, null, null);
            }while(mCursor.moveToNext());
        }mCursor.close();

我有没有犯过任何重大错误?

1 个答案:

答案 0 :(得分:0)

我认为缺少的是要更新的ID

试试这个

 ContentValues values = new ContentValues();
 values.put(HabitTable.COLUMN_DAYSLEFT, y);
 // Apply condition here
 String where = HabitTable.COLUMN_ID+"="+mCursor.getString(mCursor.getColumnIndexOrThrow(HabitTable.COLUMN_ID));
 getContentResolver().update(MyHabitContentProvider.CONTENT_URI,values, where , null);

here就是一个很好的例子。