Skip to content Skip to sidebar Skip to footer

Why Are My Textviews Null?

I want if the user enters an invalid number, two TextViews should change their texts. I looked up and checked if I got more than one TextView with the same id and the ruesult was t

Solution 1:

In your onCreate(), you have to to call setContentView(R.layout.whateveryourxml). After that, but still tracing back to your onCreate, you may call errorKnowledge(). This should make sure that neither TextView is null.

Solution 2:

[Edit: Just to clarify, you do have to call the setContentView method during onCreate, or your TextViews will resolve to null. Assuming you've done that - as in the code you posted - read on!]

These lines of code don't seem right to me. They don't look as if they will do anything:

hKnowledge.getResources().getString(R.string.FehlerGefunden);
hKnowledge.getResources().getColor(android.R.color.holo_red_dark);
tKnowledge.getResources().getString(R.string.FehlerText1);
tKnowledge.getResources().getColor(android.R.color.holo_red_light);

The reason you're seeing no effect is that these are get statements that return some values, but then you don't actually use those values to do anything.

I feel like what you actually want to say is this:

hKnowledge.setText(R.string.FehlerGefunden);
hKnowledge.setTextColor(android.R.color.holo_red_dark);
tKnowledge.setText(R.string.FehlerText1);
tKnowledge.setTextColor(android.R.color.holo_red_dark);

I'd also recommend that you spend some time in your onCreate method doing all the findView work, so that you don't need to do it again and again later. (It's also a little clearer and saves you quite a bit of boilerplate java.)

You can define your various TextView elements (etc.) as private members for the class, so - as an example, just for the 2 TextViews we're already talking about:

privateTextView hKnowledge;
privateTextView tKnowledge;
...
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  hKnowledge = (TextView) findViewById(R.id.testWissenstandHeader);
  tKnowledge = (TextView) findViewById(R.id.testWissenstandText);
  ...
}

Having done this, you can then refer to the two TextViews from anywhere else in your class just as their members: hKnowledge and tKnowledge;

Post a Comment for "Why Are My Textviews Null?"