Classes stored should not be abstract classes due to ClassInstantiationException
because class reflection is used to instantiate the retrieved records.
There is a work around posted here using wrapper classes but my method so far has been to store the "class", in my case serverType, as a field and when retrieving the base class passing the base class to a constructor of the wanted child class and copy it's properties.
Usage
Dao<BaseConnectionInfo, Integer> connections = DatabaseManager
.getInstance(this).getDatabaseHelper()
.getDao(BaseConnectionInfo.class);
BaseConnectionInfo connection = connections.queryForId(1);
if (connection.isServerType(BaseConnectionInfo.SERVER_TYPE_MSSQL)) {
connection = new MsSqlConnectionInfo(connection);
} else if (connection
.isServerType(BaseConnectionInfo.SERVER_TYPE_MYSQL)) {
connection = new MySqlConnectionInfo(connection);
}
BaseConnectionInfo
@DatabaseTable(tableName = "connections")
public class BaseConnectionInfo implements SqlDriverInterface {
public static final String TAG = "BaseConnection";
public static final String SERVER_TYPE_MYSQL = "MYSQL";
public static final String SERVER_TYPE_MSSQL = "MSSQL";
public static final String SERVER_TYPE_SYBASE = "SYBASE";
public static final String SERVER_TYPE_POSTGRESQL = "POSTGRESQL";
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
protected String serverType;
@DatabaseField
private String name;
...
public boolean isServerType(String serverType) {
return this.serverType.equals(serverType);
}
...
}
MySqlConnectionInfo
public class MySqlConnectionInfo extends BaseConnectionInfo {
public MySqlConnectionInfo() {
// FOR ORMLITE
serverType = SERVER_TYPE_MYSQL;
}
/**
* Constructor used to convert {@link BaseConnectionInfo} to
* {@link MySqlConnectionInfo}
*
* @param baseConnectionInfo
*/
public MySqlConnectionInfo(BaseConnectionInfo b) {
setId(b.getId());
setName(b.getName());
setHost(b.getHost());
setOptionsJson(b.getOptionsJson());
}
...
}
MsSqlConnectionInfo
public class MsSqlConnectionInfo extends BaseConnectionInfo {
public MsSqlConnectionInfo() {
// FOR ORMLITE
serverType = SERVER_TYPE_MSSQL;
}
/**
* Constructor used to convert {@link BaseConnectionInfo} to
* {@link MsSqlConnectionInfo}
*
* @param baseConnectionInfo
*/
public MsSqlConnectionInfo(BaseConnectionInfo b) {
setId(b.getId());
setName(b.getName());
setHost(b.getHost());
setOptionsJson(b.getOptionsJson());
}
...
}