当startActivity(Intent)运行时,Context.getResources()返回null

时间:2016-09-07 20:14:08

标签: android nullpointerexception

最近对我的代码库进行了一些重大的重构(主要是将类移到新的包中),现在我在用户登录后尝试启动NavigationDrawer活动时遇到错误。

DistributorLogin运行一个asynctask来验证用户的凭据,并返回一个Distributor对象,该对象作为额外的函数传递给启动NavigationDrawer的Intent。在startActivity(Intent)运行后的某个时刻,在设置活动时会发生对Context.getResources()的调用。看来资源对象返回null。一些设备在ContextThemeWrapper.initializeTheme(int)中出现此错误,并且我在尝试检索布尔值时也看到它发生在Window.getDefaultFeatures(Context)中。只有在尝试启动NavDrawer活动时才会出现此问题。其他活动似乎开始很好。永远不会调用NavDrawer的onCreate()。

DistributorLogin.activity

@Override
public void distributorAuthenticationFinished(Distributor output) {

try {
        //Only continue if a valid Distributor object was received
        if (output != null) {

            String currentLanguage = "ENG";
            DistributorSettings distributorSettings = output.getDistributorSettings();
            if (distributorSettings != null) {
                String homeCountry = distributorSettings.getHomeCountry();
                currentLanguage = distributorSettings.getCurrentLanguage();
                Content.getInstance().setCurrentLocale(homeCountry, currentLanguage);
                writeContentDocs(homeCountry, currentLanguage, false);
                writeAllSupportedLanguageDocs();
            }

            //Clear UI element values
            etxt_name.setText("");
            etxt_password.setText("");

            //Attempt to register a new device token if one is not already saved.
            Intent tokenIntent = IntentCreator.getTokenRegistrationIntent(this, RegistrationTokenIntentService.CREATE_NEW_IF_NONE_EXISTS,
                    Distributor.distributorId, Distributor.homeCountry, currentLanguage);
            startService(tokenIntent);

            // Start the main activity
            Intent intent = new Intent(this, NavDrawer.class);
            intent.putExtra(getString(R.string.cb_parameter_distributor), output);
            startActivity(intent);

        }
    } catch (Exception e) {
        Log.e(TAG, "Error starting nav drawer activity.", e);
    }
}

Android清单

<manifest
    package="com.marketamerica.android.unfranchiseprospecting"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:name=".models.Ufp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:uiOptions="splitActionBarWhenNarrow">
        <activity
            android:name=".activities.DistributorLogin"
            android:label="@string/app_name_acronym"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.NavDrawer"
            android:label="@string/title_activity_nav_drawer"
            android:windowSoftInputMode="adjustPan"
            android:launchMode="singleTop"/>
    </application>
</manifest>

NavDrawer

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ufpTypeFace = Typeface.createFromAsset(getAssets(), "fonts/ufp_2-0.ttf");

    isTablet = Ufp.getIsTablet();

    // Get application resources
    resources = this.getResources();

    // Define our sharedPreferences and editor objects
    sharedPreferences = getSharedPreferences(resources.getString(R.string.ma_content_shared_prefs_name), Context.MODE_PRIVATE);
    sharedPreferencesEditor = sharedPreferences.edit();
    checkAndResetSharedPrefsIfNecessary();


    // Set the initial fragmentState
    if (savedInstanceState == null) {
        fragmentState = FragmentState.viewable;
        sharedPreferencesEditor.putString("fragmentState", "viewable");
        sharedPreferencesEditor.apply();
    } else {
        shouldRestoreMediaDetail = savedInstanceState.getBoolean(getString(R.string.media_detail_arg_key));
    }


    restoreSelectedProspectId(sharedPreferences);

    if (!selectedProspectId.equals("")) {
        prospectDetails = repository.get(getString(R.string.cb_parameter_prospect_doc_prefix) + selectedProspectId, ProspectDetails.class);
    }

    // Assign our Distributor object from CB
    distributor = (Distributor) getIntent().getSerializableExtra(getString(R.string.cb_parameter_distributor));

    // ThreadPoolExecutors responsible for updating prospectDetailsArrayList and timelineItemArrayList
    detailsThreadPoolExecutor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    timelineThreadPoolExecutor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());;
    startProspectDetailsLiveQuery();
    startTimelineLiveQuery();

    // Instantiate fragmentManager
    fragmentManager = getFragmentManager();

    // Set up our content views and layouts
    if (!isTablet) { // Handset layout
        setContentView(R.layout.activity_nav_drawer);
        container = (FrameLayout) findViewById(R.id.container);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        setupFloatingActionButton();
        setUpToolbar();
    } else { // Tablet layout
        setContentView(R.layout.activity_nav_drawer_tablet);
        container = (FrameLayout) findViewById(R.id.container);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        setupFloatingActionButton();
        setUpToolbar();
    }

    if (mNavigationDrawerFragment == null) {
        // Instantiate the NavigationDrawer
        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getFragmentManager().findFragmentById(R.id.navigation_drawer);

        if (drawerLayout != null) {
            // Set up the drawer.
            mNavigationDrawerFragment.setUp(
                    R.id.navigation_drawer,
                    drawerLayout);
        }
    }

    // Instantiate prospectListFragment and corresponding layout for UI control if device is a tablet
    if (Ufp.getIsTablet()) {
        prospectListFragment = (ProspectListFragment) fragmentManager.findFragmentById(R.id.prospects_list);
        prospectListFragmentLayout = prospectListFragment.getView();
    }

logcat的

    09-07 15:48:51.644 24077-24077/com.marketamerica.android.unfranchiseprospecting E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.marketamerica.android.unfranchiseprospecting, PID: 24077
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.marketamerica.android.unfranchiseprospecting/com.marketamerica.android.unfranchiseprospecting.activities.NavDrawer}: 
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.res.Resources.newTheme()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2814)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2879)
    at android.app.ActivityThread.access$900(ActivityThread.java:182)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1475)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:145)
    at android.app.ActivityThread.main(ActivityThread.java:6141)
    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:1399)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
    Caused by: java.lang.NullPointerException: 
    Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.res.Resources.newTheme()' on a null object reference
    at android.view.ContextThemeWrapper.initializeTheme(ContextThemeWrapper.java:134)
    at android.view.ContextThemeWrapper.setTheme(ContextThemeWrapper.java:85)
    at android.support.v7.app.AppCompatActivity.setTheme(AppCompatActivity.java:86)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2760)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2879) 
    at android.app.ActivityThread.access$900(ActivityThread.java:182) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1475) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:145) 
    at android.app.ActivityThread.main(ActivityThread.java:6141) 
    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:1399) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 

0 个答案:

没有答案