0

I want to update TextView in onCreate(), so that text should be set when Activity Interface appears, what I've tried is:

Java Code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sem_selection);

    TextView T =(TextView)findViewById(R.id.textView1); 
    T.setText("required text"); 

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

but i get error when activity starts , as soon as i comment this line :

T.setText("required text");  

App runs fine without error. How should I do this? Is there any other method?

Sufian
  • 6,405
  • 16
  • 66
  • 120
Adeel Ahmad
  • 990
  • 8
  • 22

3 Answers3

1

You are referencing TextView T from fragment you will get null because in your activity you are using activity_sem_selection and getting TextView T from activity_sem_selection layout.

So use T in onCreateView method of fragment.

For example

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment__sem_selection, container,
                false);

        TextView T =(TextView)rootView.findViewById(R.id.textView1); 
        T.setText("required text"); 

        return rootView;
    }

Note : change fragment__sem_selection with your fragment layout.

Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
  • 1
    And also, it is better practice to use lowercase letters for variables - `TextView t` and not `T` – gilonm Jul 24 '14 at 05:35
  • Thanks alot #Giru bhai :) it worked perfectly , now i just couldn't get the mistake i was making previously , it was a null pointer exception , i am a beginner , kindly elaborate , thanks in advance . – Adeel Ahmad Jul 24 '14 at 05:47
  • accepted :)p.s i just asked for a little explanation about my mistake , sir ' – Adeel Ahmad Jul 24 '14 at 05:53
0

Remove

 if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction()
             .add(R.id.container, new PlaceholderFragment()).commit();
   }
Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
0

Check textView1 is present in activity_sem_selection layout.Otherwise you will get NPE.Try to place a TextView with id textView1 in activity_sem_selection layout. Otherwise you can remove those assignment and referencing for that TextView T and place those inside fragment's onCreateView(...).

Kaushik
  • 6,150
  • 5
  • 39
  • 54