我试图将上下文强制转换为 Activity。我需要这样做才能调用该活动的方法之一。为了获得我需要的上下文,我使用了 getApplicationContext()。我现在正在开发的应用程序使用 Sugar ORM 作为数据库框架。这是我得到的代码和异常。
ContentResolver.requestSync(((MainActivity) getApplicationContext()).getAccount(), AccountHelper.AUTHORITY, settingsBundle);
java.lang.ClassCastException: com.orm.SugarApp cannot be cast to id.ac.ui.presentronik.activity.MainActivity
at id.ac.ui.presentronik.activity.SessionActivity.onOptionsItemSelected(SessionActivity.java:173)
at android.app.Activity.onMenuItemSelected(Activity.java:2885)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:350)
at android.support.v7.app.ActionBarActivity.onMenuItemSelected(ActionBarActivity.java:155)
at android.support.v7.app.ActionBarActivityDelegate$1.onMenuItemSelected(ActionBarActivityDelegate.java:74)
at android.support.v7.widget.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:44)
at android.support.v7.internal.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:77)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:163)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:738)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:802)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:949)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:939)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:596)
at android.support.v7.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:145)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
看来我遇到的问题与这个问题中的一个相同:SugarORM in AndroidManifest。但该解决方案仅适用于片段。有没有其他方法可以从活动中获取正确的上下文?