Вылетает виджет после попытки получить экземпляр БД - PullRequest
0 голосов
/ 30 января 2019

Я создаю виджет для приложения выпечки, которое извлекает данные из БД в комнате.Если я закрываю приложение, виджет падает, и я получаю следующую ошибку

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...