· 9 years ago · Nov 14, 2016, 03:34 PM
1package com.example.pieter.election.com.example.pieter.election.database;
2
3import android.content.ContentValues;
4import android.content.Context;
5import android.database.sqlite.SQLiteDatabase;
6import android.database.sqlite.SQLiteOpenHelper;
7
8import com.example.pieter.election.com.example.pieter.election.candidate.Candidate;
9import com.example.pieter.election.com.example.pieter.election.candidate.ElectionUtils;
10
11import java.util.List;
12
13/**
14 * Created by Pieter on 14/11/2016.
15 */
16
17public class CandidateDbHelper extends SQLiteOpenHelper {
18 private static final int DATABASE_VERSION = 1;
19 public static Context contextIn;
20 private static final String DATABASE_NAME = "election.db";
21 private static final String DICTIONARY_TABLE_CREATE =
22 "CREATE TABLE " + ElectionContract.CandidatesEntry.TABLE_NAME + " (" +
23 ElectionContract.CandidatesEntry._ID + " INTEGER PRIMARY KEY, " +
24 ElectionContract.CandidatesEntry.COL_NAME + " TEXT NOT NULL, " +
25 ElectionContract.CandidatesEntry.COL_PARTY + " TEXT NOT NULL, " +
26 ElectionContract.CandidatesEntry.COL_AGE + " INTEGER NOT NULL, " +
27 ElectionContract.CandidatesEntry.COL_VOTES + " INTEGER NOT NULL);";
28
29 public CandidateDbHelper(Context context) {
30 super(context, DATABASE_NAME, null, DATABASE_VERSION);
31 contextIn = context;
32 }
33
34 @Override
35 public void onCreate(SQLiteDatabase sqLiteDatabase) {
36 sqLiteDatabase.execSQL(DICTIONARY_TABLE_CREATE);
37 seedDatabase(sqLiteDatabase);
38
39 }
40
41 @Override
42 public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
43 sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + ElectionContract.CandidatesEntry.TABLE_NAME);
44 onCreate(sqLiteDatabase);
45 }
46
47 private void seedDatabase(SQLiteDatabase db) {
48 List<Candidate> candidates = ElectionUtils.getCandidates(contextIn);
49 ContentValues values = new ContentValues();
50
51 for (Candidate c : candidates) {
52 values.put(ElectionContract.CandidatesEntry.COL_NAME, c.getName());
53 values.put(ElectionContract.CandidatesEntry.COL_PARTY, c.getParty());
54 values.put(ElectionContract.CandidatesEntry.COL_AGE, c.getAge());
55 values.put(ElectionContract.CandidatesEntry.COL_VOTES, c.getVotes());
56 db.insert(ElectionContract.CandidatesEntry.TABLE_NAME, null,values );
57 }
58
59 }
60}