0

I am new to android programming and I can't figure out what i'm doing wrong. My code: enter image description here

Every time I run the code, the emulator works just fine, but when I try to open the app it show the error message. enter image description here

Please help. Thanks.

hata
  • 11,633
  • 6
  • 46
  • 69
Hinzu
  • 87
  • 1
  • 1
  • 4

4 Answers4

1

first you must inflate your layout by setContentView method .

second in onCreate method , bind your view .

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity_layout);
        TextView tf1 = (TextView) findViewById(R.id.tf0);
        tf1.setText("Hello World!");
    }
Adnan Abdollah Zaki
  • 4,328
  • 6
  • 52
  • 58
0

You must call setContentView before calling findViewById.

void onCreate() {
  super.onCreate()

  setContentView(R.layout.my_activity_layout)
  TextView tf1 = findViewById(R.id.tf0)
  tf1.setText("hello")
}
dimsuz
  • 8,969
  • 8
  • 54
  • 88
0

You need SetContentView(R.layout.your_layout) before calling findViewById.

For example:

super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
tf1 = findViewById(R.id.tf0);
tf1.setText("text")
Sibirman
  • 39
  • 6
0

I suspect tf1 is null because the layout hasnt been inflated yet also setContentView(view) is required to be called in onCreate to inflate the view. Also at the point you are declaring the tf1 (outside onCreate) the reference will be null.

Try this

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tf1 = (TextView) findViewById(R.id.tf0);
        tf1.setText("Hello World!");
    }
Jaime
  • 378
  • 2
  • 7