Domanda

I'm using greenDAO for a Android project, I have to say I'm really happy with it.

Sadly, I'm currently having quite a strange problem : a NullPointerException while doing an insert, using the LocationCoordsDao, of a newly created LocationCoords object. It's only happening for this specific entity because insertions in Meal entity for example works well.

Here is my description :

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);
    }

}

And now where it fails :

@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());
}

I've tried to swap the insertions (meal before) with no effect. I've also tried all constructors for the LocationCoords entity with no more luck.

Any help would be greatly appreciated!

È stato utile?

Soluzione

You have to intiate your DAO first before you start using it. It's like this

 DevOpenHelper helper = new DaoMaster.DevOpenHelper(this.getActivity(),
            "DB name", null);
    db = helper.getWritableDatabase();
    mDaoMaster = new DaoMaster(db);
    mDaoSession = mDaoMaster.newSession();
    LocationCoordsDao mLocationCoordsDao = mDaoSession.getLocationCoordsDao();

then you can

    LocationCoords loc = new LocationCoords(null, lat, lon);
    mLocationCoordsDao.insert(loc); // init before use
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top