Tech Blogging‎ > ‎

Android, Troubleshooting "W/View: couldn't find view with id"

posted Sep 5, 2017, 5:27 AM by Haris Hashim   [ updated Sep 5, 2017, 5:31 AM ]
It is not easy to troubleshoot this error without knowing why it happens! 

Error message and debug point

Eyeballing above message also does not help much! ;)

To cut a long story short, in layout xml file we declare widgets like bellow:


<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="32dp"
android:layout_marginTop="23dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/editText"
android:layout_below="@+id/editText"
android:layout_marginTop="16dp"
android:text="Button" />

Id of EditText is set using "@+id/editText"

It is used again later as "@+id/editText" when Button is positioned bellow and aligned to end of EditText.

The way "@+id"  work is that it will try to find existing id with editText label. If it is not found, new random id number is given. This kinda explain why "@+id" is used for both case of creating a new id for widget and also to refer to existing widget.

Here is a shocker. We can also do this instead of using "@+id"

android:layout_alignEnd="@id/editText"
android:layout_below="@id/editText"
So what is the different between using "@+id" and "@id"? 

Unlike the previous form, "@id" will throw compile error when existing id is not found. Layout_alignEnd and layout_bellow depend on widget with id to exist to do the relative positioning, right? And the id can not just be some newly created random id. 

When using "@+id", Android will give us this message during runtime:

"W/View: couldn't find view with id xxxxxxxxx"

Hence the hard to troubleshoot problem. Another thing is that, not all line with "@+id" is the one having problem. 

In my case, I did the following to troubleshoot.

1. Find all line in xml layout file that have "@+id" but not "id="@+id". On Windows this is done using Notepad++ find in file function with regex search keyword. The keyword is "[^id]="@\+id" (refer to picture). 

Find in files using regex

Not being an expert in regex, regexr.com website help me a lot in testing and getting the right expression.

2. Change "@+id" to "@id" and rebuild the project until the one that give compile error is found. Much of this is try an error approach.

Error found


From that troubleshooting, I found the problem to be order of widget declared in xml file when using relative layout. Fix that and problem is solved! 

Happy troubleshooting!

Comments