ViewPager and NullObjectReference error [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've got an issue with setting an adapter to the ViewPager. Each time i get a NullObjectReference error. What's wrong with my code?
1) Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="4dp"
android:paddingTop="4dp" />
</android.support.v4.view.ViewPager>
</LinearLayout>
2) Java class:
public class FoodFragment extends Fragment {
Toolbar toolbar;
ViewPager viewPager;
TabsPagerAdapter pagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
((AppCompatActivity)getActivity())
.getSupportActionBar().setDisplayShowTitleEnabled(true);
((AppCompatActivity)getActivity())
.getSupportActionBar().setTitle(R.string.food);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setBackgroundColor(Color.parseColor("#f6a632"));
pagerAdapter = new TabsPagerAdapter(getActivity()
.getSupportFragmentManager());
viewPager = (ViewPager) getActivity().findViewById(R.id.view_pager);
viewPager.setAdapter(pagerAdapter);
return inflater.inflate(R.layout.fragment_food, container, false);
}
}
I always get this error when calling viewPager.setAdapter(pagerAdapter); line.

The reason is that your onCreateView. In fragment, you need to first inflate the view for fragment first, and then findViewById from this view.
You may see an example below:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_food, container, false);
// get your view by: rootView.findViewById()
// for example:
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
// do others...
return rootView;
}

Related

Calling ViewPager inside a Fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
findViewByID returns null
(33 answers)
Closed 2 years ago.
I am designing an Onboarding screen with the help of ViewPager. The ViewPager sits inside a fragment underlying my MainActivity class. The error arises when I pass the ViewPager adapter class to the ViewPager inside my fragment! It throws NullPointerException and after breakpoint debugging I find that the inflater inside my PagerAdapter class is null.
I have tried some alternatives to get the inflater working but no luck! I ll post my codes below:
ViewPager Fragment class:
public class ViewPagerFragment extends Fragment {
ViewPager viewpager;
LinearLayout dotsLayout;
SliderAdapter sliderAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
viewpager = (ViewPager) view.findViewById(R.id.viewPagerFragment);
dotsLayout = (LinearLayout) view.findViewById(R.id.dotsLayout);
sliderAdapter = new SliderAdapter(view.getContext());
viewpager.setAdapter(sliderAdapter); //The error is thrown here
// Inflate the layout for this fragment
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Toast.makeText(view.getContext(),"Here",Toast.LENGTH_LONG).show();
}}
ViewPager Adapter Class:
public class SliderAdapter extends PagerAdapter {
Context context1;
LayoutInflater inflater;
public int[] slide_images = {
R.drawable.band,
R.drawable.studio,
R.drawable.videoshoot
};
public String[] slide_headings = {
"REHEARSAL PAD", "RECORDING STUDIO", "SESSION VIDEOSHOOT"
};
public String[] slide_desc ={
String.valueOf(R.string.rehearsal_desc),
String.valueOf(R.string.studio_desc),
String.valueOf(R.string.videoshoot_desc)
};
public SliderAdapter(Context context){
context1 = context;
}
#Override
public int getCount() {
return slide_headings.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view== (ConstraintLayout)object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
//ViewPager Sliding Images and Desc
inflater = (LayoutInflater)context1.getSystemService(context1.LAYOUT_INFLATER_SERVICE);
//inflater = LayoutInflater.from(context1);
View view = inflater.inflate(R.layout.slider_layout,container,false);
ImageView slideImageView = (ImageView) view.findViewById(R.id.SliderImageView);
TextView slideHeading = (TextView) view.findViewById(R.id.SliderTextView1);
TextView slideDesc = (TextView) view.findViewById(R.id.SliderTextView2);
slideImageView.setImageResource(slide_images[position]);
slideHeading.setText(slide_headings[position]);
slideDesc.setText(slide_desc[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout)object);
}}
And the Exception Logs are given below:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.soundflixstudios, PID: 13363
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
at com.example.soundflixstudios.onboarding.ViewPagerFragment.onCreateView(ViewPagerFragment.java:43)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7099)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
Any help is appreciated, and yes I have gone through multiple post in stackoverflow but didnt find any solutionhence reaching out with a new question!
Thanks in advance!
Edit: I have added the xml for "view_pager_fragment" layout
enter code here<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#color/white"
android:orientation="vertical"
tools:context=".onboarding.ViewPagerFragment">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/sliderViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="1">
</androidx.viewpager2.widget.ViewPager2>
<LinearLayout
android:id="#+id/dotsLayout"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:layout_gravity="center"
android:layout_weight="1"
android:orientation="horizontal">
</LinearLayout>
Root cause
In view_pager_fragment.xml file, you declare a ViewPager2 with id sliderViewPager but in ViewPagerFragment class, you use a ViewPager variable and assign a view with id viewPagerFragment to it.
Solution
Step 1. Change fragment_view_pager.xml to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="#+id/sliderViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="1">
</androidx.viewpager.widget.ViewPager>
<LinearLayout
android:id="#+id/dotsLayout"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:layout_gravity="center"
android:layout_weight="1"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Step 2. In ViewPagerFragment class, change your code from
viewpager = (ViewPager) view.findViewById(R.id.viewPagerFragment);
to
viewpager = (ViewPager) view.findViewById(R.id.sliderViewPager);
Can you add your xml file ( viewPagerFragment). In normal case, nullPointerException will show up when you missing references to your xml, or missing create xml tag( different screen- landscape/portrait)

Unable to Position Bottom Sheet Dialog at the bottom of the screen

I have a Video Detail Fragment which I want to behave as a bottom sheet behaviour, but unfortunately, the dialog is getting displayed at the centre of the screen. I am unable to figure out the exact problem in the code. Below I am attaching the code and the layout file, in regard to the same.
This is my Video Detail fragment:
public class VideoDetailsFragment extends BottomSheetDialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AppCompatDialog dialog = new AppCompatDialog(getActivity());
dialog.setTitle(titleId);
return dialog;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View dialogView = inflater.inflate(R.layout.video_detail_fragment, container, false);
Button cancelButton = dialogView.findViewById(R.id.track_selection_dialog_cancel_button);
Button okButton = dialogView.findViewById(R.id.track_selection_dialog_ok_button);
return dialogView;
}
public static final class TrackSelectionViewFragment extends BottomSheetDialogFragment
implements TrackSelectionView.TrackSelectionListener {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.exo_track_selection_dialog, container, /* attachToRoot= */ false);
TrackSelectionView trackSelectionView = rootView.findViewById(R.id.exo_track_selection_view);
trackSelectionView.setShowDisableOption(true);
trackSelectionView.setAllowMultipleOverrides(allowMultipleOverrides);
trackSelectionView.setAllowAdaptiveSelections(allowAdaptiveSelections);
trackSelectionView.init(mappedTrackInfo, rendererIndex, isDisabled, overrides, /* listener= */ this);
return rootView;
}
}
}
The xml file for video_detail_fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="270dp"
android:visibility="visible"
app:behavior_hideable="true"
app:behavior_peekHeight="0dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
>
<FrameLayout
android:id="#+id/child_fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end">
</LinearLayout>
</LinearLayout>
I went through many posts but almost all the posts were showing the solution as setting the app attribute app:layout_behavior="android.support.design.widget.BottomSheetBehavior". But it's not working in my case. Kindly help me understand as to where I am doing wrong?

I need to inflate a RecyclerView inside a Fragment AndroidStudio

I would like to use a Tab/Fragment to show RecyclerView, but I don't know how to do it because the method of the Fragment class return a View, not a Reclycler View:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment_needs, container, false);
return myFragmentView;
}
The code of the fragment.xml is:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".NeedsFragment">
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/all_user_need_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</FrameLayout>
</RelativeLayout>
Thank u.
First off, your onCreateView() method makes no sense:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment_needs, container, false);
return needsFragmentRecyclerView; //you should be returning myFragmentView here, not whatever needsFragmentRecyclerView is
}
Second, once you inflate your layout, just use findViewById():
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment_needs, container, false);
RecyclerView recyclerView = myFragmentView.findViewById(R.id.all_user_need_list); //assign to a global variable if needed
return myFragmentView; //replaced with the proper variable
}
Alternatively, you can get the RecyclerView from anywhere in your Fragment, as long as it's called after onCreateView() with the following:
RecyclerView recyclerView = getView().findViewById(R.id.all_user_need_list);
You can return any type of view component and Custom view that is inherit from android.view class in onCreateView() method.

Android fragment - findViewById returns null [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have a problem that seems to be quite common on the internet : I have created an activity with just a fragment. This is the generated code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
ListView lv = (ListView) findViewById(android.R.id.list);
}
}
After or inside the condition, I can't get any object with findViewById: it is always null. Here is the rest of the generated code :
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_customer,
container, false);
return rootView;
}
activity_customer.xml:
<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="com.axacs.marc.CustomerActivity"
tools:ignore="MergeRootFrame" />
the listview is actually in fragment_customer.xml:
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/new_folder_button"
android:text="" />
Does anyone know what is missing ?
use following after moving this line to onCreateView() if you want to use your listview in your fragment
ListView lv = (ListView)rootview.findViewById(android.R.id.list);

Fragment is not showing up

I m trying to make a simple fragment example where one fragment will show an Article List and the other will show detailed article.
This is my main activity class-
public class ArticleFragment extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}// end class
This is the main layout file-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.ArticleList"
android:id="#+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.ArticleDetails"
android:id="#+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
This is my two fragment class for ArticleList and ArticleDetails
public class ArticleList extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.articlelist, container, false);
}
public class ArticleDetails extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.articledetails, container, false);
}
}
I have also TWO XML layout files(containing a textview) for both articleList, ArticleDetails fragment. But the app has stopped working. What have I missed here? Pls help thanx.
Check your Package name inside the code
<fragment android:name="com.abc.def............./>
.Thanks to you I know that we can do it.

Categories

Resources