findViewById() returns null when I call it in onCreate()
Activity
findViewById()
searches the activity's view hierarchy set with setContentView()
for the given view id. The view you appear to be looking for is in a fragment and not in the activity hierarchy (yet). Fragment transactions are not immediate either so even if you add it to the container in the activity hierarchy, it is not attached there right away but only when the transaction is processed.
In theory it's possible to synchronously execute pending fragment transactions with executePendingTransactions()
. However, it's better to just move the code that touches a fragment's views in its onCreateView()
. Fragments and their hosting activities are supposed to be relatively independent of each other, so an activity accessing a fragment's internals should be avoided.
findViewByID returns null
which returns null
Possibly because you are calling it too early. Wait until onFinishInflate()
. Here is a sample project demonstrating a custom View
accessing its contents.
findViewById returns null if used outside OnCreateView
You could save the view that you are inflating from the block
onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
//Previous code
view = inflater.inflate(R.layout.article_view, container, false);
}
then you can call it anywhere else in your code to get the view like this:
view.findViewById(R.id.view_searched);
instead of :
getActivity().findViewById(R.id.view_searched);
Why does findViewById() returns null?
Your tab_connect
etc. are include
d in fragment_main
layout and not in activity_main
layout that is inflated when you call findViewById()
for those ids. The code you posted does not show where you're using fragment_main
but what is certain is that it is not in your activity's view hierarchy at the time when you try to look up those views.
Either move the findViewById()
calls and whatever you're doing with the views to the fragment, or move the views from the fragment to your main activity.
How do I use findViewById() in onCreate without it returning null?
To avoid the crash due to the NPE you can test the returned value to be different by null before passing it:
MenuItem menuItem = (MenuItem) findViewById(R.id.nav_timetable);
if (menuItem != null) {
goToNavFragment(menuItem);
}
Anyway, that will not solve your problem, in fact findViewById(int)
is returning null
because the view ID you're searching for doesn't exist in your Activity layout.
The method findViewById()
, which comes from the View
class and you're invoking it on this
which is an Activity
(a Class that extends View), searches for a view id (from R
) inside the currently inflated layout.
Now, if you take a look to your onCreate
implementation you see that you're calling the setContentViewMethod(R.layout.activity_main)
; this means that you're setting the layout of this activity taking it from the xml layout with id activity_main
.
The big problem here is that the layout you're passing (activity_main
) does not contain the id you're looking for. Just take a look at the activity_main.xml
layout file, as you can see there's no object with id R.id.nav_timetable
.
An Activity can only have one layout activity file loaded at once. You can still load other layout files for menus or particular view objects (Spinner
s, List
s, etc).
The most important thing here is that you're trying to retrieve a MenuItem
; to achieve this you have to override two methods onCreateOptionsMenu()
and onOptionsItemSelected()
.
The
onCreateOptionsMenu()
does what its name says. It creates the options menu you're going to use. Here you can hook your actions but the most important thing you MUST do is to inflate a menu layout. Without this you'll not be able to apply a custom menu layout and to use findViewById
.Hence, before invoking the findViewById() you should do like:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_menu_id, menu);
// findViewById()
return true;
}
The onOptionsItemSelected()
will be called when an item from your previously created menu is selected, it will give you as an argument the selected MenuItem
and here you can implement the menu item click actions. A standard implementation can be the following:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_one:
doSomething()
return true;
case R.id.action_two:
doSomethingElse();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Android: Findviewbyid() returns null
Your application is working on phones but not on tablets, this usually means a problem of resources.
The resources (layout
, values
, ...) used by Android depends on the device used. If there is a specific folder that match the device configuration (like large screen), the resource redefine in this folder will be used instead of the general folder.
There is multiple difference between phone/tablet (screen size, ratio, orientation, ...).
In your case, you might need to update or remove the layout main_activity.xml
in a layout folder
that match your tablet.
findViewById returns null after calling setContentView
Your super.onCreate(savedInstanceState);
position is causing problem.
Replace your Help.java with this
public class Help extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
tv = (TextView) findViewById(R.id.tvBoxHelp);
tv.setText("text");
}
}
findViewById() returns null from a custom view
First you must create a custom_layout.xml
and put your TextView
and any widget you want to use like this :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
then initialize your custom_layout
in init()
methode of class GameMap :
public class GameMap extends LinearLayout {
.
.
.
private void init(Context context) {
View rootView = inflate(context, R.layout.sampel, this);
tv = rootView.findViewById(R.id.txt);
tv.setText("hello");
}
then add your custom_layout
in your MainActivity layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.crosstheboxprova.GameMap
android:id="@+id/gameMapView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</android.support.constraint.ConstraintLayout>
and in your MainActivity class :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
GameMap gameMap = (GameMap) findViewById(R.id.gameMapView);
// And continue the code ...
}
}
Related Topics
Adb Server Version (36) Doesn't Match This Client (39); Killing
How to Change the Size of a Switch Widget
Starting the Android Emulator in Sdk Tools, Revision 12
How to Get the Android Path String to a File on Assets Folder
Where to Find Info on Android's "Service Call" Shell Command
Start Activity Inside Onreceive Broadcastreceiver
Get List of Installed Android Applications
Textview with Different Textsize
Android:Configchanges="Orientation" Does Not Work with Fragments
How to Change the Fontsize in an Android Webview
Intent to Launch the Clock Application on Android
Java.Lang.Nullpointerexception (No Error Message)
Change Actionbar Color Programmatically More Than Once
Android Launching Music Player Using Intent
Navigation Drawer Semi-Transparent Over Status Bar Not Working