Create and Update Task Documents

Before we can view any documents, we need to create them.

Create a new task document


To create a new task, the user inputs a name into the text field. The task document is tagged with the list_id of the list it belongs to.

// Called when the text field's Return key is tapped.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSString *title = _addItemTextField.text;
    if (title.length == 0) {
        return NO;  // Nothing entered
    }
    [_addItemTextField setText:nil];
    
    // Create and save a new task:
    NSAssert(_detailItem, @"no current list");
    
    NSData *image = imageForNewTask ? [self dataForImage:imageForNewTask] : nil;
    Task *task = [_detailItem addTaskWithTitle:title withImage:image withImageContentType:ImageDataContentType];
    NSError *error;
    if ([task save:&error]) {
        imageForNewTask = nil;
        [self updateAddImageButtonWithImage:nil];
    } else {
        // [AppDelegate showAlert: @"Couldn't save new item" error: error fatal: NO];
    }
    
    return YES;
}
                      
No code example is currently available.
final EditText text = (EditText) header.findViewById(R.id.text);
text.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) &&
                (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            String inputText = text.getText().toString();
            if (inputText.length() > 0) {
                try {
                    Task.createTask(getDatabase(), inputText, mImageToBeAttached, listId);
                } catch (CouchbaseLiteException e) {
                    Log.e(Application.TAG, "Cannot create new task", e);
                }
            }
            // Reset text and current selected photo if available.
            text.setText("");
            deleteCurrentPhoto();
            return true;
        }
        return false;
    }
});
        
final EditText text = (EditText) header.findViewById(R.id.text);
text.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) &&
                (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            String inputText = text.getText().toString();
            if (inputText.length() > 0) {
                try {
                    Task.createTask(getDatabase(), inputText, mImageToBeAttached, listId);
                } catch (CouchbaseLiteException e) {
                    Log.e(Application.TAG, "Cannot create new task", e);
                }
            }
            // Reset text and current selected photo if available.
            text.setText("");
            deleteCurrentPhoto();
            return true;
        }
        return false;
    }
});
        
No code example is currently available.

Eventually the model object writes to the database.

- (instancetype) initInList: (List*)list
                  withTitle: (NSString*)title
                  withImage: (NSData*)image
       withImageContentType: (NSString*)contentType {
    NSAssert(list, @"Task must have a list");
    self = [super initInDatabase: list.document.database withTitle: title];
    if (self) {
        self.list_id = list;
        
        if (image) {
            [self setAttachmentNamed:kTaskImageName withContentType:contentType content:image];
        }
    }
    return self;
}
                              
No code example is currently available.
public static Document createTask(Database database,
                                      String title,
                                      Bitmap image,
                                      String listId) throws CouchbaseLiteException {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        Calendar calendar = GregorianCalendar.getInstance();
        String currentTimeString = dateFormatter.format(calendar.getTime());
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("type", DOC_TYPE);
        properties.put("title", title);
        properties.put("checked", Boolean.FALSE);
        properties.put("created_at", currentTimeString);
        properties.put("list_id", listId);
        Document document = database.createDocument();
        UnsavedRevision revision = document.createRevision();
        revision.setUserProperties(properties);
        if (image != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 50, out);
            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
            revision.setAttachment("image", "image/jpg", in);
        }
        revision.save();
        return document;
    }
                              
public static Document createTask(Database database,
                                      String title,
                                      Bitmap image,
                                      String listId) throws CouchbaseLiteException {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        Calendar calendar = GregorianCalendar.getInstance();
        String currentTimeString = dateFormatter.format(calendar.getTime());
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("type", DOC_TYPE);
        properties.put("title", title);
        properties.put("checked", Boolean.FALSE);
        properties.put("created_at", currentTimeString);
        properties.put("list_id", listId);
        Document document = database.createDocument();
        UnsavedRevision revision = document.createRevision();
        revision.setUserProperties(properties);
        if (image != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 50, out);
            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
            revision.setAttachment("image", "image/jpg", in);
        }
        revision.save();
        return document;
    }
                              
No code example is currently available.

Check a task checkbox


When the user touches a task, they'll expect the checkbox to toggle. The way we do this is by saving a new revision of a document with the opposite boolean value for the checked field.

// Called when a row is selected/touched.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CBLQueryRow *row = [self.dataSource rowAtIndex:indexPath.row];
    Task *task = [Task modelForDocument:row.document];
    
    // Toggle the document's 'checked' property:
    task.checked = !task.checked;
    
    // Save changes:
    NSError *error;
    if (![task save:&error]) {
//        [gAppDelegate showAlert: @"Failed to update item" error: error fatal: NO];
    }
}                              
                              
No code example is currently available.
// Task.java
public static void updateCheckedStatus(Document task, boolean checked)
        throws CouchbaseLiteException {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.putAll(task.getProperties());
    properties.put("checked", checked);
    task.putProperties(properties);
}                              
                          
// Task.java
public static void updateCheckedStatus(Document task, boolean checked)
        throws CouchbaseLiteException {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.putAll(task.getProperties());
    properties.put("checked", checked);
    task.putProperties(properties);
}                              
                          
No code example is currently available.