user3182266
user3182266

Reputation: 1330

Android: setting text within a TextView

Hi guys I am having some trouble setting the text within a textview so I am going to explain the situation here. First I am trying to create my own custom toast notification. Everything is fine but I want to change the text in the textview depending on an if condition. However I get a null pointer exception when I try to do it. Here is my code:

img.setOnClickListener(new OnClickListener() 
     {          
        @Override
        public void onClick(View v) 
        {               
             LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.cust_toast_layout,(ViewGroup)findViewById(R.id.ToastrelativeLayout));

                //textViewCircleDescribtion = (TextView)findViewById(R.id.textViewCircleDescribtion);

                Toast toast = new Toast(MainWindow.this);
                toast.setView(view);
                toast.setDuration(10000);                   
                toast.show();

              /*  try 
                {
                    if(Week == 1)
                        //textViewCircleDescribtion.setText(getResources().getString(R.string.circle_describ1));
                    else
                        //textViewCircleDescribtion.setText("azsdfasfasd");
                } catch (Exception e) 
                {
                    e.printStackTrace();
                }   */      
        }           
    });

The problem I think is caused because textViewCircleDescribtion is declared within a different layout than the setContentView(R.layout.activity_main_window); is there a way to fix this?

Upvotes: 0

Views: 58

Answers (3)

Pankaj Kumar
Pankaj Kumar

Reputation: 82938

Your TextView inside the view. You can find that by using view.findViewById, which looks for a child view with the given id. If this view has the given id, return this view..

So instead of using

textViewCircleDescribtion = (TextView)findViewById(R.id.textViewCircleDescribtion);

You should use

textViewCircleDescribtion = (TextView)view.findViewById(R.id.textViewCircleDescribtion);

Upvotes: 2

Preethi Rao
Preethi Rao

Reputation: 5175

Inflating of textview is wrong.Inflate it like this

textViewCircleDescribtion = (TextView)view.findViewById(R.id.textViewCircleDescribtion);

Upvotes: 0

Veaceslav Gaidarji
Veaceslav Gaidarji

Reputation: 4301

Find your TextView in inflated View

LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.cust_toast_layout,(ViewGroup)findViewById(R.id.ToastrelativeLayout));
textViewCircleDescribtion = (TextView)view.findViewById(R.id.textViewCircleDescribtion);

Upvotes: 0

Related Questions