当我从其他活动返回到我的主要活动时,我的应用程序崩溃(StackOverflowError)

时间:2017-03-24 07:32:22

标签: android

我的MainActivity包含一个mikepenz / MaterialDrawer和一个包含5个片段的分页器视图。我正在使用材料抽屉启动其他活动,但在启动许多活动并返回到我的基本主要活动后,发生以下崩溃。     我不知道找到这个问题的实际根本原因。我们将非常感谢您的帮助。

java.lang.StackOverflowError
 at android.view.GLES20Canvas.drawTextRun(GLES20Canvas.java:1345)
 at android.text.SpannableStringBuilder.drawTextRun(SpannableStringBuilder.java:1139)
 at android.view.GLES20Canvas.drawTextRun(GLES20Canvas.java:1372)
 at android.text.TextLine.drawTextRun(TextLine.java:988)
 at android.text.TextLine.handleText(TextLine.java:789)
 at android.text.TextLine.handleRun(TextLine.java:956)
 at android.text.TextLine.drawRun(TextLine.java:395)
 at android.text.TextLine.draw(TextLine.java:193)
 at android.text.Layout.drawText(Layout.java:348)
 at android.widget.Editor.drawHardwareAccelerated(Editor.java:1455)
 at android.widget.Editor.onDraw(Editor.java:1378)
 at android.widget.TextView.onDraw(TextView.java:5170)
 at android.view.View.draw(View.java:14476)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.widget.HorizontalScrollView.draw(HorizontalScrollView.java:1609)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.widget.HorizontalScrollView.draw(HorizontalScrollView.java:1609)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.support.v4.view.ViewPager.draw(ViewPager.java:2443)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)

    公共类MainActivity扩展了MyAppFragmentActivity {

public static final String app_version="v1.134";

@Inject protected MyAppServiceProvider serviceProvider;
@Inject protected LogoutService logoutService;

private MyApplication app =MyApplication.getInstance();

private boolean userHasAuthenticated = false;

MainActivity activity;

public static final String TAG = MainActivity.class.getSimpleName();

public static final String permission = MainActivity.class+".permission";





//NEW CODE
private FrameLayout rootLayout;
private LinearLayout msgContainer;

//save our header or result
private AccountHeader headerResult = null;
private Drawer result = null;
private Login login;
private String sourceMenuJson;

//PAGER RELATED
ViewPager pager;
PagerAdapter pagerAdapter;
SlidingTabLayout tabs;
static final int noOfTabs= 5;
CharSequence pagerTitles[] = {
        //some strings
};

//TABLET LAUNCH SCREEN RELATED
private myappHorizontalOptionsMenu mmyappHorizontalOptionsMenu;
private myappHorizontalOption mSelectedmyappOption;

private TeachingPlanListFragment mTeachingPlanListFragment;
private Bus bus = app.getBus();
private Bundle savedInstanceState; //used by drawer menu

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.savedInstanceState = savedInstanceState;
    setContentView(R.layout.main_activity);
    msgContainer = (LinearLayout) findViewById(R.id.croutonContainer);
    rootLayout = (FrameLayout) findViewById(R.id.rootLayout);
    rootLayout.getForeground().setAlpha(0);
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    View mobilePagerView = findViewById(R.id.pager);
    View tabletWrapperView = findViewById(R.id.tablet_wrapper_view);

    // View injection with ButterKnife
    Views.inject(this);
    //INJECTS INTO DAGGER
    Injector.inject(this);
    activity = this;
    checkAuth();
    Log.d(TAG,"userHasAuthenticated "+userHasAuthenticated);

    if(isTablet()) {
        //setContentView(R.layout.main_activity_tablet);
        Log.d(TAG,"IS table view");
        processTabletView();
    } else {
        //setContentView(R.layout.main_activity);
        Log.d(TAG,"IS mobile view");
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
        mobilePagerView.setLayoutParams(param);
        tabletWrapperView.setVisibility(View.GONE);
    }
}

@Override
protected void onPostCreate(final Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
}

@Override
protected void onResume() {
    super.onResume();
    bus.register(this);

    if(userHasAuthenticated){
        initScreen();
    }

}

@Override
public void onBackPressed() {
    //handle the back press :D close the drawer first and if the drawer is closed close the activity
    if (result != null && result.isDrawerOpen()) {
        result.closeDrawer();
    } else {
        super.onBackPressed();
    }
}

public boolean isTablet() {
    return UIUtils.isTablet(this);
}

private void initScreen() {
    if (userHasAuthenticated) {
        login = app.getLogin();
        setNavigationDrawer();
        setUserProfile();
        initPager();
    }
}

private void setAttendenceType() {
    if (NetworkUtil.isInternetAvailable())
        new AttendanceType().execute();

}

private void checkAuth() {
    new SafeAsyncTask<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            final MyAppService svc = serviceProvider.getService(MainActivity.this);
            return svc != null;
        }

        @Override
        protected void onException(final Exception e) throws RuntimeException {
            super.onException(e);
            if (e instanceof OperationCanceledException) {
                // User cancelled the authentication process (back button, etc).
                // Since auth could not take place, lets finish this activity.
                finish();
            }
        }

        @Override
        protected void onSuccess(Boolean hasAuthenticated) throws Exception {
            Log.d(TAG,"onSuccess "+hasAuthenticated);
            if(app.getLogin() == null
                    || app.getLogin().getId() == null){
                Login login = new Login();
                SharedPreferences pref = getApplicationContext().getSharedPreferences("session", 0); // 0 - for private mode


                app.setLogin(login);
            }

            setAttendenceType();

            /**GCM RELATED CODE**/
            myappGCMUtil gcmUtil = new myappGCMUtil(getApplicationContext(), app.getLogin());

            String regid = gcmUtil.getRegistrationId();

            if (regid.isEmpty()) {
                gcmUtil.registerInBackground();
            }
            super.onSuccess(hasAuthenticated);
            userHasAuthenticated = true;
            initScreen();
        }
    }.execute();
}

private class AttendanceType extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            serviceProvider.getService(activity).getAttendanceType(activity);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AccountsException e) {
            e.printStackTrace();
        }
        return null;
    }
}

//get the list of permission
private void getPermissions(){
    String permissions = "";
    new AsyncTask<Void, Void, String>(){
        @Override
        protected String doInBackground(Void... voids) {
            PermissionWrapper postPermission = new PermissionWrapper();

            List<PermissionCode> permissionCodes = new ArrayList<PermissionCode>();

            for(int i=0; i < MainActivity.permissionCodes.length; i++){
                PermissionCode code = new PermissionCode();
                code.setCode(MainActivity.permissionCodes[i]);
                permissionCodes.add(code);
            }

            for(int i=0; i < MainActivity.canPermissionCodes.length; i++){
                PermissionCode code = new PermissionCode();
                code.setCode(MainActivity.canPermissionCodes[i]);
                permissionCodes.add(code);
            }

            postPermission.setId(app.getLogin().getName());

            postPermission.setResperm(permissionCodes);

            Log.d(TAG, new Gson().toJson(postPermission));

            try {
                HttpRequest requestPermission = post(app.getURL_PERMISSION())
                        .contentType("application/json")
                        .header(HEADER_TOKEN_KEY, HEADER_TOKEN)
                        .send(new Gson().toJson(postPermission));

                if (requestPermission.ok()) {
                    Log.d(TAG, "permission loaded");
                    return Strings.toString(requestPermission.buffer());
                } else {
                    Log.d(TAG, "permission loading failed");
                    return "";
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
            return "";
        }

        @Override
        protected void onPostExecute(String permissionList) {
            super.onPostExecute(permissionList);

            SharedPreferences pref = getApplicationContext().getSharedPreferences("session", 0); // 0 - for private mode
            SharedPreferences.Editor editor = pref.edit();
            if(permissionList!=null && permissionList.length() > 0)
                editor.putString(MainActivity.permission, permissionList);
            editor.apply();
        }
    }.execute();

}

//RETRIEVES INSTITUTES LIST FROM STRING
public List<Institute> retrieveInstitutes(String instituteString){
    List<Institute> institutes = new ArrayList<Institute>();
    if(instituteString!=null){
        Gson gson = new Gson();
        Institute[] institutesArray = gson.fromJson(instituteString,Institute[].class);
        institutes = Arrays.asList(institutesArray);
        institutes = new ArrayList<Institute>(institutes);
    }
    return  institutes;
}

/***********************************************
 * PAGER RELATED
 * **********************************************/
//INIT PAGER RELATED
private void initPager(){
    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(getApplicationContext(),R.color.colorWhite);
        }
    });
    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    pagerAdapter = new PagerAdapter(getSupportFragmentManager(), pagerTitles, noOfTabs);

    pager.setAdapter(null);
    pager.setAdapter(pagerAdapter);
    pager.setCurrentItem(1, true);

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);
}

/***************************************************
 * Navigation Drawer Menu Related
 * *************************************************/

//TO LOAD READ DRAWER MENUS FROM JSON FILE
public String loadJSONMenuFromAsset() {
    if(sourceMenuJson==null){
        try {

            InputStream is = getAssets().open("drawer_menus.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            sourceMenuJson = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }else
        Log.d(TAG,"sourceMenuJson already exists");
    return sourceMenuJson;
}

//INITIALIZE NAVIGATION DRAWER
private void setNavigationDrawer(){
    // Handle Toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //set the back arrow in the toolbar
    setTitle(R.string.app_name);
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    // Create the AccountHeader
    headerResult = new AccountHeaderBuilder()
            .withActivity(this)
            .withHeaderBackground(ContextCompat.getDrawable(this,R.drawable.left_menu_header_bg))
            .withTranslucentStatusBar(false)
            .withCompactStyle(true)
            .withSavedInstance(savedInstanceState)
            .build();

    result = new DrawerBuilder()
            .withActivity(this)
            .withToolbar(toolbar)
            .withDisplayBelowStatusBar(false)
            .withTranslucentStatusBar(false)
            .withActionBarDrawerToggleAnimated(true)
            .withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                    if (drawerItem != null) {
                        onDrawerMenuSelected(drawerItem.getIdentifier());
                    }

                    return false;
                }
            })
            .addDrawerItems(
                    setMenuList()
            )
            .addStickyDrawerItems(new PrimaryDrawerItem().withName(R.string.logout_action).withIcon(myappIcon.Icon.cmu_logout).withIdentifier(-1))
            .withSavedInstance(savedInstanceState)
            .withShowDrawerOnFirstLaunch(true)
            .build();
    result.getActionBarDrawerToggle().setDrawerIndicatorEnabled(true);//SHOW HAMBURGER ICON
}

@Nullable
private IDrawerItem[] setMenuList() {
    List<IDrawerItem> iDrawerItems = new ArrayList<IDrawerItem>();
    List<DrawerMenuItem> allMenus = new Gson().fromJson(loadJSONMenuFromAsset(),DrawerMenuWrapper.class).getMenuItems();

    SharedPreferences pref = app.getSharedPreferences("session", 0);

    if(null != pref.getString(MainActivity.permission, null)) {
        Log.d(TAG, pref.getString(MainActivity.permission, null));
        PermissionResponseWrapper responseWrapper;
        try {
            responseWrapper = new Gson().fromJson(pref.getString(MainActivity.permission, null), PermissionResponseWrapper.class);
        } catch (Exception e) {
            responseWrapper = null;
        }
        if (responseWrapper != null && responseWrapper.getOutput().getData().getResperm() != null) {
            for (DrawerMenuItem menuItem : allMenus) {
                // iterate through list add the permissions available
                for (PermissionCode code : responseWrapper.getOutput().getData().getResperm()) {
                    if (code.getCode().equals(menuItem.getCode())) {
                        //SETS MENU ITEM SHOW TO TRUE;
                        menuItem.setShow(true);
                    }
                }

            }

        }

        //ITERATE ALL MENUS AND ADD TO VIEW ONLY IF "show==true"
        for (DrawerMenuItem menuItem : allMenus){
            if (menuItem.isShow()) {
                int stringID = getResources().getIdentifier(menuItem.getName(), "string", this.getPackageName());
                iDrawerItems.add(new PrimaryDrawerItem().withName(stringID).withIcon(menuItem.getIcon()).withIdentifier(menuItem.getPos()));
                iDrawerItems.add(new DividerDrawerItem());
            }
        }

        return iDrawerItems.toArray(new IDrawerItem[iDrawerItems.size()]);
    }

    return null;
}

//SETS THE USER NAME AND PHOTO
private void setUserProfile(){
    IProfile profile =  new ProfileDrawerItem().withName(login.getUname()).withEmail(login.getOrgname());

    String imageUrl = login.getImageUrl();
    if(imageUrl!=null && imageUrl.length()>0){
        //LOADS IMAGE FROM SERVER
        //initialize and create the image loader logic
        DrawerImageLoader.init(new DrawerImageLoader.IDrawerImageLoader() {
            @Override
            public void set(ImageView imageView, Uri uri, Drawable placeholder) {
                Picasso.with(imageView.getContext()).load(uri).transform(new CircleTransformPicasso()).placeholder(placeholder).into(imageView);
            }

            @Override
            public void cancel(ImageView imageView) {
                Picasso.with(imageView.getContext()).cancelRequest(imageView);
            }

            @Override
            public Drawable placeholder(Context ctx) {
                return null;
            }
            @Override
            public Drawable placeholder(Context ctx,String s) {
                return null;
            }
        });
        profile.withIcon(app.getURL_GET_AVATAR()+imageUrl);
    }else {
        //SETS DEFAULT IMAGE
        profile.withIcon(myappIcon.Icon.cmu_students);
    }
    headerResult.addProfile(profile, 0);
}

public void onDrawerMenuSelected(long position) {

    int selectedMenu = (int) position;
    switch(selectedMenu) {
        case -1:
            //Logout
            logoutService.logout(new Runnable() {
                @Override
                public void run() {
                    //Reload activity
                    Intent intent =getIntent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    finish();
                    startActivity(intent);

                }
            });
            break;

    }
}

/***************************************************
 * Tablet Land Screen Related
 ****************************************************/
//Initialize Tablet screen related work
private void processTabletView(){
    mSelectedmyappOption = new myappHorizontalOption();
    loadHorizontalMenus();
}

//LOAD HORIZONTAL OPTION MENUS FOR TABLET VIEW
private void loadHorizontalMenus(){
    final Map<String,String> tabletLaunchOptions= new LinkedHashMap<>();
    tabletLaunchOptions.put("AA", app.getResources().getString(R.string.menu_teaching_plan));
    tabletLaunchOptions.put("BB", app.getResources().getString(R.string.assignments));
    tabletLaunchOptions.put("CC", app.getResources().getString(R.string.attendance));
    mmyappHorizontalOptionsMenu = (myappHorizontalOptionsMenu) findViewById(R.id.myappHorizontalOptionsMenu);
    mmyappHorizontalOptionsMenu.distributeEvenly(true);
    mmyappHorizontalOptionsMenu.setOptions(tabletLaunchOptions);
    mmyappHorizontalOptionsMenu.disableOptionClick(true);
    // Setting Custom Color for the Scroll bar indicator of the Tab View
    mmyappHorizontalOptionsMenu.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(getApplicationContext(),R.color.colorPrimary);
        }
    });
}

//Launch Attendance Fragment
public void launchAttendanceFragment(final Intent intent, String sourceFragment){

    //Post deselection inorder to swap current selection view
    ListItemDeselectEvent event = new ListItemDeselectEvent();
    if(sourceFragment.equals("ScheduleListFragment")){
        event.setTargetClassName("MyClassListFragment");
    }else {
        event.setTargetClassName("ScheduleListFragment");
    }
    bus.post(event);

    //Get selected option and set option
    mSelectedmyappOption.setTag("ATTENDANCE");
    mSelectedmyappOption.setLabel(app.getResources().getString(R.string.attendance));
    mSelectedmyappOption.setPosition(2);
    mmyappHorizontalOptionsMenu.setSelectedOption(mSelectedmyappOption, false);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            AttendanceListFragment attendanceListFragment = new AttendanceListFragment();
            attendanceListFragment.intiFragment(MainActivity.this,intent);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_details, attendanceListFragment)
                    .commit();
        }
    },300);
}

//Set selected schedule and launches teaching plan
public void launchTeachingPlanUpdateFragment(final Schedule schedule){

    //Post deselection inorder to swap current selection view
    ListItemDeselectEvent event = new ListItemDeselectEvent();
    event.setTargetClassName("MyClassListFragment");
    bus.post(event);

    mSelectedmyappOption.setTag("CC");
    mSelectedmyappOption.setLabel(app.getResources().getString(R.string.menu_teaching_plan));
    mSelectedmyappOption.setPosition(0);
    mmyappHorizontalOptionsMenu.setSelectedOption(mSelectedmyappOption, false);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTeachingPlanListFragment = new TeachingPlanListFragment();

            mTeachingPlanListFragment.intiFragment(schedule);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_details, mTeachingPlanListFragment)
                    .commit();
        }
    },300);
}

}

1 个答案:

答案 0 :(得分:0)

最后我自己解决了这个问题。问题是我已经从onResume()初始化了“View Pager”和“Drawer Menu”。每当我从其他活动回来时,“View Pager”和“Drawer Menu”会再次初始化,从而产生StackOverflow异常。