I thought I would just post a really simple wrapper for those who don't want to implement the retarded SqliteOpenHelper, which is really, really stupid.
Below is a class to open/create a database, create/insert/delete with sql queries and performing select queries and returning a general object struct (similar to NSDictionary):
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class SQLWrapper
{
SQLiteDatabase db;
public SQLWrapper(String filename, Context context)
{
db = context.openOrCreateDatabase(filename, SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
}
public void createInsertDelete(final String query)
{
System.out.println("AFSQL: Will create/insert/delete...");
db.execSQL(query);
}
public List<ColumnValue[]> select(final String query)
{
System.out.println("AFSQL: Will select...");
List<ColumnValue[]> result = null;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst())
{
result = new ArrayList<ColumnValue[]>();
do
{
int columns = cursor.getColumnCount();
ColumnValue[] cvarray = new ColumnValue[columns];
for (int i=0; i<columns; i++)
{
String key = cursor.getColumnName(i);
String value = cursor.getString(i);
ColumnValue cv = new ColumnValue(key, value);
cvarray[i] = cv;
}
result.add(cvarray);
}
while (cursor.moveToNext());
}
cursor.close();
return result;
}
public void close()
{
db.close();
}
// Custom class for return values
public class ColumnValue
{
public String column, value;
public ColumnValue(String c, String v)
{
column = c; value = v;
}
}
}
Example of usage:
private void sql_wrapper_test()
{
try
{
final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS name_table (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);";
final String INSERT_DATA = "INSERT INTO name_table (name) VALUES ('Hello, my name is Bob.');";
final String SELECT_DATA = "SELECT * FROM name_table;";
SQLWrapper sql = new SQLWrapper("mydatabasefilename", this);
sql.createInsertDelete(CREATE_TABLE);
sql.createInsertDelete(INSERT_DATA);
List<ColumnValue[]> result = sql.select(SELECT_DATA);
System.out.println("Number of rows in database: " + result.size());
if (result.size() > 0)
{
for (int i=0; i<result.size(); i++)
{
ColumnValue[] cv = result.get(i);
for (int j=0; j<cv.length; j++)
{
ColumnValue tm = cv[j];
System.out.println("Column: " + tm.column + ", Value: " + tm.value);
}
}
}
sql.close();
}
catch (Exception e)
{
System.out.println("Sql failed!");
}
}
Can you think of any way where this wrapper can be even simpler? Why would anyone use SqliteOpenHelper instead of this? Why on earth should sql queries be wrapped in stupid methods? Any logical explanation would most certainly be an enlightenment.