0

I created a text view dynamically , but the problem is that when I want to set the text size of this text view on a button click, I get:

error: null object reference.

the code:

//in Main class

TextView textview;


//creating the text view on button click
Button mbutton1=(Button)findViewById(R.id.button1);
mbutton1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
 textview=new TextView(this);

//adding the view to the relativelayout
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT );
textview.setLayoutParams(params);

//making object for Relativelayout and add the view to activity
RelativeLayout relativel=(RelativeLayout)findViewById(R.id.relativelayout);
relative1.addView(textview);
}
});

//now here is the button which must set the size of this text view
 Button mbutton2=(Button)findViewById(R.id.button2);
mbutton2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
textview.setsize(20);

}
});
//And the error is when I click button 2 it says null object reference.

Edit: This question was closed as duplicate of another but in the other question the answers were why (null object reference)error happens , I know the causes for the problem what I need is an answer on how to set a value for a non existing object in an activity.

Hasan B.T
  • 51
  • 1
  • 7

1 Answers1

0

You must click the mbutton1 before click mbutton2

Kingyal
  • 63
  • 8