11package com .blogspot .e_kanivets .moneytracker .helper ;
22
33import android .content .ContentValues ;
4+ import android .content .Context ;
45import android .database .Cursor ;
56import android .database .sqlite .SQLiteDatabase ;
67import android .util .Log ;
@@ -94,24 +95,27 @@ public List<Record> getRecords() {
9495 return records ;
9596 }
9697
97- public void addRecord (int time , int type , String title , int category_id , int price ) {
98+ public void addRecord (int time , int type , String title , String category , int price ) {
9899 //Add record to DB
99- ContentValues contentValues = new ContentValues ();
100-
101100 SQLiteDatabase db = dbHelper .getWritableDatabase ();
102101
102+ ContentValues contentValues = new ContentValues ();
103103 contentValues .put ("type" , "1" );
104104 contentValues .put ("title" , title );
105105 contentValues .put ("category_id" , 1 );
106106 contentValues .put ("price" , price );
107107
108- int Id = (int )db .insert (Constants .TABLE_RECORDS , null , contentValues );
109- Log .d (Constants .TAG , "Id = " + Id );
108+ int id = (int ) db .insert (Constants .TABLE_RECORDS , null , contentValues );
110109
111110 db .close ();
112111
112+ if (getCategoryIdByName (category ) == -1 ) {
113+ addCategory (category );
114+ }
115+ int category_id = getCategoryIdByName (category );
116+
113117 //Add record to app list
114- records .add (new Record (Id , time , type , title , category_id , price ));
118+ records .add (new Record (id , time , type , title , category_id , price ));
115119
116120 //notify observers
117121 setChanged ();
@@ -137,11 +141,52 @@ public void deleteRecordById(int id) {
137141 }
138142 }
139143
144+ public int addCategory (String name ) {
145+ //Add category to DB
146+ SQLiteDatabase db = dbHelper .getWritableDatabase ();
147+
148+ ContentValues contentValues = new ContentValues ();
149+ contentValues .put ("name" , name );
150+
151+ int id = (int ) db .insert (Constants .TABLE_CATEGORIES , null , contentValues );
152+
153+ db .close ();
154+
155+ //Add category to app list
156+ categories .add (new Category (id , name ));
157+
158+ return id ;
159+ }
160+
161+ public void deleteCategoryById (int id ) {
162+ for (Category category : categories ) {
163+ if (category .getId () == id ) {
164+ SQLiteDatabase db = dbHelper .getWritableDatabase ();
165+ db .delete (Constants .TABLE_CATEGORIES , "id=?" ,
166+ new String [] {Integer .toString (id )});
167+
168+ categories .remove (category );
169+
170+ break ;
171+ }
172+ }
173+ }
174+
140175 public String getCategoryById (int id ) {
141176 for (Category category : categories ) {
142177 if (category .getId () == id ) return category .getName ();
143178 }
144179
145180 return null ;
146181 }
182+
183+ public int getCategoryIdByName (String name ) {
184+ for (Category category : categories ) {
185+ if (category .getName ().equals (name )) {
186+ return category .getId ();
187+ }
188+ }
189+
190+ return -1 ;
191+ }
147192}
0 commit comments