Albert Lekaj
Albert Lekaj

Reputation: 11

Declaring variables outside onCreate - Android

My application stops when I declare the TextView outside the onCreate method, I'm doing this because I need do access the TextView variable from other methods as well. I'll be grateful for any kind of help.

public class MainActivity extends ActionBarActivity {
    TextView textView = (TextView)findViewById(R.id.defaultText);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        textView.setText("Hello");
    }
} 

Upvotes: 1

Views: 3546

Answers (5)

Tasneem Nabil
Tasneem Nabil

Reputation: 1

I faced this problem and i solved it by using (tag) for my view (myTextView.tag) you can lean more about this property from here:

What is the main purpose of setTag() getTag() methods of View?

I mean I declare a variable called (counter) outside onCreate method, then i find my view wherever i need using his tag.

hope this helping

Upvotes: -1

To do this:

TextView textView = (TextView)findViewById(R.id.defaultText);

You first set the content view to the Activity if not will not work.

Upvotes: 0

TehCoder
TehCoder

Reputation: 209

You can't declare a View outside a function.

TextView tv; and in OnCreate do: tv = (TextView)findViewById(...)

Upvotes: 3

mradzinski
mradzinski

Reputation: 624

As others pointed out, the error you are getting is because the view containing the TextView as a child as not yet been inflated. You should declare the strong reference and then instantiate the variable on the onCreate() method. If you insist on using such a code then I recommend you to take a look at Dependency injection.

Upvotes: 0

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

My application stops when I declare the TextView outside the onCreate method

That is because the Layout is not yet inflated in your activity thus crashing you app and I am 100% sure the error is NPE when you set the text here : textView.setText("Hello");.

Solution:

always initialized your TextView inside your Oncreate after setContentView and having your textView object as a global instance.

public class MainActivity extends ActionBarActivity {
   TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.defaultText);
        textView.setText("Hello");
    }
}

Upvotes: 4

Related Questions