尝试获取数据库实例后,小部件崩溃

时间:2019-01-30 13:00:22

标签: android android-widget android-room android-context

我正在为烘焙应用程序构建一个小部件,该小部件可从ROOM数据库中检索数据。 如果我关闭应用程序,则小部件崩溃并且出现以下错误

Process: com.example.android.bakingapp, PID: 5714
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
    at com.example.android.bakingapp.DB.AppDatabase.getInstance(AppDatabase.java:26)
    at com.example.android.bakingapp.DB.RecipeRepository.<init>(RecipeRepository.java:22)
    at com.example.android.bakingapp.widget.BakingAppRemoteViewsFactory.onDataSetChanged(RecipeService.java:58)
    at android.widget.RemoteViewsService$RemoteViewsFactoryAdapter.onDataSetChanged(RemoteViewsService.java:142)
    at com.android.internal.widget.IRemoteViewsFactory$Stub.onTransact(IRemoteViewsFactory.java:50)
    at android.os.Binder.execTransact(Binder.java:731)

所以我要在空对象上调用getApplicationContext()-而空对象是我的应用程序,对吗?

我应该如何处理?我该如何获取不带getApplicationContext()

返回的对象应用程序的数据库实例

下面是发生错误的地方

public static AppDatabase getInstance(Context context){
    if (sInstance == null){
        synchronized (LOCK){
            sInstance = Room.databaseBuilder(context.getApplicationContext(),
                    AppDatabase.class, DATABASE_NAME).fallbackToDestructiveMigration()
                    .build();
        }
    }
    Log.d(LOG_TAG, "Getting the db instance");
    return sInstance;
}
public abstract RecipesDao recipesDao();

}

class BakingAppRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory{

private static String RECIPE_ID="recipe_id";
private static String RECIPE_NAME="recipe_name";
private final Context mContext;
private Recipe recipe;
private int recipeID;
private RecipeRepository recipeRepository;
private SharedPreferences sharedPreferences;
private List<Ingredient> ingredients = new ArrayList<>();

public BakingAppRemoteViewsFactory (Context context){
    mContext = context;
}

@Override
public void onCreate() {
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
}

@Override
public void onDataSetChanged() {
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    recipeID = sharedPreferences.getInt(RECIPE_ID, 0);
    recipeRepository = new RecipeRepository(BakingApp.getContext());
    recipe = recipeRepository.getCurrentRecipe(recipeID);
    ingredients = recipe.getRecipeIngredients();
}

这就是我传递给getInstance()调用的内容

public class BakingApp extends Application {
private static BakingApp mContext;
@Override
public void onCreate() {
    super.onCreate();
    mContext = this;
}
public static BakingApp getContext(){return mContext;}

public RecipeRepository(Application application){ AppDatabase appDatabase =AppDatabase.getInstance(application); recipesDao = appDatabase.recipesDao(); }

0 个答案:

没有答案