如何使用SQLite的子列表填充复杂列表?

时间:2016-03-04 16:56:21

标签: java android sql sqlite

我有一个列表结构,我想从数据库填充。我已经映射了所有表格和插入方法。但是,我不知道获取所有这些数据和填充Java对象的最佳方法是什么。我有这个结构:

public class DailySchedule {
    private long id;
    private List<Task> tasks;
    private List<Plan> plans;
}

public class Task {
    private long id;
    private long duration;
    private String description;
    private Date date;
}

public class Plan {
    private long id;
    private String description;
    private Date date;
    private List<User> users;
}

public class User {
    private long id;
    private String name;
}

public class DailySchedule { private long id; private List<Task> tasks; private List<Plan> plans; } public class Task { private long id; private long duration; private String description; private Date date; } public class Plan { private long id; private String description; private Date date; private List<User> users; } public class User { private long id; private String name; }

我应该创建一个巨大的INNERJOIN并获取所有数据(包括重复信息)并尝试填充Java对象,或者我应该从每个表中获取所有Id并在Java中执行循环(使用游标)并按ID进行选择并填充表格?

1 个答案:

答案 0 :(得分:1)

我假设你有以下表格

  • daily_schedule
  • 任务
  • 计划
  • 用户

代码

public List<DailySchedule> getDailySchedules(){
    SQLiteDatabase db = getReadableDataBase();
    Cursor dailyScheduleCursor = db.rawQuery(“Select * from daily_schedule ”);
    List<DailySchedule> all = new ArrayList<>();
    While(dailyScheduleCursor.next()){
        DailySchedule dailySchedule = new DailySchedule();
        dailySchedule.setId(dailyScheduleCursor.getLong(0));
        dailySchedule.setTasks(getTasks(dailyScheduleCursor.getLong(0)));
        dailySchedule.setPlans(getTasks(dailyScheduleCursor.getLong(0)));
        all.add(dailySchedule);
      }
    db.close();
}
public List<Task> getTasks(int id ){
    SQLiteDatabase db = getReadableDataBase();
    Cursor taskCursor = db.rawQuery(“Select * from tasks where id =’”+id+”’ ”);
    List<Task> all = new ArrayList<>();
    While(taskCursor.next()){
        Task task = new task();
        task.setId(taskCursor.getLong(0));
        // set other attributes     
        all.add(task);
    }
    db.close();
   return all;


}

public List<Plan> getPlan(int id ){

    getUser(id);// get all plans
    // set user
    return plans;
}
public User(int id){
       //create user from data
    return user;
}

然后从某个地方拨打getDailySchedules()

注意如果要查看SQLite数据库内容,请使用 AndroidDBvieweR