我正在使用greenDAO进行Android项目,我不得不说我对它非常满意。
可悲的是,我目前遇到了一个非常奇怪的问题:使用新创建的 LocationCoords 对象的 LocationCoordsDao 进行插入时出现NullPointerException。它只发生在这个特定的实体上,因为例如 Meal 实体中的插入效果很好。
这是我的描述:
public class MealsDiaryGenerator {
public static void main(String[] args) {
Schema schema = new Schema(2, "ch.cidzoo.journalibs.db");
addMeal(schema);
try {
new DaoGenerator().generateAll(schema, "../JournalIBS/src");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addMeal(Schema schema) {
Entity loc = schema.addEntity("LocationCoords");
loc.addIdProperty().autoincrement();
loc.addDoubleProperty("latitude").notNull();
loc.addDoubleProperty("longitude").notNull();
Entity meal = schema.addEntity("Meal");
meal.addIdProperty();
meal.addDateProperty("date");
Property locId = meal.addLongProperty("locationCoordsId").getProperty();
meal.addToOne(loc, locId);
}
}
现在它失败了:
@Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.i("onLocationChanged", "got a location update: lat=" + lat + " / lon=" + lon);
LocationCoords loc = new LocationCoords(null, lat, lon);
locationCoordsDao.insert(loc); //NullPointerException
Log.d("DaoExample", "Inserted new coord, ID: " + loc.getId());
Meal meal = new Meal(null, new Date(), null);
mealDao.insert(meal);
Log.d("DaoExample", "Inserted new meal, ID: " + meal.getId());
((MealAdapter)getListAdapter()).updateMeals(mealDao.loadAll());
}
我试图交换插入(之前用餐)没有效果。我也尝试过没有更多运气的LocationCoords实体的所有构造函数。
非常感谢任何帮助!
答案 0 :(得分:1)
在开始使用之前,您必须首先启动DAO。 就像这样
DevOpenHelper helper = new DaoMaster.DevOpenHelper(this.getActivity(),
"DB name", null);
db = helper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
LocationCoordsDao mLocationCoordsDao = mDaoSession.getLocationCoordsDao();
然后你可以
LocationCoords loc = new LocationCoords(null, lat, lon);
mLocationCoordsDao.insert(loc); // init before use