0

Hello Guys i have a strange problem i'm new in android apps developing i connected my device (Samsung A5) to Android Studio to use it instead of using an emulator. when i ran the app

package com.example.bob.myfirstapp;

import android.app.Activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b = (Button)findViewById(R.id.button);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setContentView(R.layout.contact);

            }
        });
    }
}

it runs perfectly but when i add this : Button bc = (Button)findViewById(R.id.button); inside the mainActivity class it crashes when i run it .

package com.example.bob.myfirstapp;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
/***********************************************/
Button bc = (Button)findViewById(R.id.button);
/**********************************************/
@Override
protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       Button b = (Button)findViewById(R.id.button);
       b.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               setContentView(R.layout.contact);
           }
       });
    }
}

please explain to me where is the problem and what should i do to resolve it thank you very much in advance

j2ko
  • 2,479
  • 1
  • 16
  • 29

1 Answers1

2

First of all you need to understand how java properties are initialized.

Next you need to understand how findViewById works. It lookup for views starting from DecorView aka root view which is initialized by call to setContentView.

Now you will find out that

Button bc = (Button)findViewById(R.id.button);

actually getting executed before setContentView was called. And this will cause you troubles.

Community
  • 1
  • 1
j2ko
  • 2,479
  • 1
  • 16
  • 29