ViewPager inside Fragment causes NullPointerException - android

I am trying to use ViewPager inside a Fragment and get
03-01 15:23:05.375 3937-3937/com.example.android.navigationdrawerexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.android.navigationdrawerexample.SpaFragment.onCreateView(SpaFragment.java:50)
at android.app.Fragment.performCreateView(Fragment.java:1695)
Code:
public class SpaFragment extends Fragment {
public SpaFragment(){}
private SpaList mSpa;
private TabHost tabs;
private FragmentActivity mFragmentActivity;
private View rootView;
public void setSpa(SpaList s)
{
mSpa=s;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_spa, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(mFragmentActivity.getSupportFragmentManager()));
return rootView;
}
#Override
public void onAttach(Activity activity) {
mFragmentActivity = (FragmentActivity) activity;
Log.d("ACTIVITY on attach"+mFragmentActivity,"\n");
super.onAttach(activity);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return "Title " + position;
}
#Override
public android.support.v4.app.Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
default: return FirstFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}

You are running into a NullPointerException because you are invoking a method on an object that is NULL at that time.
This could be because your
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// ...
}
method is called before your
#Override
public void onAttach(Activity activity) { }
method, and therefore, your variable mFragmentActivity is NULL. In that case, your code
String.valueOf(mFragmentActivity);
will throw a NullPointerException.

Related

push data from Fragment to Fragment

I am new to Android. Please excuse me if it's a silly question:
If i click on button of a Fragment - it has to trigger a test and show the result in other Fragment. So to make things simple, have written a code on button click as follows. It's not working. Please suggest.
My actual intent is to register a log.add BroadcastReceiver, so that anywhere any log error or debug is called, that message has to appear in the TestStatusFragment.
public class TriggerTestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_trigger, container, false);
Button stopScheduler = (Button) view.findViewById(R.id.testButton);
stopScheduler.setOnClickListener((View sview) -> {
View teststatusView = inflater.inflate(R.layout.fragment_teststatus, container, false);
TextView textView = (TextView) teststatusView.findViewById(R.id.text_view);
textView.setText("test result....");
});
return view;
}
}
MainActivity.java
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TriggerTestFragment(), "TRIGGERTEST");
adapter.addFragment(new TestStatusFragment(), "TEST STATUS");
viewPager.setAdapter(adapter);
}
Second Fragment:
public class TestStatusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_teststatus, container, false);
return view;
}
}
Use interface to communicate between them.
Fragment One
public class FragOne extends Fragment {
EditText etxtName, etxtDesc;
Button btnSubmit;
String name, desc;
private OnFragmentInteractionListener mListener;
public FragOne() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_one, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
etxtName = (EditText) view.findViewById(R.id.etxtName);
etxtDesc = (EditText) view.findViewById(R.id.etxtDesc);
btnSubmit = (Button) view.findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = etxtName.getText().toString().trim();
desc = etxtDesc.getText().toString().trim();
if(name == null || desc == null) {
Toast.makeText(getActivity(), "Both fields required", Toast.LENGTH_SHORT).show();
} else {
mListener.onFragmentInteraction(name, desc);
etxtName.setText("");
etxtDesc.setText("");
}
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String name, String desc);
}
}
Fragment Two
public class FragTwo extends Fragment implements FragOne.OnFragmentInteractionListener{
TextView textView, textDesc;
public FragTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_two, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = (TextView) view.findViewById(R.id.txtName);
textDesc = (TextView) view.findViewById(R.id.txtDesc);
}
#Override
public void onFragmentInteraction(String name, String desc) {
textView.setText(name);
textDesc.setText(desc);
}
}
Init fragments
fragOne = new FragOne();
fragTwo = new FragTwo();
PagerAdapter
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
MainActivity need implement onFragmentInteraction interface
public class MainActivity extends AppCompatActivity implements FragOne.OnFragmentInteractionListener{
static FragOne fragOne;
static FragTwo fragTwo;
MyPagerAdapter myPagerAdapter;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragOne = new FragOne();
fragTwo = new FragTwo();
viewPager = (ViewPager) findViewById(R.id.viewPager);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(myPagerAdapter);
}
#Override
public void onFragmentInteraction(String name, String desc) {
myPagerAdapter.onFragmentInteraction(name, desc );
}
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
}
You can read full article here https://www.mytrendin.com/passing-data-between-fragments/

How to add function in fragment

EDIT:
I'm new in android and i try to use fragments in my app. I try to use a fragment function in my activity but i got a null pointer exception..
Fragment:
public class VideoviewFragment extends Fragment {
private View card;
public static VideoviewFragment create() {
return new VideoviewFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_videoview, container, false);
card = (View) view.findViewById(R.id.card_video);
return view;
}
public void setalphacard(float value){
card.setAlpha(value);
}
}
In main activity i want to do that for example (i simplified my code):
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Viewpager
final SmartFragmentStatePagerAdapter adapterViewPager;
final ViewPager viewPager = (ViewPager) findViewById(R.id.am_view_pager);
adapterViewPager = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapterViewPager);
final VideoviewFragment videoviewFragment = (VideoviewFragment) adapterViewPager.getRegisteredFragment(2);
videoviewFragment.setalphacard(0.3f);
}
}
Main pager adapter:
public class MainPagerAdapter extends SmartFragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return CameraFragment.create();
case 1:
return OptionFragment.create();
case 2:
return VideoviewFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
You just have to declare the View globally like this:
public class VideoviewFragment extends Fragment {
private View card;
public static VideoviewFragment create() {
return new VideoviewFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_videoview, container, false);
card = (View) view.findViewById(R.id.card_video);
return view;
}
public void setalphacard(float value){
card.setAlpha(value);
}
}
Declare your View Object globally in your fragment.

Log Error in Nested Fragments on View Pager : No view found for id

I have a fragment that Contains view pager.there are three fragments in that Main fragment they are Fragment A,Fragment B,Fragment C. Upto this code runs properly.
Then i added a new Fragment and called via Fragment A then i got the error in the Log
No view found for id 0x7f0d0083 (com.app.sanyog:id/frame) for fragment SearchPlaces{289bf4e #0 id=0x7f0d0083}
Main Fragment:
/**
* Created by Admin on 04-06-2015.
*/
public class ContentFragment_Flight_Bkg extends Fragment {
private View view;
public ViewPager pager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_fragment_flight,container,false);
TabsPagerAdapter adapter = new TabsPagerAdapter(getFragmentManager());
pager = (ViewPager)view.findViewById(R.id.pager);
pager.setAdapter(adapter);
return view;
}
}
Pager Adapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "One Way", "Round Trip", "Multicity" };
Context context;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
OneWayTab fragmenttab1 = new OneWayTab();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
RoundTripTab fragmenttab2 = new RoundTripTab();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
MultiCityTab fragmenttab3 = new MultiCityTab();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
Fragment A
public class OneWayTab extends Fragment {
private LinearLayout oneway_source,oneway_destiantion;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab3.xml
View view = inflater.inflate(R.layout.content_one_way_tab, container, false);
oneway_source = (LinearLayout)view.findViewById(R.id.oneway_source_layout);
oneway_destiantion = (LinearLayout)view.findViewById(R.id.oneway_destination_layout);
oneway_source.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SearchPlaces fragment_Flight= new SearchPlaces();
android.support.v4.app.FragmentTransaction fragmentTransaction_Flight = getChildFragmentManager().beginTransaction();
fragmentTransaction_Flight.replace(R.id.frame,fragment_Flight,"FLight_booking");
fragmentTransaction_Flight.commit();
}
});
oneway_destiantion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Utils.showToast(getActivity(),"Destiantion");
}
});
return view;
}
}
New Fragment (Called from Fragment A)
public class SearchPlaces extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.content_search_places, container, false);
return view;
}
}

ViewPager getChildAt() returns null

I am using ViewPager in my activity and it only has two fragments, both implemented in similar structure as follow, so there should always be a fragment returned when getInstanced is called:
public class ListReminderFragment extends Fragment {
private View rootView;
private static ListReminderFragment listReminderFragment;
public static ListReminderFragment getInstance() {
if(listReminderFragment != null)
return listReminderFragment;
else {
listReminderFragment = new ListReminderFragment();
return listReminderFragment;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.content_main_screen, container, true);
return rootView;
}
#Nullable
#Override
public View getView() {
return rootView;
}
}
This is my adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ListReminderFragment.getInstance(); // temporary
}
#Override
public int getCount() {
return 2;
}
}
And I am initialising my ViewPager as below, in OnCreate() in the activity that has the ViewPager:
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.main_view_pager);
viewPager.setAdapter(viewPagerAdapter);
But when I call viewPager.getChildAt(), viewPagerAdapter.getItem(0).getView(), they both return null,
when I call viewPager.getChildCount(), it returns 0 instead of 2.
How should I access the views in side the fragment in ViewPager?

Access to getString() in a fragment that implements a viewpager

I am using a nested fragment using SherlockFragment, all works fine. But i am not being able to make viewpager title to string so that i can support multilanguage using string.xml.
Here is my code
public class schedule_pl extends SherlockFragment {
private static String titles[] = new String[] { "Portugal", "Lisbon" , "Azores" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_pager, container, false);
// Locate the ViewPager in viewpager_main.xml
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
// Set the ViewPagerAdapter into ViewPager
mViewPager.setAdapter(new MyAdapter (getChildFragmentManager()));
return view;
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class
.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position)
{
case 0:
return new place();
case 1:
return new place2();
case 2:
return new place3();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
public static class place extends Fragment {
public place() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container,
false);
return rootView;
}
}
public static class place3 extends Fragment {
public place3() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment2, container,
false);
return rootView;
}
}
public static class place2 extends Fragment {
public place2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment3, container,
false);
return rootView;
}
}
}
on getPageTitle i can't that working with strings and already tried several methods.
Access to getString() in android.support.v4.app.FragmentPagerAdapter?
This is a question similar on the site but neither answer got me on the right path.
I tried using this:
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getcontext.getString(R.string.title_section_schedule1).toUpperCase(l);
case 1:
return getcontext.getString(R.string.title_section_schedule2).toUpperCase(l);
case 2:
return getcontext.getString(R.string.title_section_schedule3).toUpperCase(l);
}
return null;
}
But do not work. Anyone knows the solution to this?
You can pass the Activity to your adapter constructor.
mViewPager.setAdapter(new MyAdapter (getChildFragmentManager(), getActivity()));
then in MyAdapter:
//declare a private variable for the activity
private Activity myActivity;
public MyAdapter(FragmentManager fm, Activity myActivity) {
super(fm);
this.myActivity = myActivity;
}
then in your getPageTitle
...
return myActivity.getString(R.String.title_section_scheduale1).toUpperCase(l);
...
Try it out hope it works for you.

Categories

Resources