Android应用程序在首次运行时崩溃(仅限)

时间:2017-12-05 22:22:46

标签: java android

所以情况就是这样: 启动时会显示一个启动画面(同时在顶部显示位置请求)并启动计时器,经过一段时间后,它会移动到MainActivity。如果我允许使用该位置(当启动画面在backgorund中时),它在进入MainActivity时会崩溃。但是,如果我等到允许该位置直到显示MainActivity,则不会崩溃。

此错误仅在安装后第一次应用应用时生成。我第二次尝试复制错误,它没有显示(但可能是因为我没有提出允许我的职位的问题?)

我不知道错误的位置,并且错误日志没有告诉我错误被触发的代码到底在哪里?

这是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) 

这是"部分" MainActivity代码(由于正文中有字符限制)

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();
        }
    }

1 个答案:

答案 0 :(得分:0)

您给出的代码不完整,我们可以回答。 但是从Logcat详细介绍它显示尝试在空引用对象“上调用虚拟方法void android.view.View.clearAccessibilityFocus()。这必须在代码行中由组成findViewById(R.id.something)如果您要添加不在当前布局中的View,则会注册错误。所以您必须指定您要调用的视图的基础查看,所以你的代码行应该像是通过View invokeTabelViewInMain调用TableLayout然后'(TableLayout)invokeTabelViewInMain.findViewwById(R.id.something)'。它会起作用。