App crashes when setting background colour - java

Every time I run my app it crashes giving me a nullpointerexception, I want to programatically change my background depending on the scenario, here is my code:
Main Activity:
public class Activity extends AppCompatActivity {
ConstraintLayout layout;
String messageSafe = "Item is Safe for Consumption";
String messageUnSafe = "Item is NOT Safe for Consumption";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
layout = new ConstraintLayout(this);
if (matched.length == 0) {
layout.setBackgroundResource(R.drawable.background_safe);
setContentView(layout);
changeColor("#00FF00");
messageView.setText(messageSafe);
}
else{
layout.setBackgroundResource(R.drawable.background_unsafe);
setContentView(layout);
changeColor("#FF0000");
messageView.setText(messageUnSafe);
}
ListView listContains = (ListView) findViewById(R.id.lvItemsFound);
ArrayAdapter<String> contains = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, foundItems);
listContains.setAdapter(contains);
ListView listRestricted = (ListView) findViewById(R.id.lvItemsRestricted);
ArrayAdapter<String> found = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matched);
listRestricted.setAdapter(found);
}

You are losing reference to your old view because you changed the layout to a new ConstraintLayout object. This means you now don't have your ListView objects and other items in your XML because that View is gone. It's not the ContentView anymore. If you want to work on the existing layout, you need to give the root view an ID.
<constraintlayout android:id="#+id/container" ... />
Then you can reference that ID with findViewById(R.id.container) and use the object you get from it to change your background like you are doing.
Try this:
1. Give your root view an ID
2. Set a ConstraintLayout object with ConstraintLayout layout = findViewById(R.id.container) (Note: You can call it anything, not just container, I am just going off my example from above, since I gave it the ID 'container')
3. call setBackgroundResource() like you are doing.
4. No need to call setContentView() again, this was set in the beginning, and you do not want to reset it to a new view you just constructed like you were initially doing.
5. You shouldn't crash when trying to call setAdapter() to your ListView now because you don't have a reference to an object that isn't in your content view.
layout = (ConstraintLayout)findViewById(R.id.container);
if (matched.length == 0) {
layout.setBackgroundResource(R.drawable.background_safe);
changeColor("#00FF00"); //assuming this is some local function?
messageView.setText(messageSafe);
}
else{
layout.setBackgroundResource(R.drawable.background_unsafe);
changeColor("#FF0000");
messageView.setText(messageUnSafe);
}

You are trying to set the background by replacing the view of your activity (this is what setContentView() does). This causes a null pointer exception later because the old layout (defined in the XML) has been replaced, so your list view no longer exists.
Instead, you should get a reference to the existing root view (the ConstraintLayout, although if you're just setting background you can just reference it as a View, no need to be so specific), and set the background on it, like so:
findViewById(R.id.container).setBackgroundResource(R.drawable.unsafe);
You'll also need to give the containing layout an id in the existing layout XML:
<android.support.constraint.ConstraintLayout
android:id="#+id/container"
... etc.

Related

How to connect a ListView that's not in the main layout?

I am working on my first rather big project in android studio and I've been struggling for the past three days with this:
My app has a bottom navigation component that opens 3 other fragments and I was wondering how I could implement a ListView into one of those 3 fragments. I managed to put the ListView in the main layout (activity_main.xml), but as soon as I put the ListView into a layout that's not the main layout I get an NPE. I guess that's because if I try to link the ListView to its data with findViewById(R.id.ListView) it's looking for ListView in activity_main. The code that tries to link the ListView to the component in the layout-file is written in the onCreate in the mainActivity.java. How can I tell the programm to look for the ListView in layout_With_List.xml?
I read on another question that I need to change the setContentView(R.layout.activity_main) in onCreate to setContentView(R.layout.layout_With_List), but that just creates another error.
So how can I properly put a ListView into another fragment, so it won't float around in the main layout when I change tabs with the bottom navigation AND make it display data?
The error i'm getting:
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
This is the Relevant code bits:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv_productlist = findViewById(R.id.lv_productlist);
showFoodOnListView(db_helper);
}
The code that passes data to the ListView:
private void showFoodOnListView(DB_Helper db_helper2) {
food_ArrayAdapter = new ArrayAdapter<Product_Model>(MainActivity.this, android.R.layout.simple_list_item_1, db_helper2.getEveryone());
lv_productlist.setAdapter(food_ArrayAdapter);
}
layout_With_List.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lv_productlist"
android:name="com.ocdm.prepper.ListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ListFragment"
tools:listitem="#layout/fragment_list" />
===========================SOLUTION===============================
Thanks to [https://stackoverflow.com/users/4039784/hayssam-soussi]
I could figure it out.
lv_productlist = (ListView) view.findViewById(R.id.R.id.lv_productlist);
showFoodOnListView(db_helper);
I had to move the code above into the Layouts corresponding java class, e.g fragment_A.java.
Then I had to move the method showFoodOnListView into fragment_A.java
and set the context to getActivity():.
food_ArrayAdapter = new ArrayAdapter<Product_Model>(getActivity(), android.R.layout.simple_list_item_1, db_helper2.getEveryone());
Let's say you need to add the ListView to Fragment A
First you have to create a layout for Fragment A (i.e fragment_a.xml)
Add your ListView to fragment_a.xml
Then your FragmentA.java code should look like this:
public class FragmentA extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_a, container, false);
// get the reference of ListView
lv_productlist = (ListView) view.findViewById(R.id.lv_productlist);
showFoodOnListView(db_helper);
return view;
}
}

Adding checkboxes into a ListView

Hello I'm currently trying to make my first app on android and I've gotten some problems. I'm trying to make a todo-list app so want some kind of input to be transformed into checkboxes. I've made it work with radio buttons using radioGroup. But when using Checkboxes with ListView it just doesn't work.
Here's my code:
public class MainActivity extends AppCompatActivity {
EditText t;
ListView listView;
ArrayList<CheckBox> checkList = new ArrayList<>();
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void add(View view){
t = findViewById(R.id.input);
String s = t.getText().toString();
CheckBox check = new CheckBox(this);
checkList.add(check);
listView = findViewById(R.id.list);
checkList.get(i).setText(s);
listView.addView(checkList.get(i));
i++;
t.setText("");
}}
The app crashes saying something about adapterView
You're unfortunately doing something wrong here. You are trying to add your view to Listviews on
listView.addView(checkList.get(i));
This is not the correct way to use ListViews. You have to use an adapter. The adapter would need to provide data for the listview to load.
Please have a look at this tutorial for how to use listviews.
Below is a summary of the steps to use a listView correctly.
Create a new layout file (say custom_cell.xml) inside your layouts folder.
Insert a checkbox inside your custom_cell.xml and place an Id which you can use later to identify the checkbox
Create an adapter for your listview
Override the getView method
Inside the getView method, inflate a new cell using the custom_cell.xml or reuse an existing cell if provided
Reference the Checkbox by using the Id you provided in the custom_cell.xml file

Programatically add LinearLayout with Text and Image

I'm trying to add a LinearLayout for each item in a varying Array. I need each item to have an image and text horizontally, but for now I am testing with the text.
Keeping in mind this code is in a Fragment.
I think the error is with the getContext() but not to sure.
The code I currently have is:
List<PaymentOption> paymentOptions = aTradeItem.getPaymentOptions();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(ImageUtils.dpToPx(16), ImageUtils.dpToPx(4), ImageUtils.dpToPx(16), ImageUtils.dpToPx(4));
LinearLayout.LayoutParams lineparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ImageUtils.dpToPx(1));
lineparams.setMargins(0, ImageUtils.dpToPx(4), 0, ImageUtils.dpToPx(4));
if (paymentOptions != null && paymentOptions.size() > 0) {
for (PaymentOption t : paymentOptions) {
LinearLayout paymentOptionLayout = new LinearLayout(getContext());
paymentOptionLayout.setOrientation(LinearLayout.HORIZONTAL);
paymentOptionLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
TextView heading = new TextView(getContext());
heading.setText(t.getDescription());
heading.setTextColor(getResources().getColor(R.color.light_text));
heading.setLayoutParams(lp);
paymentOptionLayout.addView(heading);
}
}
There are no errors, the data just doesnt populate on the screen. I have tried Hardcoding random text in the setText() but with no success.
Thank you
You're not adding your paymentOptionLayout to the layout which is set as your content View. Basically what you're doing is programatically creating the layout, but then doing nothing with it.
By default your activity_main.xml file will come with some type of layout depending on how you setup your code, for example a blank activity's xml file would be
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity"
android:id="#+id/RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
However when you create layouts programmatically the way you did, you must append them to the layout which is the parent layout in your XML file.
So I think what you need to do is the following.
RelativeLayout rl=(RelativeLayout)findViewById(R.id.RelativeLayout); //getting the view from the xml file. Keep in mind that the id is defiend in the xml file by you
List<PaymentOption> paymentOptions = aTradeItem.getPaymentOptions();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(ImageUtils.dpToPx(16), ImageUtils.dpToPx(4), ImageUtils.dpToPx(16), ImageUtils.dpToPx(4));
LinearLayout.LayoutParams lineparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ImageUtils.dpToPx(1));
lineparams.setMargins(0, ImageUtils.dpToPx(4), 0, ImageUtils.dpToPx(4));
if (paymentOptions != null && paymentOptions.size() > 0) {
for (PaymentOption t : paymentOptions) {
LinearLayout paymentOptionLayout = new LinearLayout(getContext());
paymentOptionLayout.setOrientation(LinearLayout.HORIZONTAL);
paymentOptionLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
TextView heading = new TextView(getContext());
heading.setText(t.getDescription());
heading.setTextColor(getResources().getColor(R.color.light_text));
heading.setLayoutParams(lp);
paymentOptionLayout.addView(heading);
rl.addView(paymentOptionLayout); //adding the view to the parent view
}
}
Please note that from the looks of your code, you're really just reimplementing listView which is an available layout in android. I think you should take a look at that.
getContext() is a method of activity class. It returns the context view only for currently running activity.
For Fragment either pass the instance of current activity class via constructor or use getActivity() method or this instead of getContext()
See here for help
Using context in a fragment
How to add view into LinearLayout of Fragment by onClick?
Also add paymentOptionLayout to the parent layout view right after for loop.

parentActivityName forces onCreate

In my Android manifest, I am specifying a parentActivityName in order to utilise the back button displayed in the activity.
I find this however re-calls onCreate of the previous activity, in which I do several network calls and set up a recycler view widget.
This causes the screen to refresh entirely, I'd like to avoid this and deal with the recyclerview and what new content to display and delete to ensure the user flow is not jolted.
I currently set my application up in onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container_list);
final SwipeRefreshLayout swiperefreshContainerListRecyclerView = (SwipeRefreshLayout) this.findViewById(R.id.swiperefresh_container_list_recyclerview);
swiperefreshContainerListRecyclerView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshContainerList();
}
}
);
// Get a handle on our RecyclerView for interactin and setup
containerListRecyclerView = (RecyclerView) findViewById(R.id.container_list_recyclerview);
// Grab a new LayoutManager
containerListLayoutManager = new LinearLayoutManager(this);
// Grab a new adapter
List<ContainerModel> containers = new ArrayList<>();
containerListRecyclerAdapter = new ContainerListRecyclerViewAdapter(containers, this);
// Better performance as the size of our RecyclerView does not change
containerListRecyclerView.setHasFixedSize(true);
// Attach our LayoutManager to our RecyclerView
containerListRecyclerView.setLayoutManager(containerListLayoutManager);
// Wire up adapter for RecyclerView
containerListRecyclerView.setAdapter(containerListRecyclerAdapter);
cAdvisorService = new CAdvisorService();
cAdvisorService.fetchDataFromService(context, containerListRecyclerAdapter);
System.out.println("Running onCreate!");
}
I already have logic within my cAdvisorService to deal with removing and adding items into the RecyclerView.
How do I deal with the fact that onCreate is called each time, forcing new instances of my RecyclerView and cAdvisorService?
There way to achieve this by declaring your parent activity in your Android manifest as
android:launchMode="singleTop"
, see more at: How can I return to a parent activity correctly?

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

I have to switch between two layouts frequently. The error is happening in the layout posted below.
When my layout is called the first time, there doesn't occur any error and everything's fine. When I then call a different layout (a blank one) and afterwards call my layout a second time, it throws the following error:
> FATAL EXCEPTION: main
> java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
My layout-code looks like this:
tv = new TextView(getApplicationContext()); // are initialized somewhere else
et = new EditText(getApplicationContext()); // in the code
private void ConsoleWindow(){
runOnUiThread(new Runnable(){
#Override
public void run(){
// MY LAYOUT:
setContentView(R.layout.activity_console);
// LINEAR LAYOUT
LinearLayout layout=new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
// TEXTVIEW
layout.addView(tv); // <========== ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT
et.setHint("Enter Command");
layout.addView(et);
}
}
}
I know this question has been asked before, but it didn't help in my case.
The error message says what You should do.
// TEXTVIEW
if(tv.getParent() != null) {
((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); // <========== ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT
simply pass the argument
attachtoroot = false
View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);
I came here on searching the error with my recyclerview but the solution didn't work (obviously). I have written the cause and the solution for it in case of recyclerview. Hope it helps someone.
The error is caused if in the onCreateViewHolder() the following method is followed:
layoutInflater = LayoutInflater.from(context);
return new VH(layoutInflater.inflate(R.layout.single_row, parent));
Instead it should be
return new VH(layoutInflater.inflate(R.layout.single_row, null));
I got this message while trying to commit a fragment using attach to root to true instead of false, like so:
return inflater.inflate(R.layout.fragment_profile, container, true)
After doing:
return inflater.inflate(R.layout.fragment_profile, container, false)
It worked.
You must first remove the child view from its parent.
If your project is in Kotlin, your solution will look slightly different than Java. Kotlin simplifies casting with as?, returning null if left side is null or cast fails.
(childView.parent as? ViewGroup)?.removeView(childView)
newParent.addView(childView)
Kotlin Extension Solution
If you need to do this more than once, add this extension to make your code more readable.
childView.removeSelf()
fun View?.removeSelf() {
this ?: return
val parentView = parent as? ViewGroup ?: return
parentView.removeView(this)
}
It will safely do nothing if this View is null, parent view is null, or parent view is not a ViewGroup
frameLayout.addView(bannerAdView); <----- if you get error on this line the do like below..
if (bannerAdView.getParent() != null)
((ViewGroup) bannerAdView.getParent()).removeView(bannerAdView);
frameLayout.addView(bannerAdView); <------ now added view
If other solution is not working like:
View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);
check for what are you returning from onCreateView of fragment is it single view or viewgroup? in my case I had viewpager on root of xml of fragment and I was returning viewpager, when i added viewgroup in layout i didnt updated that i have to return viewgroup now, not viewpager(view).
My error was define the view like this:
view = inflater.inflate(R.layout.qr_fragment, container);
It was missing:
view = inflater.inflate(R.layout.qr_fragment, container, false);
In my case it happens when i want add view by parent to other view
View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(lyt); // -> crash
you must add parent view like this
View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(root);
Simplified in KOTLIN
viewToRemove?.apply {
if (parent != null) {
(parent as ViewGroup).removeView(this)
}
}
In my case, I had id named as "root" for constraint layout, which was conflicting the existing parent root id.
Try to change the id.
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/root" //<--It should not named as root.
android:layout_width="match_parent"
android:layout_height="match_parent"
</androidx.constraintlayout.widget.ConstraintLayout>
In my case the problem was caused by the fact that I was inflating parent View with <merge> layout. In this case, addView() caused the crash.
View to_add = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, true);
// parent_layout.addView(to_add); // THIS CAUSED THE CRASH
Removing addView() helped to solve the problem.
The code below solved it for me:
#Override
public void onDestroyView() {
if (getView() != null) {
ViewGroup parent = (ViewGroup) getView().getParent();
parent.removeAllViews();
}
super.onDestroyView();
}
Note: The error was from my fragment class and by overriding the onDestroy method like this, I could solve it.
My problem is related to many of the other answers, but a little bit different reason for needing to make the change... I was trying to convert an Activity to a Fragment. So I moved the inflate code from onCreate to onCreateView, but I forgot to convert from setContentView to the inflate method, and the same IllegalStateException brought me to this page.
I changed this:
binding = DataBindingUtil.setContentView(requireActivity(), R.layout.my_fragment)
to this:
binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)
That solved the problem.
You just need to pass attachToRoot parameter false.
mBinding = FragmentCategoryBinding.inflate(inflater, container, false)
If you're using ViewBinding, make sure you're referring to the right binding!
I had this issue when I was trying to inflate a custom dialog from within an activity:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertBinding alertBinding = AlertBinding.inflate(LayoutInflater.from(this), null, false);
builder.setView(binding.getRoot()); // <--- I was using binding (which is my Activity's binding), instead of alertBinding.
This is how I do my custom dialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
android.view.View views = getLayoutInflater().inflate(layout_file, null, false);
builder.setView(views);
dialog = builder.create();
dialog.show();
I changed it into this and its works for me, I hope this helps
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(layout_file);
dialog.show();
check if you already added the view
if (textView.getParent() == null)
layout.addView(textView);
if(tv!= null){
((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
I was facing the same error, and look what I was doing. My bad, I was trying to add the same view NativeAdView to the multiple FrameLayouts, resolved by creating a separate view NativeAdView for each FrameLayout, Thanks
In my case I was accidentally returning a child view from within Layout.onCreateView() as shown below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.activity_deliveries, container, false);
RecyclerView rv = (RecyclerView) v.findViewById(R.id.deliver_list);
return rv; // <- here's the issue
}
The solution was to return the parent view (v) instead of the child view (rv).
I found another fix:
if (mView.getParent() == null) {
myDialog = new Dialog(MainActivity.this);
myDialog.setContentView(mView);
createAlgorithmDialog();
} else {
createAlgorithmDialog();
}
Here i just have an if statement check if the view had a parent and if it didn't Create the new dialog, set the contentView and show the dialog in my "createAlgorithmDialog()" method.
This also sets the positive and negative buttons (ok and cancel buttons) up with onClickListeners.
In my case, I had an adapter which worked with a recyclerView, the items that were being passed to the adapter were items with their own views.
What was required was just a LinearLayout to act as a container for every item passed, so what I was doing was to grab the item in the specified position inside onBindViewHolder then add it to the LinearLayout, which was then displayed.
Checking the basics in docs,
When an item scrolls off the screen, RecyclerView doesn't destroy its
view
Therefore, with my items, when I scroll towards a direction, then change towards the opposite direction - fast, the racently displayed items have not been destroyed, meaning, the items are still associated with the LinearLayout container, then on my end, I'm trying to attach to another container, which ends up with a child having a parent already.
My solution was to check if the specified item has a parent, if it has, I assign it to a variable, then call parentVar.removeView(item), then assign the new parent.
Here's the sample code(Problematic Adapter):
override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {
holder.linearLayoutContainer.removeAllViewsInLayout()
val questionWidget: QuestionWidget =
dataSource[position]
questionWidget.setValueChangedListener(this)
holder.linearLayoutContainer.addView(questionWidget)/*addView throws error once in a while*/
}
inner class QuestionWidgetViewHolder(mView: View) :
RecyclerView.ViewHolder(mView) {
val linearLayoutContainer: LinearLayout =
mView.findViewById(R.id.custom_question_widget_container)
}
Content of the R.id.custom_question_widget_container:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/custom_question_widget_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical"
android:padding="10dp" />
So, the questionWidget seems to have been retaining the parent for almost 4 steps outside visibility, and when I scroll to the opposite direction fast, I would encounter it still with its parent, then I'm attempting to add it to another container.
Here's the fix - option 1:
override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {
holder.linearLayoutContainer.removeAllViewsInLayout()
val questionWidget: QuestionWidget =
dataSource[position]
questionWidget.setValueChangedListener(this)
val initialWidgetParent : ViewParent? = questionWidget.parent
//attempt to detach from previous parent if it actually has one
(initialWidgetParent as? ViewGroup)?.removeView(questionWidget)
holder.linearLayoutContainer.addView(questionWidget)
}
Another better solution - option 2:
override fun onBindViewHolder(holder: QuestionWidgetViewHolder, position: Int) {
holder.linearLayoutContainer.removeAllViewsInLayout()
val questionWidget: QuestionWidget =
dataSource[position]
questionWidget.setValueChangedListener(this)
val initialWidgetParent : ViewParent? = questionWidget.parent
//if it's in a parent container already, just ignore adding it to a view, it's already visible
if(initialWidgetParent == null) {
holder.linearLayoutContainer.addView(questionWidget)
}
}
Actually, it's much of asking the child if it has a parent before adding it to a parent.
I tried all the things that you guys suggested, with no luck.
But, I managed to fix it by moving all my binding initializations from onCreate to onCreateView.
onCreate(){
binding = ScreenTicketsBinding.inflate(layoutInflater)
}
MOVE TO
onCreateView(...){
binding = ScreenTicketsBinding.inflate(layoutInflater)
}
You can use this methode to check if a view has children or not .
public static boolean hasChildren(ViewGroup viewGroup) {
return viewGroup.getChildCount() > 0;
}
My case was different the child view already had a parent view i am adding the child view inside parent view to different parent. example code below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/lineGap"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black1"
android:layout_gravity="center"
android:gravity="center"
/>
</LinearLayout>
And i was inflating this view and adding to another LinearLayout, then i removed the LinaarLayout from the above layout and its started working
below code fixed the issue:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/black1" />
It happened with me when I was using Databinding for Activity and Fragments.
For fragment - in onCreateView we can inflate the layout in traditional way using inflater.
and in onViewCreated method, binding object can be updated as
binding = DataBindingUtil.getBinding<FragmentReceiverBinding>(view) as FragmentReceiverBinding
It solved my issue
In my case, I was doing this (wrong):
...
TextView content = new TextView(context);
for (Quote quote : favQuotes) {
content.setText(quote.content);
...
instead of (good):
...
for (Quote quote : favQuotes) {
TextView content = new TextView(context);
content.setText(quote.content);
...
If you are working with MaterialAlertDialog, this worked for me:
(yourChildView.parent as? ViewGroup)?.removeView(yourChildView)
If in your XML you have layout with id "root" It`s problem, just change id name

Categories