getApp()
方法正在返回null
。知道为什么吗?
public class App extends Application {
private static App app;
private BoxStore boxStore;
@Override
public void onCreate() {
super.onCreate();
app = this;
boxStore = MyObjectBox.builder().androidContext(App.this).build();
if(BuildConfig.DEBUG)
{
new AndroidObjectBrowser(boxStore).start(this);
}
}
public static App getApp() {
return app;
}
public BoxStore getBoxStore() {
return boxStore;
}
}
从以下活动中调用getApp()
方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BoxStore boxStore = App.getApp().getBoxStore();
Box<ListEntryObject> listEntryObjectBox = boxStore.boxFor(ListEntryObject.class);
sharedPreferences = getSharedPreferences("TYPE_OF_ACTION", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putInt("sourceToDest", 0);
editor.apply();
sharedPreferences = getSharedPreferences("POSITION" , Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putInt("position", 0);
editor.apply();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sharedPreferences = getSharedPreferences("TYPE_OF_ACTION", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putInt("sourceToDest", 0);
editor.apply();
fragmentManager = getSupportFragmentManager();
entryDialogFragment = new EntryDialogFragment();
entryDialogFragment.show(fragmentManager, "Sample Fragment");
}
});
entryObjectList = new ArrayList<>();
}
答案 0 :(得分:2)
请务必将此类(App)链接到Manifest.xml中的应用程序标记,如下面的代码所示
<application
android:name="package.MyClass"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
...
</application>