ORMLite на Android: невозможно получить записи в таблице
Я пытаюсь использовать ORMLite на Android. Я использую существующую базу данных SQLite, которую копирую из папки ресурсов во внешнем хранилище телефона. Эта часть работает правильно.
Мне также удалось создать DAO для одной из таблиц (она может найти таблицу, я уверен в этом), но когда я пытаюсь получить записи с помощью queryForAll в DAO, я всегда получаю 0 элементов. Я использовал метод подсчета, и я также получаю значение 0, но в этой таблице есть элементы.
Как это возможно?
Моя таблица называется "информация", и я использую этот DAO:
@DatabaseTable(tableName="info")
public class Info {
@DatabaseField
private String version;
@DatabaseField
private String kanjidic2Version;
@DatabaseField
private String kanjiVGVersion;
/**
* Gets the version.
* @return the version.
*/
public String getVersion(){
return this.version;
}
/**
* Gets the KanjiDic2 version
* @return the version.
*/
public String getKanjidic2Version(){
return this.kanjidic2Version;
}
/**
* Gets the KanjiVG version.
* @return the version.
*/
public String getKanjiVGVersion(){
return this.kanjiVGVersion;
}
У меня есть 1 строка в информационной таблице, но, похоже, приложение не может ее получить. Вот код, который я использую, чтобы получить его:
public class InfoRepository {
Dao<Info, String> infoDao;
public InfoRepository(DBHelper helper){
try{
this.infoDao = helper.getInfoDao();
}catch(SQLException e){
Log.e(getClass().getSimpleName(), e.getMessage());
}
}
/**
* Gets all the info.
* @return all the info.
*/
public List<Info> getAll(){
List<Info> infos = new ArrayList<>();
try{
long count = this.infoDao.countOf();
Log.d(getClass().getSimpleName(), "Info entry count: " +count);
infos.addAll(this.infoDao.queryForAll());
}catch(SQLException e){
Log.e(getClass().getSimpleName(), e.getMessage());
}
return infos;
}
}
Редактировать: вот код DBHelper:
public class DBHelper extends OrmLiteSqliteOpenHelper {
private final static String DB_NAME = "kanjidb.db";
private final static int DB_VERSION = 1;
private String dataDir;
private AssetManager assetManager;
private Dao<Info, String> infoDao = null;
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
this.init(context);
}
public DBHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion) {
super(context, databaseName, factory, databaseVersion);
this.init(context);
}
public DBHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion, int configFileId) {
super(context, databaseName, factory, databaseVersion, configFileId);
this.init(context);
}
public DBHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion, File configFile) {
super(context, databaseName, factory, databaseVersion, configFile);
this.init(context);
}
public DBHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion, InputStream stream) {
super(context, databaseName, factory, databaseVersion, stream);
this.init(context);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
Log.i(getClass().getSimpleName(), "Creating database...");
//TableUtils.createTable(connectionSource, Entry.class);
TableUtils.createTable(connectionSource, Info.class);
} catch (SQLException e) {
Log.e(getClass().getSimpleName(), e.getMessage());
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try{
if(oldVersion < 2){
Log.i(getClass().getSimpleName(), "Updating database...");
// Example
// "test" column has been added in version 2
this.infoDao.executeRaw("ALTER TABLE 'info' ADD COLUMN test INTEGER;");
}
}catch(SQLException e){
Log.e(getClass().getSimpleName(), e.getMessage());
}
}
@Override
public synchronized void close(){
super.close();
this.infoDao = null;
}
/**
* Gets the info DAO
* @return the info DAO.
* @throws SQLException in case of issue.
*/
public Dao<Info, String> getInfoDao() throws SQLException {
if(null == this.infoDao){
this.infoDao = getDao(Info.class);
}
return this.infoDao;
}
/**
* Initializes this object.
* @param context as the given context.
*/
private void init(Context context){
this.dataDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +"ORMLiteTest";
this.assetManager = context.getAssets();
String filePath = this.dataDir +File.separator + DB_NAME;
if(!this.exists(filePath)){
Log.d(getClass().getSimpleName(), "-- Database not found --");
getWritableDatabase();
try {
this.copyDatabaseFromAssets(filePath);
}catch(IOException e){
Log.e(getClass().getSimpleName(), e.getMessage());
}
}
}
/**
* Gets an indication whether the given database exists.
* @param dbPath as the given database path.
* @return true if it exists; otherwise false.
*/
boolean exists(String dbPath){
if(null == dbPath){
throw new NullPointerException("dbPath");
}
Log.d(getClass().getSimpleName(), "checking if this DB exists: " +dbPath);
File dbFile = new File(dbPath);
return dbFile.exists();
}
/**
* Copies the database from the assets folder.
* @param dbPath as the given database path.
* @throws IOException in case of database file not found.
*/
private void copyDatabaseFromAssets(String dbPath) throws IOException{
InputStream input = this.assetManager.open(DB_NAME);
OutputStream output = new FileOutputStream(dbPath);
Log.d(getClass().getSimpleName(), "Creating database in: " +dbPath);
byte[] buffer = new byte[1024];
int length;
while((length = input.read(buffer)) > 0){
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
}
}
У кого-нибудь есть идеи?
Спасибо!