Search code examples
androidglobal-variablesmain-activity

Why does declaring global variables result in application force close


It works fine when the variables are in onCreate scope, but I need to use the variables in onDestroy scope too so I made it global variables. but then my app force closed when opened.

public class MainActivity extends Activity {

    GamePanel gamePanel = new GamePanel (this);
    EditText editText = (EditText) getLayoutInflater().inflate(R.layout.edit_text_template, null);

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    //Remove title
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    //Set fullscreen
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


    RelativeLayout.LayoutParams gameParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    gamePanel.setLayoutParams(gameParams);

    RelativeLayout.LayoutParams etParams = new RelativeLayout.LayoutParams(
            300, 100);
    etParams.leftMargin = 200;
    etParams.topMargin = 800;
    editText.setLayoutParams(etParams);

    RelativeLayout content = new RelativeLayout(this);

    content.addView(gamePanel);
    content.addView(editText);

    setContentView(content);
}

@Override
protected void onDestroy(){
    super.onDestroy();
}


}

As seen in the code, I want to use gamePanel and editText as global variables. Any idea how to do this? Or am I missing something? Thanks in advance.


Solution

  • You should initialize yours variables in OnCreate()

     GamePanel gamePanel;
        EditText editText;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        gamePanel = new GamePanel (this);
        editText = (EditText) getLayoutInflater().inflate(R.layout.edit_text_template, null);
    
    ...}