如何在android领域中使用构造函数

ycl3bljg  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(299)

我要用 Realm 我创建了一个 provider class 保存值,但在主类中使用此类构造函数时( activity )显示此错误,请查看此图像中的错误:错误图像链接
任务提供程序类:

public class Task_Provider extends RealmObject {

    public Task_Provider() {
    }

    public String getAddTask() {
        return addTask;
    }

    public void setAddTask(String addTask) {
        this.addTask = addTask;
    }

    public long getAdded_date() {
        return added_date;
    }

    public void setAdded_date(long added_date) {
        this.added_date = added_date;
    }

    public long getWhen_date() {
        return when_date;
    }

    public void setWhen_date(long when_date) {
        this.when_date = when_date;
    }

    public boolean isComplete() {
        return complete;
    }

    public void setComplete(boolean complete) {
        this.complete = complete;
    }

    public Task_Provider(String addTask, long added_date, long when_date, boolean complete) {
        this.addTask = addTask;
        this.added_date = added_date;
        this.when_date = when_date;
        this.complete = complete;
    }

    private String addTask;
    @PrimaryKey
    private long added_date;
    private long when_date;
    private boolean complete;

}

主要活动(按钮setonclicklistener):

String addTask = dialog_edit_task.getText().toString();
long now = System.currentTimeMillis();
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(getActivity()).build();
Realm.setDefaultConfiguration(realmConfiguration);
Realm realm = Realm.getDefaultInstance();
Task_Provider task_provider = new Task_Provider(addTask, now, 0, false);

realm.beginTransaction();
realm.copyToRealm(task_provider);
realm.commitTransaction();
realm.close();

我怎样才能解决这个问题?tnx全部<3

9rygscc1

9rygscc11#

编辑:从领域2.0.0开始,构造函数就开始工作并提供默认值。
以前:

public Task_Provider(String addTask, long added_date, long when_date, boolean complete) {
    this.addTask = addTask;
    this.added_date = added_date;
    this.when_date = when_date;
    this.complete = complete;
}

这不起作用,因为领域转换器在调用前无法执行realmproxy的构造函数 super() ,所以正确的方法是

public Task_Provider() {
}

public static Task_Provider create(String addTask, long added_date, long when_date, boolean complete) {
    Task_Provider taskProvider = new Task_Provider();
    taskProvider.addTask = addTask;
    taskProvider.added_date = added_date;
    taskProvider.when_date = when_date;
    taskProvider.complete = complete;
    return taskProvider;
}

那你就可以了

Task_Provider taskProvider = Task_Provider.create(...);

相关问题