Reputation: 165
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.unFocus(android.view.View)' on a null object reference.
I want to remove all the views from a Linear Layout, except the first two views. The views that i want to delete were dynamically created. This is what i've tried:
//Edit, i've called it with a wrong layout, but still not working
LinearLayout myFirstLinearLayout = findViewById(R.id.linLay);
deleteLinearLayoutChild(myFirstLinearLayout);
This is the function:
private void deleteLinearLayoutChild(LinearLayout linearView){
int childNumber = linearView.getChildCount();
Log.d("childNumb", childNumber+"");
if (childNumber > 2){
for (int i=2;i<childNumber;i++){
linearView.removeViewAt(i);
}
}
}
Upvotes: 0
Views: 422
Reputation: 126
I recommend you to use recycler view or list view to add and remove view in a view group, it will be better practice for you. Several issue may occur in future if you use your methodology , like : 1. Configure change issue 2. Memory leak issue 3. already have child during adding view issue 4. UI lagging issue(ANR may occur)
Upvotes: 1
Reputation:
You should delete the views from layout in reverse order. Check below:
for (int i = childNumber - 1; i > 1; i--){
linearView.removeViewAt(i);
}
If you use while-loop, then you have to call getChildCount
in every iteration
Upvotes: 2
Reputation: 1420
You are passing wrong layout might be :
LinearLayout myFirstLinearLayout = findViewById(R.id.linLay);
deleteLinearLayoutChild(myFirstScrollView); //
deleteLinearLayoutChild(myFirstLinearLayout) // pass myFirstLinearLayout
Also these are the method you can use ;
myFirstLinearLayout .removeView(view)//remove particular view
myFirstLinearLayout.removeViewAt(position);//remove view from particular position
Upvotes: 1