i have a lite problem with my code, i was search in this site but still not found the best answer i will send data to my tab fragment, this my code
My Activity class
public class MainActivity extends AppCompatActivity
private ViewPager pager;
private Toolbar toolbar;
private TabLayout tabs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager=(ViewPager) findViewById(R.id.pager);
tabs=(TabLayout) findViewById(R.id.tabs);
pager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager()));
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
// set Fragmentclass Arguments
tab1Fragment fragobj = new tab1Fragment();
fragobj.setArguments(bundle);
}
}
and this my tab1 class
public class tab1Fragment extends Fragment
public tab1Fragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_tab1, container, false);
TextView tes=(TextView) view.findViewById(R.id.testtab1);
String strtext = getArguments().getString("edttext");
tes.setText("tes :"+ strtext);
return view;
}
}
and this my page fragment adapter
public class TabFragmentPagerAdapter extends FragmentPagerAdapter
String[] title = new String[]{
"Tab 1", "Tab 2", "Tab 3"
};
public TabFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position){
Fragment fragment=null;
switch (position){
case 0:
fragment=new tab1Fragment();
break;
case 1:
fragment=new tab2Fragment();
break;
case 2:
fragment=new tab3Fragment();
break;
default:
fragment=null;
break;
}
return fragment;
}
@Override
public CharSequence getPageTitle(int position){
return title[position];
}
@Override
public int getCount(){
return title.length;
}
}
when i run error
java.lang.NullPointerException
Please Help
In your AppCompatActivity
you have send
tab1Fragment fragobj = new tab1Fragment();
fragobj.setArguments(bundle);
but in your TabFragmentPagerAdapter
fragment=new tab1Fragment();
break;
it has null arguments
inside switch
switch (position){
case 0:
fragment=new tab1Fragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
fragment.setArguments(bundle);
break;