2

I am 2 days old to Android Programming. I may be comitting a mistake at the core level. If this is the case, pardon.

I am trying to add a text box to a Relative Layout. When a button is clicked. The method is bound to the button by the attribute android:onClick="method"

By doing the below.

public method (View view){
    RelativeLayout vRL = (RelativeLayout)findViewById(R.layout.rLayout);
    TextView vET = new TextView(this);
    vET.setText("Text added to view.");
    vET.setId(1);
    vRL.addView(vET);
    setContentView(R.layout.rLayout);
}

But I am getting a null pointer exception at vRL.addView(vET);

  • what is it that I am doing wrong? -OR-
  • Am I not adding the TextView element properly?
2
  • which is main setContentView ? Commented Sep 11, 2012 at 10:55
  • @SamirMangroliya it is set to rLayoutHome. How to proceed the same with inflating a layout and adding an element.? Commented Sep 11, 2012 at 11:02

5 Answers 5

1

in below line

RelativeLayout vRL = (RelativeLayout)findViewById(R.layout.rLayout);

change the R.layout.rLayout to R.id.rLayout

Sign up to request clarification or add additional context in comments.

2 Comments

yup it results in null but Why?
Because there is no any setContenView() in your Activity before accessing this RelativeLayout and findViewById() only works in there is any View inflated to Activity. Or you can inflated a View and access RelativeLayout by reference of this view...
0
setContentView(R.layout.rLayout);

put this line in onCreate() of Activity..

and this line from method()

RelativeLayout vRL = (RelativeLayout)findViewById(R.id.rLayout);

2 Comments

I am trying to change the contentview from one layout to another from an activity. I do not want to setthe view to setContentView(R.layout.rLayout); at the beginning.
Then you can not find R.id.rLayout RelativeLayout in your activity without setContentVIew() before. It always be null.
0

Replace below line with

`RelativeLayout vRL = (RelativeLayout)findViewById(R.id."id name of relative layout");` 

Comments

0

Change like this:

public method (View view){
    RelativeLayout vRL = (RelativeLayout)findViewById(R.id.rLayout);
    TextView vET = new TextView(this);
    vET.setText("Text added to view.");
    vET.setId(1);
    vRL.addView(vET);
    setContentView(R.layout.rLayout);
}

Comments

0

change the R.layout.rLayout to R.id.rLayoutR.layout.rLayout);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.