我如何在提供程序中使用guice获取Context?

时间:2012-03-16 11:30:29

标签: android guice roboguice

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

这是我在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);
}

}

感谢您的帮助

3 个答案:

答案 0 :(得分:2)

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

public class DatabaseHelperProvider implements Provider<DatabaseHelper> {

    @Inject
    Application application;

    @Override
    public DatabaseHelper get() {

    return OpenHelperManager
            .getHelper(application.getApplicationContext(), DatabaseHelper.class);
    }
}

答案 1 :(得分:1)

只需使用

@Inject Context context

而不是

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

应该解决你的问题。如果不是为什么你不能访问上下文懒惰......

答案 2 :(得分:-1)

更好:

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

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