TextView.setText (Android) is causing crashes.. any idea why?
Asked Answered
O

4

11

Trying to get started with Android development, and doing some basic work with TextViews..

For some reason TextView's setText() method is causing huge problems for me.. here's a simplified version of my code to show what I mean:

package com.example.testapp;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        text = (TextView) findViewById(R.id.text1);  
        setContentView(R.layout.activity_main);
        text.setText("literally anything");
    }
}

This will cause a crash, and I don't understand why.. if I create the TextView within the onCreate it works just fine, but if I create it outside of it, it doesn't.. why is that? Has the line "TextView text;" not been executed yet or something?

Thanks!

Odont answered 8/8, 2013 at 20:1 Comment(0)
S
11

You need to call setContentView() before initializing the TextView so that your Activity has access to all the layout components.

setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);  

text.setText("literally anything");
Sculpture answered 8/8, 2013 at 20:2 Comment(0)
F
3

switch these 2 lines

text = (TextView) findViewById(R.id.text1);  
    setContentView(R.layout.activity_main);

you need to set the content first

Fungible answered 8/8, 2013 at 20:2 Comment(0)
B
2

From docs:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

So this means that if you will reference your views in the layout, you must first set the content view and already then call findViewById method to reference child views of the layout resource defining your activity's UI

Brevet answered 8/8, 2013 at 20:9 Comment(0)
H
2
text = (TextView) findViewById(R.id.text1);  
setContentView(R.layout.activity_main);
text.setText("literally anything");

If "literally anything" is a variable, which often may be the case, be sure that it isn't throwing a NullPointerException. I kept having that problem myself. I fixed it to be:

    text = (TextView) findViewById(R.id.text1);  
    setContentView(R.layout.activity_main);
    try {
         text.setText("literally anything");
    } catch (NullPointerException e) {
         // Do something
    }

Exceptions can be really useful, so if you're a beginning programmer, I suggest you put exception handling on your list of things to learn soon.

Hb answered 19/7, 2017 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.