How do I accomplish inline .puts when using ContentValues class?

32 views Asked by At

There are many classes where I can do what I call inline method calls.

I want to be able to do this with the SQLite database class ContentValues.

Right now I am doing it this way.

ContentValues cv = new ContentValues(); cv.put("column_name", columnValue); cv.put("column_name", columnValue); cv.put("column_name", columnValue);

I want to be able to do it this way.

new ContentValues().put("column_name", columnValue) .put("column_name:, columnValue) .put("column_name", columnValue);

Is this possible?

1

There are 1 answers

1
Chaosfire On

According to the docs, all put methods have a return type void, so it's not possible. The only option is to write it yourself - you can use a wrapper class of your own:

public class ContentValuesWrapper {

  private final ContentValues cv;

  private ContentValuesWrapper(ContentValues cv) {
    this.cv = cv;
  }

  public static ContentValuesWrapper wrap() {
    return wrap(new ContentValues());
  }

  public static ContentValuesWrapper wrap(ContentValues cv) {
    return new ContentValuesWrapper(cv);
  }

  public ContentValuesWrapper put(String col, Integer val) {
    this.cv.put(col, val);
    return this;
  }

  //overloads with other types, if necessary

  public ContentValues unwrap() {
    return this.cv;
  }
}

Usage:

ContentValues cv = ContentValuesWrapper.wrap()
        .put("name1", 1)
        .put("name2", 2)
        .put("name3", 3)
        .unwrap();