Created
November 12, 2014 22:25
-
-
Save sheharyarn/37143305b6bddbf6c125 to your computer and use it in GitHub Desktop.
Java: Create Tables in SQLite beautifully
This file contains hidden or 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 SQLiteHelper extends SQLiteOpenHelper { | |
private static final String BOOK_TABLE = "books"; | |
private static final HashMap<String, String> BOOK_FIELDS = new HashMap<String, String>() {{ | |
put("title", "TEXT"); | |
put("author", "TEXT"); | |
put("sales", "INTEGER"); // Neatly write fields and their types | |
}}; | |
// ... | |
@Override | |
public void onCreate(SQLiteDatabase db) { | |
createTable(db, BOOK_TABLE, BOOK_FIELDS); // Create the table in a single, beautiful line. | |
} | |
// This function does all the dirty work | |
static public void createTable(SQLiteDatabase db, String tableName, HashMap<String, String> fields) { | |
String command = "CREATE TABLE " + tableName + " ( id INTEGER PRIMARY KEY AUTOINCREMENT"; | |
for (Map.Entry<String, String> entry : fields.entrySet()) | |
command = command + ", " + entry.getKey() + " " + entry.getValue(); | |
command = command + " )"; | |
db.execSQL(command); | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment