lundi 4 avril 2016

How do I use/write/read to this Database?

I'm currently having to make an App that has to be able to write and read to and from a Database. The thing is that I have not made this Databse but it has been provided by someone in my Studygroup. It looks something like this:

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "SleepAttention.db";
    private static final String TAG = DatabaseHelper.class.getSimpleName();
    private static final int DATABASE_VERSION = 1;
    private static DatabaseHelper instance;
    private final Context context;

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    public static synchronized DatabaseHelper getInstance(Context context) {
        if(instance == null) {
            instance = new DatabaseHelper(context.getApplicationContext());
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        executeSQLScript(db, "database_setup.sql");
        Log.v(TAG, "onCreate execute setup script");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion) {
            switch (oldVersion) {
                case 1: {
                    //executeSQLScript(db, "upgade_v2.sql");
                    //DATABASE_VERSION = 2;
                }
                case 2: {
                    // Run next upgrade script;
                    break;
                }
            }
        }
    }

    private void executeSQLScript(SQLiteDatabase db, String fileName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte buffer[] = new byte[1024];
        int length;
        InputStream inputStream;
        try {
            inputStream = context.getAssets().open(fileName);
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();

            String[] createScript = outputStream.toString().split(";");
            for (String s : createScript) {
                String sqlStatement = s.trim();
                if(sqlStatement.length() > 0) {
                    db.execSQL(sqlStatement + ";");
                }
            }
        }
        catch(IOException e) {
            Log.e(TAG,"Unknown IOException: " + e.getMessage());
            e.printStackTrace();
        } catch(SQLException e) {
            Log.e(TAG, "Wrong SQL file mate: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Then he also made another class that that looks something like this:

public class SleepRepository {

    private DatabaseHelper dbHelper;
    private List<Sleep> sleepList;
    private static final String TAG = SleepRepository.class.getSimpleName();

    public SleepRepository(Context context) {
        dbHelper = DatabaseHelper.getInstance(context);
        sleepList = new ArrayList<>();
    }

    public boolean insertRecord(double duration, Date date, int quality) {
        ContentValues cv = new ContentValues();
        if (duration == 0.0 || date == null) {
            return false;
        }
        cv.put(Sleep.KEY_DURATION, duration);
        cv.put(Sleep.KEY_DATE, new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", new Locale("da", "DK")).format(date));
        cv.put(Sleep.KEY_QUALITY, quality);

        if(dbHelper.getWritableDatabase().insert(Sleep.TABLE_NAME, null, cv) == -1) {
            dbHelper.close();
            return false;
        }
        dbHelper.close();
        return true;
    }

    public boolean deleteRecord(int sleepID) {
        if (dbHelper.getWritableDatabase().delete(Sleep.TABLE_NAME, Sleep.KEY_ID + " = ?", new String[]{Integer.toString(sleepID)}) >= 1) {
            dbHelper.close();
            return true;
        }
        dbHelper.close();
        return false;
    }

    /**
     *
     * @param sleepID
     * @return
     */
    public Sleep getRecord(int sleepID) {
        return parseResults(dbHelper.getReadableDatabase().rawQuery("SELECT * FROM " + Sleep.TABLE_NAME + " WHERE " + Sleep.KEY_ID + " = ? ",
                new String[]{Integer.toString(sleepID)})).get(0);

    }

    public List<Sleep> getAllRecords() {
        return parseResults(dbHelper.getReadableDatabase().rawQuery("SELECT * FROM " + Sleep.TABLE_NAME, null));
    }

    private List<Sleep> parseResults(Cursor results) {
        List<Sleep> sleepList = new ArrayList<>();
        if(results.moveToFirst()) {
            do {
                try {
                    Sleep s = new Sleep(
                            results.getInt(results.getColumnIndex(Sleep.KEY_ID)),
                            results.getDouble(results.getColumnIndex(Sleep.KEY_DURATION)),
                            new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", new Locale("da", "DK")).parse(results.getString(results.getColumnIndex(Sleep.KEY_DATE))),
                            results.getInt(results.getColumnIndex(Sleep.KEY_QUALITY)));
                    sleepList.add(s);
                } catch(ParseException e) {
                    Log.e(TAG, "ParseException happened: " + e.getMessage());
                    e.printStackTrace();
                }
            }
            while (results.moveToNext());
        }
        else {
            sleepList.add(null);
        }
        dbHelper.close();
        results.close();
        return sleepList;
    }

    public boolean updateRecord(int sleepID, double duration, Date date, int quality) {
        ContentValues cv = new ContentValues();
        if (sleepID >= 0) {
            cv.put(Sleep.KEY_ID, sleepID);
            if(date != null) {
                cv.put(Sleep.KEY_DATE, new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", new Locale("da", "DK")).format(date));
            }
            cv.put(Sleep.KEY_QUALITY, quality);
            cv.put(Sleep.KEY_DURATION, duration);
            if(dbHelper.getWritableDatabase().update(Sleep.TABLE_NAME, cv, Sleep.KEY_ID + " = ?", new String[]{sleepID + ""}) >= 1) {
                return true;
            }
        }
        return false;
    }
}

I dont fully understand what is going on and I dont really know how to work with this. I do understand the basics of Java/Android but I haven't worked with SQLite before. I have read several tutorials about this topic, but I still cannot figure out how to implement the databse in a new Class.

I want to make a new Class that only has one button in it and when I press it, I want to save the current Time and Date to the Databse. How do I do that? Do I have to extend one of the two classes that I've posted above? How do I then read the saved data and also, where is the saved data stored at, I mean directory-wise? I would really appreciate if someone could help me out here.

Aucun commentaire:

Enregistrer un commentaire