android ViewPager: unable to switch pages onClick - android

i wanted to know if someone can help me solve this issue. I have a button setup and when its clicked, its supposed to navigate to another viewpager page. But everytime its clicked, the app crashes returning the error at onClick at fragmenttab2 class. Here is my Main Activity.
public class MainActivity extends SherlockFragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
viewPager.setCurrentItem(1);
}
}
Here is the fragment containing the onClick:
public class FragmentTab1 extends SherlockFragment {
ViewPager viewPager;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity activity = getActivity();
if (activity != null) {
addListenerOnButton();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmenttab1, container, false);
return view;
}
public void addListenerOnButton() {
Button nextfrag = (Button) getView().findViewById(R.id.btn_nextfrag);
nextfrag.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ViewPager) viewPager.findViewById(R.id.pager)).setCurrentItem(1);
}
});
}
}
The log:
E/AndroidRuntime java.lang.NullPointerException
E/AndroidRuntime com.test.seriessample.FragmentTab1$1.onClick(FragmentTab1.java:58)

your viewPager is probably null. I also see that viewPager itself is a ViewPager and in the onClick you search for another ViewPager within that ViewPager which doesn't seem right.
EDIT:
you should add something like this in your activity
public ViewPager getPager() {
return viewPager;
}
And in the onClick of your Fragment
((MainActivity) getActivity()).getPager().setCurrentItem(1);

Related

findViewByID not work in tab layout

i use tab layout matching this tutorial:
tab layout tutorial androidhive
It works fine, but when I add a button to fragment_one.xml , i cant use setOnClickListener for this button Because findViewById not work in MainActivity.java
the MainActivity bellow code:
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
the app stopped with this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener' on a null object reference
Where should the button be defined and setOnClickListener?
Even though a fragment is hosted by an activity, it has its own layout (which is contained in the activity's layout) and therefore you'll have to define the fragment's view in its java class.
In most cases, a fragment would have its own Java class for you to manage and manipulate it, so in your case, it should look like this:
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#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_one, container, false);
Button button=view.findViewById(R.id.myButtonInFragment);
return view;
}
}
If you'd like to access this button from its parent activity, you can achieve it by making the button public:
public class OneFragment extends Fragment{
public Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_one, container, false);
button=view.findViewById(R.id.myButtonInFragment);
return view;
}
}
and then, access it using the fragment's instance in your activity:
OneFragment myFragment=new OneFragment();
After you have attached the fragment to the activity, you can use:
myFragment.button.setClickEnabled(false);
However, accessing fragment's children outside of the fragment is not recommended, and you should avoid it if you can.
public class MainActivity extends AppCompatActivity {
Button button;
Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new Fragment();
View view = fragment.getView();
if (view !=null) {
view.findViewById(R.id.button);
}
}
}

Save RecyclerView State inside Fragment in ViewPager created inside another Fragment

I have a ViewPager inside a Fragment
public class FragmentPager extends BaseFragment {
#Bind(R.id.viewpager)
ViewPager viewPager;
#Bind(R.id.detail_tabs)
TabLayout detailTabs;
private Activity mActivity;
private PagerAdapter mPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mPagerAdapter = new PagerAdapter(getChildFragmentManager());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager, container, false);
ButterKnife.bind(this, v);
viewPager.setAdapter(mPagerAdapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
viewPager.setPageMargin(pageMargin);
detailTabs.setupWithViewPager(viewPager);
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
#Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
I am already using FragmentStatePagerAdapter to manage my fragments in ViewPager. Each Fragment has a RecyclerView. On clicking each item of the RecyclerView I am replacing the FragmentPager with FragmentDetail. When I navigate back to the FragmentPager, the RecyclerView starts from the beginning instead of position scrolled.
I think you change your fragment with fragmentTransaction replace method. You need to do it with fragmentTransaction add method. See the below
Basic difference between add() and replace() method of Fragment

ImageButton on Fragment which goes to another Activity. Android Studio

I have been searching this but I haven't found anything that could help me.
I have a main activity with 2 fragments which I use as tabs in my toolbar. Is there any possibility of connecting an ImageButton from a fragment in my MainActivity to an other Activity. I know how to connect Activity to Activity through an imagebuttom, i just don't know how to do it from Fragment-> Activity. Thanks.
I have an image button on my fragment, and I want to open an activity when I press that ImageButton.
public class Movies extends Fragment {
public Movies() {
// Required empty public constructor
}
ImageButton imageButton2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_movies, container, false);
imageButton2 = (ImageButton) findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentLoadNewActivity = new Intent(Movies.this, Activity_Civil_War.class);
startActivity(intentLoadNewActivity);
}
});
}
}
I am getting lots of errors. I also tried doing it in the MainActivity but I get the null object exception.
MainActivity Class:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
view_pager_adapter viewPagerAdapter;
ImageButton imageButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById((R.id.toolBar));
tabLayout=(TabLayout)findViewById((R.id.tabLayout));
viewPager=(ViewPager)findViewById((R.id.ViewPager));
viewPagerAdapter = new view_pager_adapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new Showcase(),"Showcase");
viewPagerAdapter.addFragments(new Movies(),"Movie List");
viewPagerAdapter.addFragments(new Menu(),"Menu");
viewPagerAdapter.addFragments(new Login(),"Login");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
Few things first :
return inflater.inflate(R.layout.fragment_movies, container, false);
If your return a value here, the rest of the code below it will not be called. What you need to do is keep a reference to it and return it at the end of your method.
Then
Intent intentLoadNewActivity = new Intent(Movies.this, Activity_Civil_War.class);
I assume that Movies is a Fragment and Activity_Civil_War is an Activity (correct me if I'm wrong).
There is no constructor in the Intent class that takes a Fragment as a parameter. What you are trying to do by calling 'this' is to get a Context. In a Fragment you can do so by calling getActivity()
If we sum things up we get :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movies, container, false);
imageButton2 = (ImageButton) findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentLoadNewActivity = new Intent(getActivity(), Activity_Civil_War.class);
startActivity(intentLoadNewActivity);
}
});
return view;
}

Android: how to update recyclerview inside fragment which is inside viewpager upon button click

I have a recyclerview inside a fragment which is inside viewpager. I have button outside viewpager. How to update the recyclerview upon clicking the button.
public class Level2MainActivity_grid1 extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level2mainlayout_place1);
// I am putting a viewpager with fragments into them and put tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
Button buttonId = (Button) findViewById(R.id.planmytraveludupitown);
buttonId.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//I want to save some things and do the changes in the recyclerview of tab 0;
}
});
}
}
The framgment code in tab 0 of the viewpager, in which i am using recyclerview is as below:
public class Udupiwhattosee extends Fragment {
private RecyclerView rv;
private List<Udupiwhattoseearray> udupiwhattoseearray;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
RecyclerView v =(RecyclerView) inflater.inflate(R.layout.tab_1,container,false);
v.setLayoutManager(new LinearLayoutManager(getActivity()));
v.setHasFixedSize(true);
initializeData();
WhattoseeRVAdapter adapter = new WhattoseeRVAdapter(udupiwhattoseearray,container.getContext());
v.setAdapter(adapter);
return v;
}
private void initializeData(){
udupiwhattoseearray = new ArrayList<>();
udupiwhattoseearray.add(new Udupiwhattoseearray("Udupi Sri Krishna Temple", "Udupi, Karanata,INDIA", R.drawable.udupi));
udupiwhattoseearray.add(new Udupiwhattoseearray("Udupi place 2", "Udupi, Karanata,INDIA", R.drawable.udup_krishna_math_gopura_udupi));
udupiwhattoseearray.add(new Udupiwhattoseearray("Udupi Place 3", "Udupi, Karanata,INDIA", R.drawable.udupi_rath));
udupiwhattoseearray.add(new Udupiwhattoseearray("Udupi place 4", "Udupi, Karanata,INDIA", R.drawable.udupi_window));
}
recycler_view.post(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
HERE you will see the working of interface ,try this hope its gonna work fine

onClick inside fragment giving me NPE

I've been wrestling with this for quite a while now.
I switched from having a regular Activity to now using fragments (by users recommendations), but I've been getting the same issue.
I have 3 pages that are now 3 fragments inside of a ViewPager. I want the button with the id addSiteButton in the addSite fragment; when clicked, to scroll over to setCurrentItem(2).
Any help is appreciated! Here's my code.
The FragmentActivity
public class fieldsActivity extends FragmentActivity {
private static final int NUMBER_OF_PAGES = 3;
ViewPager mPager;
MyFragmentPagerAdapter mMyFragmentPagerAdapter;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
mPager = (ViewPager) findViewById(R.id.fieldspager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyFragmentPagerAdapter);
mPager.setCurrentItem(1);
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int page) {
switch (page) {
case 0: return new settingFields();
case 1: return new addSite();
case 2: return new createSite();
}
return null;
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
The class with the button
public class addSite extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (container == null) {
return null;
}
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.add_site, container, false);
final ViewPager mPager = (ViewPager) mRelativeLayout.findViewById(R.id.fieldspager);
Button addSiteButton = (Button) mRelativeLayout.findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
});
return mRelativeLayout;
}
}
I feel like I'm going in circles and not getting the desired motion.
Thanks for the help!
Simply make the Fragment as a class inside the FragmentActivity and take out the variable shadowing in onCreateView() since your pager is a global variable.
public class fieldsActivity extends FragmentActivity {
private static final int NUMBER_OF_PAGES = 3;
ViewPager mPager;
MyFragmentPagerAdapter mMyFragmentPagerAdapter;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
mPager = (ViewPager) findViewById(R.id.fieldspager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyFragmentPagerAdapter);
mPager.setCurrentItem(1);
}
public static class addSite extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.add_site, container, false);
//final ViewPager mPager = (ViewPager) mRelativeLayout.findViewById(R.id.fieldspager);
Button addSiteButton = (Button) mRelativeLayout.findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
});
return mRelativeLayout;
}
}
}
Also consider using the #Override annotation whenever you override a method so you don't make mistakes and use proper naming conventions. Java classes start with a capital.

Categories

Resources