NullPointerException accessing views in onCreate()
The tutorial is probably outdated, attempting to create an activity-based UI instead of the fragment-based UI preferred by wizard-generated code.
The view is in the fragment layout (fragment_main.xml
) and not in the activity layout (activity_main.xml
). onCreate()
is too early in the lifecycle to find it in the activity view hierarchy, and a null
is returned. Invoking a method on null
causes the NPE.
The preferred solution is to move the code to the fragment onCreateView()
, calling findViewById()
on the inflated fragment layout rootView
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
View something = rootView.findViewById(R.id.something); // not activity findViewById()
something.setOnClickListener(new View.OnClickListener() { ... });
return rootView;
}
As a side note, the fragment layout will eventually be a part of the activity view hierarchy and discoverable with activity findViewById()
but only after the fragment transaction has been run. Pending fragment transactions get executed in super.onStart()
after onCreate()
.
onCreate Null Pointer Exception
You likely are using a Fragment
. You should have in your code a class called PlaceHolderFragment
, that has an onCreateView
method.
In that project you have two xml layout, one named activity_matchpage
and other for the fragment, fragment_main
. You need to modify the latter and keep the first like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="youor.packaque.MainActivity"
tools:ignore="MergeRootFrame" />
And in fragment_main
, you declare your Views.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.tformacion.finale.MainActivity$PlaceholderFragment" >
<!-- Your Views here -->
</RelativeLayout>
Then, in your Java code, in PlaceHolderFragment
, inside of onCreateView
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
seekBar = (seekBar) rootView.findViewById(R.id.yourSeekBarId);
}
If you want to get rid of the fragment you simply create your XML in activity_matchpage
and do not add the fragment, so, remove this:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
Null Pointer Exception in an Activity's onCreate() method
You are trying to findViewById
before setting the content to the activity. ListView
should be initialized after content being set.
It should be like this:
super.onCreate(savedInstanceState);
setContentView(R.layout.rowlayout);
ListView lv = (ListView) findViewById(R.id.list);
NullPointerException in onCreate of Activity
Try this code may be help to you
Just change
loginTwitter.setOnClickListener(new OnClickListener() {
instead of
loginTwitter.setOnClickListener(new View.OnClickListener() {
Use this solution
Button loginTwitter = (Button) findViewById(R.id.twitterLoginButton);
Button noLogin = (Button) findViewById(R.id.noLoginButton);
loginTwitter.setOnClickListener(new OnClickListener() {
/**
* Login via Twitter
*/
@SuppressLint("NewApi")
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
startActivity(i);
}
});
noLogin.setOnClickListener(new OnClickListener() {
/**
* Proceed to use app without login
*/
@SuppressLint("NewApi")
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
NullPointerException when trying to access views in a Kotlin fragment
Kotlin synthetic properties are not magic and work in a very simple way. When you access btn_K
, it calls for getView().findViewById(R.id.btn_K)
.
The problem is that you are accessing it too soon. getView()
returns null
in onCreateView
. Try doing it in the onViewCreated
method:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
btn_K.setOnClickListener { Log.d(TAG, "onViewCreated(): hello world"); }
}
BaseActivity for NavigationDrawer gives NullPointerException when accessing views
First you try to call your custom setContentView
:
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
super.onCreateDrawer();
}
But that null checks frameLayout
:
@Override
public void setContentView(int layoutResID) {
if (frameLayout != null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
View stubView = inflater.inflate(layoutResID, frameLayout, false);
frameLayout.addView(stubView, lp);
}
}
Which is not actually initialized until later:
protected void onCreateDrawer() {
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
}
So, of course, you have not inflated a layout from which to get your DrawerLayout, hence your crash.
I would suggest you spend time learning how to debug your application.
Hope that helps!
UPDATE:
OK, I thought pointing you to your problem would help you solve the issue on your own. Here's my suggestion:
BaseActivity should set up the base layout that the derived class will inflate into (notice that we do not override setContentView
):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_activity);
onCreateDrawer();
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
// Here, ask the derived class for the layout resource to inflate into the content frame layout
View stubView = inflater.inflate(getContentLayoutResId(), frameLayout, false);
frameLayout.addView(stubView, lp);
}
abstract protect int getContentLayoutResId();
Then your MainActivity is just:
@Override
protected int getContentLayoutResId() {
return R.layout.activity_main;
}
NullPointerException onCreate() Android Studio
See here:
setContentView(R.layout.activity_main);
you are setting "activity_main" as Layout
. But in your Layout xml file there is no ListView with id listMe
.
So shift this code to activity_main
:
<ListView
android:id="@+id/listMe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="@array/Me"
/>
I hope it will work then.
NullPointerException in onCreate() when using findViewById - setContentView is used before?
Get your views and set the listeners in onPostCreate() method.
Related Topics
How to Discover Memory Usage of My Application in Android
How to Return a Boolean from Asynctask
Populating a Listview Using an Arraylist
Where to Store Application Data (Non-User Specific) on Linux
Sort Arraylist of Custom Objects by Property
What's Wrong With Java Date & Time API
Preparedstatement in Clause Alternatives
Java - Sending Http Parameters Via Post Method Easily
Why Can't I Use Switch Statement on a String
Calling Non-Static Method in Static Method in Java
View'S Getwidth() and Getheight() Returns 0
Custom Fonts and Xml Layouts (Android)
Execution Failed For Task :App:Compiledebugjavawithjavac in Android Studio
How to Execute Python Script from Java (Via Command Line)
Why Does My Arraylist Contain N Copies of the Last Item Added to the List
Java Multiple File Transfer Over Socket