BadCodersHub BadCodersHub - 3 months ago 16
Android Question

NullPointer trying to find resource

I am taking a look at this Search field

I am trying to create the searchbar, but I get an eror everytime shown below:


java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.arlib.floatingsearchview.FloatingSearchView.findViewById(int)' on a null object reference


Here is my XML file search.xml:

<RelativeLayout 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/parent_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<View
android:id="@+id/header_view"
android:layout_width="match_parent"
android:layout_height="@dimen/sliding_search_view_header_height"
android:background="#01579B"/>

<FrameLayout
android:id="@+id/dim_background"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.arlib.floatingsearchview.FloatingSearchView
android:id="@+id/floating_search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:translationY="@dimen/sliding_search_view_header_height"
app:floatingSearch_close_search_on_keyboard_dismiss="false"
app:floatingSearch_dimBackground="false"
app:floatingSearch_dismissOnOutsideTouch="true"
app:floatingSearch_leftActionMode="showHamburger"
app:floatingSearch_menu="@menu/menu_search_view"
app:floatingSearch_searchBarMarginLeft="@dimen/search_view_inset"
app:floatingSearch_searchBarMarginRight="@dimen/search_view_inset"
app:floatingSearch_searchBarMarginTop="@dimen/search_view_inset"
app:floatingSearch_searchHint="Search..."
app:floatingSearch_showSearchKey="true"
app:floatingSearch_suggestionsListAnimDuration="250"/>
</FrameLayout>




and here is what I did in the activity class:

public class CreateSearch extends AppCompatActivity{

FloatingSearchView mSearchView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search.xml);

mSearchView.findViewById(R.id.floating_search_view);
...


I get the error here

mSearchView.findViewById(R.id.floating_search_view);


any idea why? any help is much appreciated.

Answer

mSearchView is not initialised yet so has the default value null. Also, findViewById(int res) is a method belong to Activity class not FloatingSearchView class. Try changing to

mSearchView = (FloatingSearchView) findViewById(R.id.floating_search_view);