Android view findviewbyid null

findViewById returns NULL when using Fragment

I’m new to Android developing and of course on Fragments.

I want to access the controls of my fragment in main activity but ‘findViewById’ returns null. without fragment the code works fine.

Here’s part of my code:

The fragment:

the onCreate of MainActivity:

on this point the txtXML is null.

What’s Missing in my code or what should I do?

7 Answers 7

Try like this on your fragments on onCreateView

You should inflate the layout of the fragment on onCreateView method of the Fragment then you can simply access it’s elements with findViewById on your Activity .

In this Example my fragment layout is a LinearLayout so I Cast the inflate result to LinearLayout.

I’m late, but for anyone else having this issue. You should be inflating your view in the onCreateView method. Then override the onCreateActivity method and you can use getView().findViewById there.

You can’t access the the view of fragment in activity class by findViewById instead what you can do is.

You must have an object of Fragment class in you activity file, right? create getter method of EditText class in that fragment class and access that method in your activity.

create a call back in Fragment class on the event where you need the Edittext obj.

Eclipse menu -> Project -> Clean.

update

2) If you have 2 or more instances of ‘main’ layout, check if all of them have a view with ‘txtXML’ id

A Fragment is a piece of an application’s user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager, which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager().

The Fragment class can be used many ways to achieve a wide variety of results. It is core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.

Источник

Android ViewPager findViewById not working — Always returning null

I have this code up there ^^ . Pretty much taken directly from http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizontal-view-paging/ . I’m still pretty new in the world of android developement :/

Now I’m trying to access a spinner control and some buttons inside the «pages». But findViewById keeps returning null!

I remember something about the layout doesn’t exist really inside the code and has to be inflated first, which is happening in the instantiateItem() function. And it’s pretty obvious that it’s going into the «view» variable. But when I call view.findViewById(R.id.light1_off);

which is a button by the way, it is always returning ZERO! I even made sure it only called when it was actually that page being loaded. But no matter what I did, it always keep returning a null and I get a nasty nullpointer exception.

Could someone help me out here? I’m pretty much out of ideas, and Google isn’t of any help, already been to page 5 on about 10 different search terms.

3 Answers 3

After much frustration and pulling my hair out over this issue, I have solved it! At least for me. Assuming you used the tutsplus tutorial like I did, you have separate XML files for your screens. Now, I assume those layout XMLs contain layouts within them (ie. LinearLayout, RelativeLayout, etc.). Now, those layouts contain your button and other widgets. What you have to do to be able to findViewById is, in the actual switch statement in the instatiateItem method, initialize your button in this way:

So. first you have to inflate the view, then initialize the layout held within the view by casting the type of layout (RelativeLayout) and calling .findViewById(resource id). Then, you initialize the actual widget you’re looking for by doing the same, but casting the widget type (Button) and calling .findViewById(resource id).

This worked for me, so I hope this saves you some trouble! Took forever for me to figure out.

Just guess as you don’t show xml for inflated. Do you use +@id. If not give it a try.

You can avoid all this dirty job just adding setContentView(R.layout.youlayout) before findViewById

Not the answer you’re looking for? Browse other questions tagged android android-layout or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  Как удалить самсунг аккаунт без пароля андроид 11

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

findViewByID returns null

First of all: yes, I read all the other threads on this topic. And not only those from this site. (you see, I’m a little frustrated)

Most of them come with the advice to use android:id instead of just id in the XML file. I did.

From others, I learned, that View.findViewById works different than Activity.findViewById . I handled that, too.

In my location_layout.xml , I use:

In my Activity I do:

and in my custom view class:

which returns null . Doing this, my Activity works fine. So maybe it’s because of the Activity.findViewById and View.findViewById differences. So I stored the context passed to the customs view constructor locally and tried:

which also returned null .

Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my custom view, so that the View.findViewById should work as supposed. Suprise: it didn’t solve anything.

So what the heck am I doing wrong?

I’ll appreciate any comments.

29 Answers 29

Possibly because you are calling it too early. Wait until onFinishInflate() . Here is a sample project demonstrating a custom View accessing its contents.

Possibly, you are calling findViewById before calling setContentView ? If that’s the case, try calling findViewById AFTER calling setContentView

Make sure you don’t have multiple versions of your layout for different screen densities. I ran into this problem once when adding a new id to an existing layout but forgot to update the hdpi version. If you forget to update all versions of the layout file it will work for some screen densities but not others.

FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.

This would be wrong

This is correct

Alongside the classic causes, mentioned elsewhere:

  • Make sure you’ve called setContentView() before findViewById()
  • Make sure that the id you want is in the view or layout you’ve given to setContentView()
  • Make sure that the id isn’t accidentally duplicated in different layouts

There is one I have found for custom views in standard layouts, which goes against the documentation:

In theory you can create a custom view and add it to a layout (see here). However, I have found that in such situations, sometimes the id attribute works for all the views in the layout except the custom ones. The solution I use is:

    Replace each custom view with a FrameLayout with the same layout properties as you would like the custom view to have. Give it an appropriate id , say frame_for_custom_view .

which puts the custom view in the frame.

In my case, I had 2 activites in my project, main.xml and main2.xml . From the beginning, main2 was a copy of main , and everything worked well, until I added new TextView to main2 , so the R.id.textview1 became available for the rest of app. Then I tried to fetch it by standard calling:

and it was always null. It turned out, that in onCreate constructor I was instantiating not main2 , but the other one. I had:

I noticed this after I arrived here, on the site.

A answer for those using ExpandableListView and run into this question based on it’s title.

I had this error attempting to work with TextViews in my child and group views as part of an ExpandableListView implementation.

You can use something like the following in your implementations of the getChildView() and getGroupView() methods.

FWIW, I don’t see that anyone solved this in quite the same way as I needed to. No complaints at compile time, but I was getting a null view at runtime, and calling things in the proper order. That is, findViewById() after setContentView(). The problem turned out that my view is defined in content_main.xml, but in my activity_main.xml, I lacked this one statement:

When I added that to activity_main.xml, no more NullPointer.

I’m pretty new to Android/Eclipse, by mistake I added the UI stuff to activity_main.xml instead of fragment_main.xml . Took me some hours to figure that out.

I had this same problem. I was using a third-party library that allows you to override their adapter for a GridView and to specify your own layout for each GridView cell.

I finally realized what was happening. Eclipse was still using the library’s layout xml file for each cell in the GridView, even though it gave no indication of this. In my custom adapter, it indicated that it was using the xml resource from my own project even though at runtime, it wasn’t.

Читайте также:  Топ языков для программирования android

So what I did was to make sure my custom xml layouts and ids were different from those still sitting in the library, cleaned the project and then it started reading the correct custom layouts that were in my project.

In short, be careful if you’re overriding a third-party library’s adapter and specifying your own layout xml for the adapter to use. If your layout inside your project has the same file name as that in the library, you might encounter a really difficult-to-find bug!

Источник

java.lang.NullPointerException: Attempt to invoke virtual method ‘android.view.View android.view.View.findViewById(int)’ on a null object reference

I have a BlankFragment

and it’s layout is:

Here is the MainActivity

and here is the layout of MainActivity

In the onCreate method of activity I am adding fragment to layout. This works fine unless I try to change the Text using setText method.

And I get this error:

referring to this line

Can somebody explain what’s causing this exception?

6 Answers 6

Don’t

Do

line causing issue, becuase calling setText method of Fragment before adding Fragment in FragmentManager .

Call setText method after adding bf Fragment:

The problem is FragmentTransaction is async by default

Then you still can’t get the Fragment yet, you have to get it from the FragmentTransaction

This article helped me to understand this problem better

do it in onCreateView();

You can use a temporary variable that can hold the String while the View is not yet created.

My assumption is that you want to instantiate your BlankFragment with some initial text as well as allowing the text to be set later on from your MainActivity .

In that case I would first change the the Fragment to accept an initial text like so:

The Activity code would then look like the following:

Note that the null-check of savedInstanceState is to guard for Activity-recreation for instance due to configuration changes.

Источник

FindViewByID возвращает null

Прежде всего: да, я прочитал все другие темы по этой теме. И не только из этого сайта … (видите ли, я немного расстроен)

Большинство из них приходят с советами по использованию android:id вместо простого id в XML-файле. Я сделал.

Из других я узнал, что View.findViewById работает не так, как Activity.findViewById . Я тоже это обработал.

В моем location_layout.xml я использую:

В моей деятельности я делаю:

И в моем классе пользовательских представлений:

null возвращает null . Выполняя это, моя деятельность работает нормально. Возможно, это View.findViewById различиями Activity.findViewById и View.findViewById . Поэтому я сохранил контекст, переданный конструктору вида таможни локально, и попытался:

Который также возвратил null .

Затем я изменил свой пользовательский вид, чтобы расширить ViewGroup вместо этого View и изменил location_layout.xml чтобы TextView был прямым дочерним элементом моего пользовательского представления, так что View.findViewById должен работать так, как предполагалось. Suprise: он ничего не решал.

Так что, черт возьми, я поступаю неправильно?

Буду признателен за любые комментарии.

Возможно потому, что вы называете это слишком рано. Подождите, пока onFinishInflate() . Вот пример проекта, демонстрирующий пользовательский View доступ к его содержимому.

Возможно, вы вызываете findViewById перед вызовом setContentView ? Если это так, попробуйте вызвать findViewById ПОСЛЕ вызова setContentView

Убедитесь, что у вас нет нескольких версий макета для разных плотностей экрана. Однажды я столкнулся с этой проблемой при добавлении нового идентификатора в существующий макет, но забыл обновить версию hdpi. Если вы забудете обновить все версии файла макета, он будет работать для некоторых плотностей экрана, но не для других.

В моем случае у меня было 2 активности в моем проекте, main.xml и main2.xml . С самого начала main2 был копией main , и все работало хорошо, пока я не добавил новый TextView к main2 , поэтому R.id.textview1 стал доступен для остальных приложений. Затем я попытался получить его по стандартным вызовам:

И это всегда было нулевым. Оказалось, что в конструкторе onCreate я main2 экземпляр не main2 , а другой. Я имел:

Я заметил это после того, как приехал сюда, на сайт.

Наряду с классическими причинами, упомянутыми в другом месте:

  • Убедитесь, что вы вызвали setContentView() перед findViewById()
  • Убедитесь, что id вы хотите, находится в представлении или макете, который вы setContentView() для setContentView()
  • Убедитесь, что id не случайно дублируется в разных макетах

Есть один, который я нашел для пользовательских представлений в стандартных макетах, что противоречит документации:

Теоретически вы можете создать собственное представление и добавить его в макет ( см. Здесь ). Однако я обнаружил, что в таких ситуациях атрибут id работает для всех представлений в макете, кроме пользовательских. Решение, которое я использую:

    Замените каждое настраиваемое представление на FrameLayout с теми же свойствами макета, что и пользовательский вид. Дайте ему соответствующий id , скажем frame_for_custom_view .

Который помещает пользовательский вид в фрейм.

FindViewById может быть нулевым, если вы вызываете неправильный суперконструктор в пользовательском представлении. Тег ID является частью attrs, поэтому, если вы игнорируете attrs, вы удаляете ID.

Читайте также:  Burnout paradise android 4pda

Это было бы неправильно

Ответ для тех, кто использует ExpandableListView, и запускать этот вопрос на основе его названия.

У меня была ошибка при попытке работать с TextViews в моих дочерних и групповых представлениях как часть реализации ExpandableListView.

В реализациях методов getChildView () и getGroupView () вы можете использовать что-то вроде следующего.

Я нашел это здесь .

Я довольно новичок в Android / Eclipse, по ошибке я добавил материал пользовательского интерфейса в activity_main.xml вместо fragment_main.xml . Мне потребовалось несколько часов, чтобы понять это …

В моем конкретном случае я пытался добавить нижний колонтитул в ListView. Следующий вызов onCreate () возвращал значение null.

Изменение этого, чтобы раздуть представление нижнего колонтитула вместо того, чтобы найти его по идентификатору, решило эту проблему.

FWIW, я не вижу, чтобы кто-то решил это так же, как мне было нужно. Никаких жалоб во время компиляции, но я получал нулевое представление во время выполнения и вызывал вещи в правильном порядке. То есть findViewById () после setContentView (). Проблема в том, что мое представление определено в content_main.xml, но в моем activity_main.xml мне не хватало этого одного утверждения:

Когда я добавил это к activity_main.xml, больше нет NullPointer.

В моем случае я использовал ExpandableListView, и я установил android:transcriptMode=»normal» . Это привело к тому, что несколько детей в расширяемой группе исчезли, и я использовал исключение NULL, когда я использовал прокрутку списка.

Для меня у меня было два xml-макета для одной и той же активности – один в портретном режиме и один в ландшафте. Конечно, я изменил идентификатор объекта в ландшафте xml, но забыл сделать то же изменение в портретной версии. Убедитесь, что если вы изменили одно, вы сделаете то же самое с другим xml или вы не получите сообщение об ошибке, пока не запустите / отлаживаете его, и он не сможет найти идентификатор, который вы не изменили. О, глупые ошибки, почему ты так меня наказываешь?

Задайте содержимое активности из ресурса макета. Т.е. setContentView(R.layout.basicXml) ;

У меня была такая же проблема. Я использовал стороннюю библиотеку, которая позволяет переопределить их адаптер для GridView и указать собственный макет для каждой ячейки GridView.

Наконец я понял, что происходит. Eclipse все еще использовал XML-файл раскладки библиотеки для каждой ячейки в GridView, хотя он не дал никаких указаний на это. В моем пользовательском адаптере он указал, что он использует ресурс xml из моего собственного проекта, хотя во время выполнения он не был.

Так что я сделал, чтобы убедиться, что мои собственные макеты xml и идентификаторы отличаются от тех, которые все еще сидят в библиотеке, очистили проект, а затем начали читать правильные пользовательские макеты, которые были в моем проекте.

Короче говоря, будьте осторожны, если вы переопределяете адаптер сторонней библиотеки и указываете свой собственный макет xml для использования адаптером. Если ваш макет внутри вашего проекта имеет то же имя файла, что и в библиотеке, вы можете столкнуться с действительно сложной ошибкой!

У меня такая же проблема, но я думаю, что ее стоит поделиться с вами, ребята. Если вам нужно findViewById в пользовательском макете, например:

Вы не можете получить представление в конструкторе. Вы должны вызвать findViewById после того, как просмотр завышен. Их метод, который вы можете переопределить onFinishInflate

В моем случае я раздул макет, но взгляды на ребенка возвращали нуль. Первоначально у меня было это:

Однако, когда я изменил его на следующее, он работал:

Ключ должен был специально ссылаться на уже завышенный макет, чтобы получить вид ребенка. То есть, чтобы добавить footerView :

  • FooterView .findViewById …

По моему опыту, похоже, что это также может произойти, когда ваш код вызывается после OnDestroyView (когда фрагмент находится в фоновом стеке.) Если вы обновляете пользовательский интерфейс на входе от BroadCastReceiver, вы должны проверить, действительно ли это так ,

В дополнение к вышеуказанным решениям вы убедитесь, что
tools:context=».TakeMultipleImages» в макете такое же значение в файле mainfest.xml:
android:name=».TakeMultipleImages» для одного и того же элемента активности. Это происходит при использовании копирования и вставки для создания новой активности

ОГРАНИЧИВАЙТЕ СРОК! (Который содержит идентификатор)

В моем случае findViewById () возвратил null, потому что макет, в котором был написан элемент, не был завышен …

FindViewById (R.id.listview) возвратил null, потому что я не делал inflater.inflate (R.layout.fragment_layout, …, …); перед этим.

Надеюсь, этот ответ поможет некоторым вам.

Мое решение состояло в том, чтобы просто очистить проект.

Просто хотел бросить здесь свой конкретный случай. Может помочь кому-то спуститься по линии.

Я использовал эту директиву в своем Android-интерфейсе Android следующим образом:

Детский вид (retry_button):

.findViewById (R.id.retry) всегда возвращает null. Но, если я переместил идентификатор из дочернего представления в тег include, он начал работать.

FindViewById также может возвращать значение null, если вы находитесь внутри фрагмента. Как описано здесь: findViewById in Fragment

Вы должны вызвать getView () для возврата верхнего уровня в фрагмент. Затем вы можете найти элементы макета (кнопки, текстовые изображения и т. Д.),

Источник

Оцените статью