2017-10-08 87 views
-1

getApp()方法返回null。任何想法为什么?获取App对象返回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<>(); 

} 
+1

发表你调用getApp方法的代码 –

+0

@AbdulWheheed我编辑过。请检查。 –

+0

您需要将您的应用程序类添加到清单文件android:name 为应用程序实现的Application子类的标准名称。当应用程序进程启动时,这个类在应用程序的任何组件之前被实例化。 子类是可选的;大多数应用程序不需要一个。在没有子类的情况下,Android使用基本应用程序类的实例。 – Hector

回答

2

请务必在的Manifest.xml如下代码中提到在这一类(APP)链接到应用标签

<application 
android:name="package.MyClass" 
android:icon="@drawable/ic_launcher" 
android:label="@string/app_name" 
android:theme="@style/AppTheme"> 
... 
</application> 

希望对你有帮助

+0

非常感谢你。我从来不知道这一点。 –

+1

我很高兴这很有帮助。请不要忘记upvote和标记为接受:) –