Created
August 31, 2015 12:42
-
-
Save zabawaba99/980ea292b305cbdd230a to your computer and use it in GitHub Desktop.
sqlite database helpers for android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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