Search code examples
androidforceclose

No error but force close


I'm new to Android. I'm writing simple code to change a TextView depending on an EditText with button. I have no error in code. But when I execute it from a device, I get a force close.

Here's my code:

public class MainActivity extends Activity {

    //EditText et = (EditText)findViewById(R.id.editText1); << Error if uncomment
    //TextView tv = (TextView)findViewById(R.id.textView1); << Error if uncomment

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Solution

  • You cannot use findViewById() to initialize class variables in place

    public class MainActivity extends Activity {
    
        EditText  et;
        TextView  tv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // move these here
            et = (EditText)findViewById(R.id.editText1);
            tv = (TextView)findViewById(R.id.textView1);
        }
    
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    }
    

    If you think about it, the layout will only get initialized after the call to setContentView so you cannot find elements in that layout before it is even initialized or even set as the layout for the activity.