Skip to content

Instantly share code, notes, and snippets.

@allaryin
Forked from DV8FromTheWorld/CommentsDataHandler.java
Last active August 29, 2015 14:04
Show Gist options
  • Save allaryin/9befeed26edef498a4af to your computer and use it in GitHub Desktop.
Save allaryin/9befeed26edef498a4af to your computer and use it in GitHub Desktop.
public class Comment extends DAO
{
public static final String TABLE_NAME = "comments";
public static final String COLUMN_ID = "id";
public static final String COLUMN_COMMENT = "comment";
@Override
public static String[] getCreateSQL() {
return {
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_COMMENT + " TEXT NOT NULL);"
}
}
...
}
package net.dv8tion.android.beekeeper.datahandler;
import java.util.ArrayList;
import java.util.List;
import net.dv8tion.android.beekeeper.MySQLiteHelper;
import net.dv8tion.android.beekeeper.datatype.Comment;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class CommentsDataSource
{
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { Comment.COLUMN_ID, Comment.COLUMN_COMMENT };
public CommentsDataSource(Context context)
{
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException
{
database = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public Comment createComment(String comment)
{
ContentValues values = new ContentValues();
values.put(Comment.COLUMN_COMMENT, comment);
long insertId = database.insert(Comment.TABLE_NAME, null,
values);
Cursor cursor = database.query(Comment.TABLE_NAME,
allColumns, Comment.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Comment newComment = cursorToComment(cursor);
cursor.close();
return newComment;
}
public void deleteComment(Comment comment)
{
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(Comment.TABLE_NAME, Comment.COLUMN_ID
+ " = " + id, null);
}
public List<Comment> getAllComments()
{
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(Comment.TABLE_NAME,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return comments;
}
private Comment cursorToComment(Cursor cursor)
{
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
}
public class DAO {
public static abstract String[] getCreateSQL();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment