很长一段时间后从后台恢复时Android应用程序崩溃

时间:2014-05-06 12:21:26

标签: android

我是编程方面的新手,我有一个奇怪的问题。我尝试在后台长时间从背景中恢复应用程序,并使用NullPointerException进行崩溃。

这是logcat的错误

05-06 14:19:28.278: W/~~~~~~~~~~~~~~~~MainActivity(12129): onSaveInstanceState() com.main.MainActivity@43087bb0 fragment: PrivateCabinetFragment{430d2ae0 #0 id=0x7f09005e PrivateCabinetFragment}
05-06 14:19:35.168: E/BaseFragment(13342): onCreate 
05-06 14:19:35.168: D/AndroidRuntime(13342): Shutting down VM
05-06 14:19:35.168: W/dalvikvm(13342): threadid=1: thread exiting with uncaught exception (group=0x4158cba8)
05-06 14:19:35.168: E/AndroidRuntime(13342): FATAL EXCEPTION: main
05-06 14:19:35.168: E/AndroidRuntime(13342): Process: com, PID: 13342
05-06 14:19:35.168: E/AndroidRuntime(13342): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.main.MainActivity}: java.lang.NullPointerException
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.os.Handler.dispatchMessage(Handler.java:102)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.os.Looper.loop(Looper.java:136)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.main(ActivityThread.java:5017)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at java.lang.reflect.Method.invokeNative(Native Method)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at java.lang.reflect.Method.invoke(Method.java:515)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at dalvik.system.NativeStart.main(Native Method)
05-06 14:19:35.168: E/AndroidRuntime(13342): Caused by: java.lang.NullPointerException
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.main.MainActivity.setUnreadedMessages(MainActivity.java:151)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.main.PrivateCabinetFragment.onCreate(PrivateCabinetFragment.java:104)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.Fragment.performCreate(Fragment.java:1437)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:877)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:1856)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:210)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.main.BaseActivity.onCreate(BaseActivity.java:55)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at com.main.MainActivity.onCreate(MainActivity.java:65)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.Activity.performCreate(Activity.java:5231)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-06 14:19:35.168: E/AndroidRuntime(13342):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-06 14:19:35.168: E/AndroidRuntime(13342):    ... 11 more

这是我的代码

package com.main;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;



   import com.R;
    import com.connection.ActionGetData;
    import com.data.Constants;

public class MainActivity extends BaseActivity implements OnClickListener, DialogInterface.OnCancelListener {
    private final static String CLASS_TAG = MainActivity.class.getSimpleName();
    private Fragment mContent;
    private PrivateCabinetFragment privateCabinetFrag;
    private SettingsFragment settingsFragment;
    private NewOrderMainFragment stayOrderFragment;
    private PopularQuestionListFragment questionsFragment;
    private PaymentsMenu paymentsMenu;
    private MessageMain messageMain;
    private MyRequestOrdersListFragment requestList;
    private ImageView service;
    private ImageView helpAndSupport;
    private ImageView payments;
    private ImageView settings;
    private RelativeLayout btnService;
    private RelativeLayout btnHelpAndSupport;
    private RelativeLayout btnPayments;
    private RelativeLayout btnSettings;
    private RelativeLayout btnMessages;
    private ImageView btnSupportStayOrder;
    private TextView btnSupportRequestOrders;
    private TextView btnSupportPopularQuestion;
    private ImageView messages;
    private TextView tvNewMessages;
    private RelativeLayout dashBoard;
    private LinearLayout toggleButton;
    private Bundle extras;
    private String fragment_tag = "";
    private FragmentManager frag_manager;
    private int onBackpress = 0;
    public static boolean sDisableFragmentAnimations = false;

    protected Animation animUp;
    protected Animation animDown;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Log.e(CLASS_TAG,"savedInstanceState"+ savedInstanceState);
        if (savedInstanceState != null) {
            Log.e(CLASS_TAG, "savedInstanceState" + savedInstanceState.isEmpty());

            Log.i(CLASS_TAG, "savedInstance != null");
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();

        } else {

            setContentView(R.layout.main_activity);
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
            extras = getIntent().getExtras();
            tvNewMessages = (TextView) findViewById(R.id.tv_new_messages);
            service = (ImageView) findViewById(R.id.iv_services_main_board);

            btnService = (RelativeLayout) findViewById(R.id.rl_services_main_board);
            btnService.setOnClickListener(this);

            helpAndSupport = (ImageView) findViewById(R.id.iv_support_main_board);
            btnHelpAndSupport = (RelativeLayout) findViewById(R.id.rl_support_main_board);
            btnHelpAndSupport.setOnClickListener(this);

            payments = (ImageView) findViewById(R.id.iv_payments_main_board);
            btnPayments = (RelativeLayout) findViewById(R.id.rl_payments_main_board);
            btnPayments.setOnClickListener(this);

            messages = (ImageView) findViewById(R.id.iv_message_main_board);
            btnMessages = (RelativeLayout) findViewById(R.id.rl_message_main_board);
            btnMessages.setOnClickListener(this);

            settings = (ImageView) findViewById(R.id.iv_settings_main_board);
            btnSettings = (RelativeLayout) findViewById(R.id.rl_settings_main_board);
            btnSettings.setOnClickListener(this);

            toggleButton = (LinearLayout) findViewById(R.id.ll_toggle_container);
            toggleButton.setBackgroundDrawable((getResources().getDrawable(R.drawable.top_panel_background)));

            dashBoard = (RelativeLayout) findViewById(R.id.dash_board);

            btnSupportStayOrder = (ImageView) findViewById(R.id.iv_new_order);
            btnSupportStayOrder.setOnClickListener(this);

            btnSupportPopularQuestion = (TextView) findViewById(R.id.tv_popular_questions);
            btnSupportPopularQuestion.setOnClickListener(this);

            btnSupportRequestOrders = (TextView) findViewById(R.id.tv_my_orders);
            btnSupportRequestOrders.setOnClickListener(this);

            questionsFragment = new PopularQuestionListFragment();
            privateCabinetFrag = new PrivateCabinetFragment();
            settingsFragment = new SettingsFragment();
            stayOrderFragment = new NewOrderMainFragment();
            paymentsMenu = new PaymentsMenu();
            messageMain = new MessageMain();
            requestList = new MyRequestOrdersListFragment();
            animUp = AnimationUtils.loadAnimation(this, R.anim.anim_up);
            animDown = AnimationUtils.loadAnimation(this, R.anim.anim_down);
            frag_manager = getSupportFragmentManager();
            service.setBackgroundResource(R.drawable.services_main_board_pressed);
            if (extras != null) {
                boolean payments = extras.getBoolean(Constants.EXTRAS_MAIN_ACTIVITY_PAY_FRAGMENT);
                if (payments) {
                    fragment_tag = PaymentsMenu.class.getSimpleName();
                    pushFragmentsWithoutAnimation(paymentsMenu, fragment_tag);

                }
            } else {
                fragment_tag = PrivateCabinetFragment.class.getSimpleName();
                pushFragmentsWithoutAnimation(privateCabinetFrag, fragment_tag);
            }
        }

    }

public void setUnreadedMessages(int count) {
    if (count > 0) {
        tvNewMessages.setVisibility(View.VISIBLE);

        tvNewMessages.setText(Integer.toString(count));
    } else {
        tvNewMessages.setVisibility(View.INVISIBLE);
    }

}

@Override
protected void onSaveInstanceState(Bundle outState) {

    Log.w("~~~~~~~~~~~~~~~~" + CLASS_TAG, "onSaveInstanceState() " + toString() + " fragment: " + mContent);

    try {
        frag_manager.putFragment(outState, "mContent", mContent);
    } catch (Exception e) {
        Log.e(CLASS_TAG, "!!!!!!!!");
        e.printStackTrace();
    }
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    Log.w("~~~~~~~~~~~~~~~~" + CLASS_TAG, "onRestoreInstanceState() " + toString() + " fragment: " + mContent.getClass().getSimpleName());
    mContent = frag_manager.getFragment(savedInstanceState, "mContent");
    Log.i(CLASS_TAG, "savedInstance != null");


    super.onRestoreInstanceState(savedInstanceState);

}



public void pushFragments(Fragment fragment, String tag) {
    onBackpress = 0;
    String old_tag = "";
    try {
        old_tag = mContent.getClass().getSimpleName();

    } catch (Exception e) {
        e.printStackTrace();
        old_tag = "new";
    }
    mContent = fragment;
    if (old_tag.equals(tag)) {

    } else {
        clearFragments();
        // frag_manager.popBackStack(null,
        // FragmentManager.POP_BACK_STACK_INCLUSIVE);
        FragmentTransaction ft = frag_manager.beginTransaction();

        ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left).replace(R.id.frame_container, fragment, tag);
        ft.commit();
        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

}

public void clearFragments() {
    sDisableFragmentAnimations = true;
    frag_manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

}

public void pushFragmentsWithoutAnimation(Fragment fragment, String tag) {
    onBackpress = 0;
    String old_tag = "";
    try {
        old_tag = mContent.getClass().getSimpleName();

    } catch (Exception e) {
        e.printStackTrace();
        old_tag = "new";
    }
    mContent = fragment;
    if (old_tag.equals(tag)) {

    } else {
        clearFragments();
        FragmentTransaction ft = frag_manager.beginTransaction();

        ft.replace(R.id.frame_container, fragment, tag);
        ft.commit();
        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}

public void navigateTo(Fragment fragment) {
    onBackpress = 0;
    mContent = fragment;

    frag_manager.beginTransaction().setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_right)
            .replace(R.id.frame_container, fragment).addToBackStack(Integer.toString(frag_manager.getBackStackEntryCount() + 1)).commit();

    if (getCurrentFocus() != null) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }

}

public void navigateBack() {
    Log.v(CLASS_TAG, "navigateBack()");
    onBackpress = 0;

    final int cnt = frag_manager.getBackStackEntryCount();

    Log.v(CLASS_TAG, "stack depth: " + cnt);

    if (cnt >= 1) {

        frag_manager.popBackStack();

        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    } else {
        onBackPressed();
        Log.v(CLASS_TAG, "Can't navigate");
    }
}

@Override
public void onBackPressed() {
    if (clients_Data.getClientAcc().size() < 2) {
        if (onBackpress >= 1) {
            hideProgressDialog();
            if (clients_Data.isLogedIn()) {
                ActionGetData.doLogOut();
                finish();
            }
            super.onBackPressed();
        } else if (onBackpress < 1) {
            Toast.makeText(this, getString(R.string.push_for_exit), Toast.LENGTH_SHORT).show();
        }
        onBackpress++;
    } else {
        super.onBackPressed();
        MainActivity.this.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
    }
}

public void isPayments() {
    hideTopPanel();
    payments.setBackgroundResource(R.drawable.payments_main_board_pressed);
    helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);
    messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
    service.setBackgroundResource(R.drawable.services_main_board_unpressed);
    settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.rl_support_main_board:

        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_pressed);

        btnSupportPopularQuestion.setTextColor(getResources().getColor(R.color.top_panel_text_color_selected));
        btnSupportPopularQuestion.setBackgroundColor(getResources().getColor(R.color.top_panel_background_selected));

        btnSupportRequestOrders.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));
        btnSupportRequestOrders.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));

        btnSupportStayOrder.setImageResource(R.drawable.stay_order_unselected);

        fragment_tag = PopularQuestionListFragment.class.getSimpleName();

        pushFragments(questionsFragment, fragment_tag);
        messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
        service.setBackgroundResource(R.drawable.services_main_board_unpressed);
        settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);
        payments.setBackgroundResource(R.drawable.payments_main_board_unpressed);

        break;
    case R.id.tv_popular_questions:

        btnSupportPopularQuestion.setTextColor(getResources().getColor(R.color.top_panel_text_color_selected));
        btnSupportPopularQuestion.setBackgroundColor(getResources().getColor(R.color.top_panel_background_selected));

        btnSupportRequestOrders.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));
        btnSupportRequestOrders.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));

        btnSupportStayOrder.setImageResource(R.drawable.stay_order_unselected);
        fragment_tag = PopularQuestionListFragment.class.getSimpleName();
        pushFragments(questionsFragment, fragment_tag);
        break;
    case R.id.tv_my_orders:

        btnSupportRequestOrders.setBackgroundColor(getResources().getColor(R.color.top_panel_background_selected));
        btnSupportRequestOrders.setTextColor(getResources().getColor(R.color.top_panel_text_color_selected));

        btnSupportPopularQuestion.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));
        btnSupportPopularQuestion.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));

        btnSupportStayOrder.setImageResource(R.drawable.stay_order_unselected);
        fragment_tag = MyRequestOrdersListFragment.class.getSimpleName();
        pushFragments(requestList, fragment_tag);
        break;
    case R.id.iv_new_order:

        btnSupportStayOrder.setImageResource(R.drawable.stay_order_selected);

        btnSupportPopularQuestion.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));
        btnSupportPopularQuestion.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));

        btnSupportRequestOrders.setBackgroundColor(getResources().getColor(R.color.top_panel_background_unselected));
        btnSupportRequestOrders.setTextColor(getResources().getColor(R.color.top_panel_text_color_unselected));
        fragment_tag = NewOrderMainFragment.class.getSimpleName();
        pushFragments(stayOrderFragment, fragment_tag);
        break;
    case R.id.rl_payments_main_board:

        hideTopPanel();
        payments.setBackgroundResource(R.drawable.payments_main_board_pressed);
        fragment_tag = PaymentsMenu.class.getSimpleName();
        pushFragments(paymentsMenu, fragment_tag);
        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);
        messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
        service.setBackgroundResource(R.drawable.services_main_board_unpressed);
        settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);

        break;
    case R.id.rl_services_main_board:

        hideTopPanel();
        service.setBackgroundResource(R.drawable.services_main_board_pressed);
        privateCabinetFrag = new PrivateCabinetFragment();
        fragment_tag = PrivateCabinetFragment.class.getSimpleName();
        pushFragments(privateCabinetFrag, fragment_tag);
        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);
        messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
        settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);
        payments.setBackgroundResource(R.drawable.payments_main_board_unpressed);

        break;
    case R.id.rl_settings_main_board:

        hideTopPanel();
        settings.setBackgroundResource(R.drawable.settings_main_board_pressed);
        fragment_tag = SettingsFragment.class.getSimpleName();
        pushFragments(settingsFragment, fragment_tag);
        messages.setBackgroundResource(R.drawable.message_main_board_unpressed);
        service.setBackgroundResource(R.drawable.services_main_board_unpressed);
        payments.setBackgroundResource(R.drawable.payments_main_board_unpressed);
        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);

        break;

    case R.id.rl_message_main_board:

        hideTopPanel();
        messages.setBackgroundResource(R.drawable.message_main_board_pressed);
        service.setBackgroundResource(R.drawable.services_main_board_unpressed);
        payments.setBackgroundResource(R.drawable.payments_main_board_unpressed);
        helpAndSupport.setBackgroundResource(R.drawable.support_main_bord_unpressed);
        settings.setBackgroundResource(R.drawable.settings_main_board_unpressed);
        fragment_tag = MessageMain.class.getSimpleName();
        pushFragments(messageMain, fragment_tag);

        break;

    }

}

public void hideTopPanel() {
    if (dashBoard.isShown()) {
        // dashBoard.startAnimation(animUp);
        dashBoard.setVisibility(View.GONE);
    }
}

public void showTopPanel() {
    if (!dashBoard.isShown()) {
        dashBoard.setVisibility(View.VISIBLE);
        dashBoard.startAnimation(animDown);
    }
}

@Override
protected void onPause() {
    Log.e(CLASS_TAG,"ON onPause");
    // TODO Auto-generated method stub
    super.onPause();
    onBackpress = 0;
}

@Override
protected void onResume() {
    Log.e(CLASS_TAG,"ON onResume");
    // TODO Auto-generated method stub
    super.onResume();
    onBackpress = 0;
}

@Override
protected void onStart() {
    Log.e(CLASS_TAG,"ON Start");
    super.onStart();
}


}

1 个答案:

答案 0 :(得分:1)

堆栈跟踪表示您仍然在超类onCreate()中,它会重新创建片段并回调MainActivity setUnreadedMessages()。此时,tvNewMessages等成员变量未初始化。

通常,片段不应与托管活动具有此类依赖关系。考虑在那里重新设计。