M
M
Maybe_V2016-03-23 13:07:06
Android
Maybe_V, 2016-03-23 13:07:06

How to fix error when recreating ViewStub?

Layout should be created on the activity by clicking on the button, for this I use ViewStub! The bottom line is this: when the button is pressed, I check whether the ViewStub exists, if not, I create it and display it on the screen, if it exists, I need to remove it!

ViewStub viewStub = null;
View v;
public void onClick(View view) {
if (viewStub == null){
    viewStub = (ViewStub) finalView.findViewById(R.id.space);
      v = viewStub.inflate();
}else if (viewStub != null){
      v.setVisibility(View.GONE);
       viewStub = null;
}
}

Everything works, when the first time I press the layout is displayed, the second time it is hidden!
But on the third click on the button, it should be recognized as non-existent and re-created,
but this does not happen and throws an error:
FATAL EXCEPTION: main java.lang.NullPointerException at com.vitaliy.useexpandablelistview.MainActivity$ListAdapter$1.onClick(MainActivity.java:167)

It seems that everything is clear what I have , but it is not clear why this happens, because when it does not exist, I create it again !!! ??? Help solve the problem!viewStub = null

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-03-23
@prokopov-vi

After you called inflate() on the ViewStub, it is no longer part of the view hierarchy, meaning you can't find it a second time with finalView.findViewById(R.id.space).
But your View has already been created, it is already in the hierarchy, only it is invisible (you have hidden it with v.setVisibility(View.GONE)).
So all you have to do is check v != null at the very beginning of onClick() , in which case make it visible: v.setVisibility(View.VISIBLE);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question