1

我如何获得上下文?我在这里做错了吗?

这是我在 Android 中的错误:

致命异常:主要 com.google.inject.CreationException:Guice 创建错误:1)注入构造函数时出错,java.lang.NullPointerException

public class DatabaseProvider implements Provider {

    @Inject
    protected static Provider<Context> contextProvider;
    //eror context is null
    protected Context context = contextProvider.get();

    @Override
    public DatabaseHelper get() {
        return (DatabaseHelper) OpenHelperManager
            .getHelper(context, DatabaseHelper.class);
    }
}

实现 DaoProvider:

public class DaoProvider<D extends Dao<E, ?>, E> implements Provider<D> {

@Inject
private DatabaseProvider databaseProvider;


private final Class<E> cls;

public DaoProvider(Class<E> cls) {
    this.cls = cls;
}

@Override
public D get() {

    try {
        return databaseProvider.get().getDao(cls);

    } catch (SQLException e) {
        Log.d("injection", "database provider error", e);
    }

    return null;
}

}

在模块中实现:

public class BabyModule extends AbstractModule {
@Override
protected void configure() {

        TypeLiteral<Dao<Baby, Integer>> typeLiteral = new TypeLiteral<Dao<Baby,         Integer>>(){};
        DaoProvider<Dao<Baby,Integer>, Baby> provider = new DaoProvider<Dao<Baby,Integer>, Baby>(Baby.class);
        bind(typeLiteral).toProvider(provider);
}

}

感谢帮助

4

3 回答 3

2

我有自己的解决方案。我现在得到了关于 application.class 的上下文。

public class DatabaseHelperProvider implements Provider<DatabaseHelper> {

    @Inject
    Application application;

    @Override
    public DatabaseHelper get() {

    return OpenHelperManager
            .getHelper(application.getApplicationContext(), DatabaseHelper.class);
    }
}
于 2012-03-28T07:00:41.997 回答
1

只需使用

@Inject Context context

代替

@Inject protected static Provider<Context> contextProvider; //eror context is null
protected Context context = contextProvider.get();

应该可以解决您的问题。如果它不是你为什么不懒惰地访问上下文的原因......

于 2012-03-28T07:26:40.840 回答
-1

更好的:

@Override
public DatabaseHelper get(Context context) {
     return (DatabaseHelper) OpenHelperManager.getHelper(context, DatabaseHelper.class);
}

您可以从活动中获取上下文(活动正在扩展上下文)。

于 2012-03-16T11:39:58.987 回答