简体   繁体   中英

Android application crashes at first run (only)

So this is the case: At start up a splash screen is shown (and at the same time a location request is shown ontop) with a timer activated, after the time has passed it moves on to the MainActivity. And if I allow the position to be used (while the splash screen is in the backgorund), it crashes when it enters the MainActivity. However, if I wait with allowing the position until the MainActivity is shown, no crash.

This error is only generated the first time the app is opned after installation. The second time I try to replicate the error, its not show (but it may have to be that I'm not giving the question to allow my position?)

I have no clue where the error can be, and the error log is not telling me exactly where in the code the error is trigged?

This is the error from the logcat:

12-05 23:19:35.670 19723-19723/se.dxapps.skidspar.beta E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: se.dxapps.skidspar.beta, PID: 19723
                                                                     java.lang.RuntimeException: Unable to stop activity {se.dxapps.skidspar.beta/se.dxapps.skidspar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.clearAccessibilityFocus()' on a null object reference
                                                                         at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3962)
                                                                         at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4011)
                                                                         at android.app.ActivityThread.-wrap25(ActivityThread.java)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1542)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:241)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6274)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.clearAccessibilityFocus()' on a null object reference
                                                                         at android.view.ViewGroup.removeViewInternal(ViewGroup.java:4706)
                                                                         at android.view.ViewGroup.removeViewAt(ViewGroup.java:4665)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1762)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1819)
                                                                         at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3227)
                                                                         at android.support.v4.app.FragmentManagerImpl.dispatchStop(FragmentManager.java:3204)
                                                                         at android.support.v4.app.FragmentController.dispatchStop(FragmentController.java:236)
                                                                         at android.support.v4.app.FragmentActivity.onStop(FragmentActivity.java:597)
                                                                         at android.support.v7.app.AppCompatActivity.onStop(AppCompatActivity.java:183)
                                                                         at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1290)
                                                                         at android.app.Activity.performStop(Activity.java:6895)
                                                                         at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3959)
                                                                         at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4011) 
                                                                         at android.app.ActivityThread.-wrap25(ActivityThread.java) 
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1542) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                         at android.os.Looper.loop(Looper.java:241) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6274) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

Here is a "part" of the MainActivity code (since there was a character limitation in the body)

public class MainActivity extends AppCompatActivity implements TabListener, LocationListener {

    private static final String TAG = "lol";
    private static int ACTIVITY_SETTINGS = 4;
    private static MapsearchFragment mMapFragment;
    private static ListsearchFragment mListFragment;
    private static ListFavoritesFragment mFavFragment;
    SearchView mSearchView = null;
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
     * three primary sections of the app. We use a {@link android.support.v4.app.FragmentPagerAdapter}
     * derivative, which will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    AppSectionsPagerAdapter mAppSectionsPagerAdapter;
    /**
     * The {@link ViewPager} that will display the three primary sections of the app, one at a
     * time.
     */
    ViewPager mViewPager;
    private int defaultShowAge = 7;
    private boolean defaultShowPref = true;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private WebView adView;
    private Toolbar toolbar;

    private LocationManager locationManager;
    private Skidspar skidspar;
    private String prop_firstLaunch = "firstLaunch";
    private PropertyStorage propertyStorage;

    private AdHelper adHelper;


    // private GifImageView gifImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Crittercism.initialize(getApplicationContext(), "52a2321a8b2e331d0f000003");
        setContentView(R.layout.activity_main);
        //final ActionBar actionBar = getActionBar();

        // Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
        adView = ReviveAdHelper.getAdView(findViewById(R.id.reviveAdFooter));
        adView.loadUrl(ReviveAdHelper.footerAdUrl);
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager(), getResources());

        //Location listener stuff.
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        MyLog.d("Skidspar", "onCreate");
        skidspar = (Skidspar) getApplicationContext();
        skidspar.setMyMain(this);

        /* augustw */
        if (PermissionRequest.execute(this)) //else -> efterfrågar permissions och kör onRequestPermissionsResult() istället.
            invokeLocationManagement();

        //adHelper = new AdHelper(this, (GifImageView) findViewById(R.id.adview), skidspar.getDefaultTracker());

        if (hasGPSPermission()) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            if (locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {
                skidspar.setMyLocation(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
            }
            Location wifi = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (wifi != null) {
                if (skidspar.getMyLocation() == null) {
                    skidspar.setMyLocation(wifi);
                } else if (Utils.isBetterLocation(wifi, skidspar.getMyLocation())) {
                    skidspar.setMyLocation(wifi);
                }
            }
        } else {

        }

        mTitle = mDrawerTitle = getTitle();

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new MenuListAdapter(this, 0, 0, createMenuList()));

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                toolbar,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */
        ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                toolbar.setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                toolbar.setTitle(mDrawerTitle);
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        //ViewPager stuff.
        SlidingTabLayout mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
        mSlidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {

            @Override
            public int getIndicatorColor(int position) {
                return Color.WHITE;
            }

        });
        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When swiping between different app sections, select the corresponding tab.
                // We can also use ActionBar.Tab#select() to do this if we have a reference to the
                // Tab.
                // actionBar.setSelectedNavigationItem(position);
                if (position == 0) {
                    if (mListFragment != null) {
                        mListFragment.refreshMyView();
                    }
                } else if (position == 1) {
                    if (mMapFragment != null) {
                        mMapFragment.refreshMyView();
                    }
                }
                Log.d("AdHelper","Swiped");
                adView.loadUrl(ReviveAdHelper.footerAdUrl);
                //adHelper.generateAd();
            }
        });


        //setSlidingTabLayoutContentDescriptions();

        Resources res = getResources();
        //mSlidingTabLayout.setSelectedIndicatorColors(res.getColor(R.color.tab_selected_strip));
        mSlidingTabLayout.setDistributeEvenly(true);
        mSlidingTabLayout.setViewPager(mViewPager);

        if (mSearchView != null) {
            mSearchView.setQuery("", false);
        }
        int shownTab = 0;
        try {
            shownTab = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(this).getString("pref_default_tab", "1"));
        } catch (Exception e) {
            shownTab = 0;
        }
        mViewPager.setCurrentItem(shownTab);
        //adHelper.generateAd();
      //  gifImageView = (GifImageView) findViewById(R.id.banner);

        Tracker tracker = ((Skidspar) getApplication()).getTracker(Skidspar.TrackerName.APP_TRACKER);
        tracker.send(new HitBuilders.ScreenViewBuilder().setNewSession().build());

        propertyStorage = new PropertyStorage(getApplicationContext());
        String firstLaunch = propertyStorage.get(prop_firstLaunch);
        if(firstLaunch == null){ //alltid null vid första launch iom att värdet aldrig har sparats
            onFirstAppLaunch();
            propertyStorage.save(prop_firstLaunch, "false");
        }

    }

    public void onFirstAppLaunch() {
        final Toast toast = Toast.makeText(getApplicationContext(), "Under inställningar kan du välja vilka anläggningar som ska visas", Toast.LENGTH_LONG);
        CountDownTimer toastCountDown = new CountDownTimer(8000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                toast.show();
            }

            @Override
            public void onFinish() {
                toast.cancel();
            }
        };
        //Visa toast och starta nedräkningen
        toast.show();
        toastCountDown.start();
    }

    public void invokeLocationManagement() {
        try {

            tryStartLocationService();
            if (locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {
                skidspar.setMyLocation(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
            }
            Location wifi = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (wifi != null) {
                if (skidspar.getMyLocation() == null) {
                    skidspar.setMyLocation(wifi);
                } else if (Utils.isBetterLocation(wifi, skidspar.getMyLocation())) {
                    skidspar.setMyLocation(wifi);
                }
            }
        } catch(SecurityException ex) {
            ex.printStackTrace();
        }
    }

Your given code is not well complete that we can answer. But From Logcat details focus that it showing Attempt to invoke a virtual method void android.view.View.clearAccessibilityFocus() on null reference object" . This must be happen at the code line consists of findViewById(R.id.something) here if your going to add View that are not in your current layout, will register error. So you must have to specify that on which basis of the view your are going to invoke that view, so your that code line should be like if it is TableLayout invoke via View invokeTabelViewInMain then '(TableLayout)invokeTabelViewInMain.findViewwById(R.id.something)' . It will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM