Rassamdul
Rassamdul

Reputation: 23

Saving to database inside Constructor

I got a problem. I am building a budget app, so therefor i have created 2 classes called 'Year' and 'Month'

When my constructor for Year is called i want to create 12 objects of Month and add them to my SQLite database.

I set an instance of my database class as an paramter for the constructor.

Year class:

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();
}

}

Month 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();
}

}

Relevant methods from my DbHandler class

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;
}

The problem is that even though i can call create a year to the database, my database contains no Months

Upvotes: 0

Views: 156

Answers (1)

swit
swit

Reputation: 187

This would be more suitable for a comment, but since I don't have the rep:

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

should be

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

Upvotes: 1

Related Questions