gpt4 book ai didi

java - 在构造函数中保存到数据库

转载 作者:行者123 更新时间:2023-12-02 11:55:12 25 4
gpt4 key购买 nike

我遇到了问题。我正在构建一个预算应用程序,因此我创建了 2 个名为“年”和“月”的类

当调用 Year 的构造函数时,我想创建 12 个 Month 对象并将它们添加到我的 SQLite 数据库中。

我将数据库类的实例设置为构造函数的参数。

年级:

public class Year implements Serializable {

private int id;
private int year;
private Month[] months;
private List<Category> categories;

public Year(int year, MyDBHandler mdb) {
this.id = mdb.getYearID();
this.year = year;
for(int i = 0; i > 12; i ++){
Month mon = new Month(mdb.getMonthID(), i, this);
mdb.addMonth(mon);
months[i] = mon;
}
mdb.close();
}

}

月份类(class):

public class Month implements Serializable{
private int id;
private String name;
private int number;
private Year year;
private List<Entry> entries;
private List<Category> categories;


public Month(int id, int nr, Year year) {
this.id = id;
String [] months = {"January", "February", "March", "April", "May", "June", "July", "August", "Septemper", "October", "November", "December"};
this.name = months[nr];
this.number = nr;
this.year = year;
categories = year.getCategories();
}

}

我的 DbHandler 类中的相关方法

public void addMonth(Month month){
ContentValues values = new ContentValues();
values.put(COLUMN_MONTH_ID, month.getId());
values.put(COLUMN_MONTH_NUMBER, month.getNumber());
values.put(COLUMN_MONTH_YEAR_ID, month.getYear().getId());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_MONTH, null, values);
}

public ArrayList<Month> getMonths() {
ArrayList<Month> list = new ArrayList<Month>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_MONTH + " WHERE 1";

Cursor c = db.rawQuery(query, null);
c.moveToFirst();

while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex(COLUMN_MONTH_NUMBER)) != null) {
int x1 = c.getInt(c.getColumnIndex("_id"));
int x2 = c.getInt(c.getColumnIndex("nr"));

Month month = new Month(x1, x2, null);
list.add(month);
c.moveToNext();
}
}
c.close();
db.close();
return list;
}

问题是,即使我可以调用创建数据库一年,我的数据库不包含月份

最佳答案

这更适合评论,但因为我没有代表:

for(int i = 0; i > 12; i ++)

应该是

for (int i = 0; i < 12; i++)

关于java - 在构造函数中保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47656758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com