Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample : Data persistence with local database #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import com.yalantis.beamazingtoday.ui.widget.BatRecyclerView;
import com.yalantis.beamazingtoday.util.TypefaceUtil;

import java.util.ArrayList;
import java.util.List;

/**
Expand All @@ -31,8 +30,11 @@ public class ExampleActivity extends AppCompatActivity implements BatListener, O
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;

private BatItemAnimator mAnimator;

private GoalDatabaseOpenHelper mDatabaseHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Expand All @@ -47,19 +49,11 @@ protected void onCreate(Bundle savedInstanceState) {
mRecyclerView = (BatRecyclerView) findViewById(R.id.bat_recycler_view);
mAnimator = new BatItemAnimator();

mDatabaseHelper = GoalDatabaseOpenHelper.getInstance(this);
mGoals = mDatabaseHelper.getGoals();

mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
add(new Goal("first"));
add(new Goal("second"));
add(new Goal("third"));
add(new Goal("fourth"));
add(new Goal("fifth"));
add(new Goal("sixth"));
add(new Goal("seventh"));
add(new Goal("eighth"));
add(new Goal("ninth"));
add(new Goal("tenth"));
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));

ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
Expand All @@ -76,19 +70,29 @@ public void onClick(View v) {

@Override
public void add(String string) {
mGoals.add(0, new Goal(string));
Goal goal = new Goal(string);
mDatabaseHelper.addGoal(goal);

mGoals.add(0, goal);
mAdapter.notify(AnimationType.ADD, 0);
}

@Override
public void delete(int position) {
Goal goal = (Goal)mGoals.get(position);
mDatabaseHelper.removeGoal(goal);

mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}

@Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
Goal goal = (Goal)mGoals.get(from);
goal.setChecked(!goal.isChecked());
mDatabaseHelper.updateCheckStatus(goal);

mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/com/yalantis/beamazingtoday/sample/Goal.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,18 @@ public class Goal implements BatModel {

private boolean isChecked;

private int id;

public Goal(String name) {
this.name = name;
}

public Goal(int id, String name, boolean isChecked) {
this.id = id;
this.name = name;
this.isChecked = isChecked;
}

public String getName() {
return name;
}
Expand All @@ -27,6 +35,10 @@ public void setChecked(boolean checked) {
isChecked = checked;
}

public int getId() { return id;}

public void setId(int id) { this.id = id; }

@Override
public boolean isChecked() {
return isChecked;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package com.yalantis.beamazingtoday.sample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.yalantis.beamazingtoday.interfaces.BatModel;

import java.util.ArrayList;
import java.util.List;

public class GoalDatabaseOpenHelper extends SQLiteOpenHelper {

private static GoalDatabaseOpenHelper sInstance;

// Database Info
private static final String DATABASE_NAME = "GoalsDatabase";
private static final int DATABASE_VERSION = 1;

// Table Names
private static final String TABLE_GOALS = "goals";

// User Table Columns
private static final String KEY_GOAL_ID = "id";
private static final String KEY_GOAL_LABEL = "label";
private static final String KEY_GOAL_CHECKED = "checked";

private GoalDatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

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

@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}

@Override
public void onCreate(SQLiteDatabase db) {

String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_GOALS +
"(" +
KEY_GOAL_ID + " INTEGER PRIMARY KEY," +
KEY_GOAL_LABEL + " TEXT," +
KEY_GOAL_CHECKED + " BOOL DEFAULT 0" +
")";

db.execSQL(CREATE_USERS_TABLE);

List<BatModel> dummyGoals = new ArrayList<BatModel>() {{
add(new Goal("first"));
add(new Goal("second"));
add(new Goal("third"));
add(new Goal("fourth"));
add(new Goal("fifth"));
add(new Goal("sixth"));
add(new Goal("seventh"));
add(new Goal("eighth"));
add(new Goal("ninth"));
add(new Goal("tenth"));
}};

for (BatModel goal : dummyGoals) {
ContentValues value = new ContentValues();
value.put(KEY_GOAL_LABEL, goal.getText());
value.put(KEY_GOAL_CHECKED, goal.isChecked());
db.insert(TABLE_GOALS, null, value);
}
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
// Will be implemented when needed
}
}

public void addGoal(Goal goal) {
// Create and/or open the database for writing
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(KEY_GOAL_LABEL, goal.getName());
values.put(KEY_GOAL_CHECKED, goal.isChecked());
db.insertOrThrow(TABLE_GOALS, null, values);

db.setTransactionSuccessful();
} catch (Exception e) {
Log.d(this.toString(), "Error while trying to add goal to database.");
} finally {
db.endTransaction();
}
}

public List<BatModel> getGoals() {
List<BatModel> goalList = new ArrayList<>();

SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_GOALS, null, null, null, null, null, null);
try {
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(KEY_GOAL_ID));
String name = cursor.getString(cursor.getColumnIndex(KEY_GOAL_LABEL));
boolean isChecked = cursor.getInt(cursor.getColumnIndex(KEY_GOAL_CHECKED)) != 0;
System.err.println(isChecked);
goalList.add(new Goal(id, name, isChecked));
} while(cursor.moveToNext());
}
} catch (Exception e) {
Log.d(this.toString(), "Error while trying to get goals from database.");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return goalList;
}

public boolean removeGoal(Goal goal) {
SQLiteDatabase db = getReadableDatabase();
String whereClause = KEY_GOAL_ID + "=?";
String[] whereArgs = new String[] { String.valueOf(goal.getId()) };
return db.delete(TABLE_GOALS, whereClause, whereArgs) != 0;
}

public boolean updateCheckStatus(Goal goal) {
SQLiteDatabase db = getReadableDatabase();
String whereClause = KEY_GOAL_ID + "=" + goal.getId();
ContentValues value = new ContentValues();
value.put(KEY_GOAL_CHECKED, goal.isChecked());
return db.update(TABLE_GOALS, value, whereClause, null) != 0;
}
}