Skip to content

Instantly share code, notes, and snippets.

@zabawaba99
Created August 31, 2015 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zabawaba99/980ea292b305cbdd230a to your computer and use it in GitHub Desktop.
Save zabawaba99/980ea292b305cbdd230a to your computer and use it in GitHub Desktop.
sqlite database helpers for android
public class DatabaseInterface extends SQLiteOpenHelper implements NewsDatabaseInterface {
public NewsDatabaseInterface newsHelper;
// Database version
private static final int DATABASE_VERSION = 1;
public DatabaseInterface(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
newsHelper = new NewsDatabaseImpl(this);
}
//in your oncreate you will write the queries to create your tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NEWS = "CREATE TABLE News(id INTEGER)";
db.execSQL(CREATE_NEWS);
}
// upgrading tables
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// drop tables if exist
db.execSQL("DROP TABLE IF EXSIST " + NEWS);
// recreate tables
onCreate(db);
}
}
public class NewsDatabaseImpl implements NewDatabaseInterface {
private SQLiteOpenHelper sqlOpener;
public NewsDatabaseImpl(SQLiteOpenHelper sqlOpener) {
this.sqlOpener = sqlOpener;
}
public ArrayList<News> getNews() {
ArrayList<News> mNewes = new ArrayList<News>();
SQLiteDatabase db = null;
Cursor cursor = null;
try {
String sQry = "SELECT * FROM " + NEWS;
db = sqlOpener.getWritableDatabase();
cursor = db.rawQuery(sQry, null);
if (cursor.moveToFirst()) {
do {
mNewes.add(new News(cursor.getInt(0)));
} while (cursor.moveToNext());
}
} catch (SQLiteException e) {
Log.e("SQLite - getNewes", e.getMessage());
return null;
} finally {
cursor.close();
db.close();
}
return mNewes;
}
}
public interface NewDatabaseInterface {
public ArrayList<News> getNews();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment