Why is ViewPager doesn't running class? - android

I have an activity that has a ViewPager, as following:
public class timetables extends FragmentActivity {
private ViewPager viewPager;
private RelativeLayout page1;
private RelativeLayout page2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timetables);
Intent intentTimetables = getIntent();
setTitle(Global.lineName);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MainPageAdapter());
}
class MainPageAdapter extends PagerAdapter {
#Override
public int getCount() {
return 2;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
View page;
switch (position) {
case 0:
if (page1 == null) {
page1 = (RelativeLayout) LayoutInflater.from(timetables.this).inflate(R.layout.activity_timetable_1, collection, false);
}
page = page1;
break;
((ViewPager) collection).addView(page, 0);
return page;
}
}
And when I run it, it loads good activity_timetable_1, but it doesn't run the code I have in that class, for example:
public class timetable_1 extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timetable_1);
GridView gridWorking = (GridView) findViewById(R.id.gridWorking);
gridWorking.setAdapter(new textAdapter(this));
}
}
Could anyone tell me what I am doing wrong? Thank you so much

if (page1 == null) {
page1 = (RelativeLayout) LayoutInflater.from(ctx).inflate(R.layout.activity_timetable_1, collection, false);
}
Do you expect when this inflates the custom view you have will be called?
Replace it with:
if (page1 == null) {
page1 = new Activity1Form(this);
}
Activity1Form = timetable_1
Also, extends ViewGroup instead of FragmentActivity at timetable_1, with this you should modify the class, remove the onCreate and place the code inside it on the constructor.
public class Activity1Form extends ViewGroup {
public Activity1Form(Context ctx) {
LayoutInflater.from(timetables.this).inflate(R.layout.activity_timetable_1, collection, true);
GridView gridWorking = (GridView) findViewById(R.id.gridWorking);
gridWorking.setAdapter(new textAdapter(this));
}
}
You should instantiate your class instead of the layout.
EDIT:
Also, your activity_1 (awful name by the way), is a Activity and cant be placed inside another Activity or used as a Fragment, you must extende Fragment or View (or any View child such RelativeLayout/ViewGroup)

Related

Moving Data from Activity to Another Activity's TabFragment's Fragment

I want to move some data from my Mainactivity to a Fragment...which is inside a tab fragment (which handles a SectionPagerAdapter)....which is inside a fragment in Mainactivity2.
I feel its too complicated and cant get it done.
GameEndedActivity (See wrong and correct variable...these are to be transferred)
public class GameEndedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_ended);
int correct = getIntent().getIntExtra("correct", 0);
int wrong = getIntent().getIntExtra("wrong", 0);
}
}
TabFragment
public class TabFragment extends Fragment {
private int tabsCount;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tab, container, false);
if(this.getContext() instanceof ChallengeOverviewActivity){
tabsCount = 2;
} else {
tabsCount = 3;
}
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this.getContext(), getFragmentManager(), tabsCount);
ViewPager viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
return view;
}
}
ResultFragment (Transfer data here - wrong and correct variables)
public class ResultDetailsFragment extends Fragment {
private TextView tvWrong, tvCorrect;
private AnswerListener answerListener;
public interface AnswerListener {
public void correct(int i);
public void wrong(int i);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_result_details, container, false);
tvCorrect = view.findViewById(R.id.tvCorrect);
tvWrong = view.findViewById(R.id.tvWrong);
return view;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
if (context != null) {
answerListener = (AnswerListener) context;
}
}
}
One way to do this is the add arguments to the fragment when you create an instance of it. In your activity when you create the fragment you want to attach you add some arguments to it. These arguments can then be accessed from the fragments onCreate method.
Just do this same thing again when you are in your fragment and create your second one.
Check this answer out which explains more in detail how to do it: https://stackoverflow.com/a/17436739/964887

Using ViewPager with ListFragment and CursorAdapter

I have an existing app displaying five different lists of entries from a database. It uses a left drawer to choose which list is displayed.
I would like to use ViewPager to these lists, but have a really hard time figuring out how this works. Unfortunately, I cannot find a tutorial that addresses this.
I have a MainActivity to which I connect a viewpagerAdapter
MainActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// Setting the viewpager
mPager = (ViewPager) findViewById(R.id.pager_container_home);
mPagerAdapter = new EntriesListPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
...
}
private class EntriesListPagerAdapter extends FragmentPagerAdapter {
...
#Override
public Object instantiateItem(ViewGroup container, int position) {
// What to put here???
return view;
}
}
I have a ListFragment class getting its data from a ResourceCursorAdapter (called EntriesCursorAdapter). It is a long class, so I give some parts to give you an idea.
public class EntriesListFragment extends ListFragment {
...
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
...
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mEntriesCursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mEntriesCursorAdapter.swapCursor(Constants.EMPTY_CURSOR);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mUri = savedInstanceState.getParcelable(STATE_URI);
mShowFeedInfo = savedInstanceState.getBoolean(STATE_SHOW_FEED_INFO);
mListDisplayDate = savedInstanceState.getLong(STATE_LIST_DISPLAY_DATE);
mEntriesCursorAdapter = new EntriesCursorAdapter(getActivity(), mUri, Constants.EMPTY_CURSOR, mShowFeedInfo);
}
}
#Override
public View inflateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_entry_list, container, true);
if (mEntriesCursorAdapter != null) {
setListAdapter(mEntriesCursorAdapter);
}
mListView = (ListView) rootView.findViewById(android.R.id.list);
...
}
public void setData(Uri uri, boolean showFeedInfo) {
mUri = uri;
mShowFeedInfo = showFeedInfo;
mEntriesCursorAdapter = new EntriesCursorAdapter(getActivity(), mUri, Constants.EMPTY_CURSOR, mShowFeedInfo);
}
Can you help me how to create five instances of the listfragment (with cursoradapter) and connect it to the ViewPager in the MainActivity? Any hint how to proceed is welcome.
Update: I noticed that the FragmentPagerAdapter is from the support.v4 library. If I am to use this, It looks like I have to use the ListFragment from support.v4 as well, including the LoaderManager. Unfortunately, the LoaderManager is not easily upgraded to support.v4. Any thoughts are welcome.
I got it solved. I will give the main pointers.
First, read this tutorial, because the given structure works. http://www.truiton.com/2013/05/android-fragmentpageradapter-example/
Second, check that all your imports are from the support.v4 library. This means the FragmentActivity (AppCompatActivity in the case above), ListFragment, Loader, LoaderManager and CursorLoader. I spent quite some time trying to figure out what was wrong with the code, while all the time I still had the Loader and CursorLoader from the wrong library.
Third, the MainActivity is where the FragmentPagerAdapter is placed, like:
MainActivity extends AppCompatActivity {
static final int ITEMS = 5; // number of lists
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// Setting the viewpager
mPager = (ViewPager) findViewById(R.id.pager_container_home);
mPagerAdapter = new EntriesListPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
...
}
public class EntriesListPagerAdapter extends FragmentPagerAdapter {
public EntriesListPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
return EntriesListFragment.init(position);
}
}
}
Fourth, the ListFragment has to change. It has to be able to be used several times in order to support the number of different lists in the ViewPager. I will give the importants methods/elements.
public class EntriesListFragment extends ListFragment {
// Loader to get the data from database for the list. Called from startLoaders();
private final LoaderManager.LoaderCallbacks<Cursor> mEntriesLoader = new LoaderManager.LoaderCallbacks<Cursor>() {...}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Getting the page number when created
pageViewerFragmentNum = getArguments() != null ? getArguments().getInt("val") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_entry_list, container, false); // orig was 'true'
mListView = (ListView) rootView.findViewById(android.R.id.list);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.e(TAG, "onActivityCreated");
super.onActivityCreated(savedInstanceState);
// Setting the adapter for each of the Feeds
// The used feedId is the pageViewerFragmentNum + 1
String FeedId = String.valueOf(pageViewerFragmentNum+1);
mUri = EntryColumns.ENTRIES_FOR_FEED_CONTENT_URI(FeedId);
// setting the adapter for the list
mEntriesCursorAdapter = new EntriesCursorAdapter(getActivity(), mUri,
Constants.EMPTY_CURSOR);
setListAdapter(mEntriesCursorAdapter);
startLoaders();
}
// Initialise the new listFragment for each Page. Notice the static!
public static EntriesListFragment init(int positie) {
EntriesListFragment viewPagerFragmentList = new EntriesListFragment();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putInt("val", positie);
viewPagerFragmentList.setArguments(args);
return viewPagerFragmentList;
}
private void startLoaders() {
LoaderManager loaderManager = getLoaderManager();
loaderManager.restartLoader(ENTRIES_LOADER_ID, null, mEntriesLoader);
}
}
Notice that the code given above is not complete. The tutorial mentioned earlier is, but I just tried to show you the main ingredients to get you started if you get stuck on this like I did.

Change Fragment with ViewPager

I am using PagerSlidingTab Library for ViewPager. And I want to change Fragment while scrolling of tabs. It is working fine. Check out my code.
I am using AsynTask() on each Fragment.
When the App opens with the MainActivity, First Fragment is attached to the activity, But It shows two AsynTask() dialog message, one from First and another from Second Fragment. And When I scroll to second tab, It shows dialog message of Third Fragment.
So, If I scroll from left to right in tabs, the Fragment right to the current fragment is displayed and if i scroll from right to left, the Fragment left to the current Fragment is displayed.
Please help me to solve the problem.
My Code:
public class PageSlidingTabStripFragment extends Fragment {
public static final String TAG = PageSlidingTabStripFragment.class
.getSimpleName();
public static PageSlidingTabStripFragment newInstance() {
return new PageSlidingTabStripFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.pager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view
.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
private final String[] TITLES = { "Instant Opportunity", "Events",
"Experts" };
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new InstantOpportunity();
case 1:
return new Events();
case 2:
return new Experts();
default:
break;
}
return null;
}
}
}
Explanation:
It turns out there is an easier implementation for scrollable tabs which doesn't involve another library. You can easily implement tabs into your app using normal Android code straight from the default SDK.
The Code
Main Class:
public class PageSlidingTabStripFragment extends Fragment {
//Variables
private ViewPager viewPager;
private PagerTitleStrip pagerTitleStrip;
public PageSlidingTabStripFragment() {
// Required empty public constructor
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Find your pager declared in XML
viewPager = (ViewPager) getView().findViewById(R.id.pager);
//Set the viewPager to a new adapter (see below)
viewPager.setAdapter(new MyAdapter(getFragmentManager()));
//If your doing scrollable tabs as opposed to fix tabs,
//you need to find a pagerTitleStrip that is declared in XML
//just like the pager
pagerTitleStrip = (PagerTitleStrip)
getView().findViewById(R.id.pager_title_strip);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.[your layout name here], container, false);
}
}
Adapter:
//Note: this can go below all of the previous code. Just make sure it's
//below the last curly bracket in your file!
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if (arg0 == 0) {
fragment = new InstantOpportunity();
}
if (arg0 == 1) {
fragment = new Events();
}
if (arg0 == 2) {
fragment = new Experts();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Instant Opportunity";
}
if (position == 1) {
return "Events";
}
if (position == 2) {
return "Experts";
}
return null;
}
}
Conclusion:
I hope this helps you understand another way to make scrollable tabs! I have examples on my Github Page about how to make each type (That being Fixed or Scrollable).
Links:
Fixed Tabs Example - Click Here
Scrollable Tabs Example - Click Here
Hope this helps!
Edit:
When asked what to import, make sure you select the V4 support fragments.
please use this example..its very easy.i already implement that.
reference link
hope its useful to you.its best example of pager-sliding-tabstrip.
Use
framelayout compulsory:
FrameLayout fl = new FrameLayout(getActivity());
fl.addView(urFragementView);
and then set your fragement view in this framelayout.

Access TextView in ViewPager from Activity

I have an Activity with a ViewPager containing multiple fragments. how can i now access a TextView in one of that fragments to change its text from the main activity? I tried multiple ways and they all ended in a NullPointerException.
Activity:
public class SummonerOverview extends SherlockFragmentActivity implements TabListener, OnPageChangeListener {
private ViewPager mPager;
private PagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summoner_overview);
initialize();
}
private void initialize() {
// initialize Pager
mPager = (ViewPager) findViewById(R.id.viewpager);
mAdapter = new PagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
mPager.setOnPageChangeListener(this);
}
}
PagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
frags = new Fragment[3];
frags[0] = new StatisticsFragment(0);
frags[1] = new RatingsFragment(1);
frags[2] = new HistoryFragment(2);
}
private final int NUM_PAGES = 3;
Fragment[] frags;
#Override
public Fragment getItem(int arg0) {
if (arg0 == 0)
return frags[0];
else if (arg0 == 1)
return frags[1];
else
return frags[2];
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
The Fragment:
public class StatisticsFragment extends SherlockFragment {
public StatisticsFragment(int fragNr) {
this.fragNr = fragNr;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_statistics, container, false);
return v;
}
}
The Textview in the StatisticsFragment is labeled with an id in the fragment_overview_statistics.xml, but when i try
TextView tv = (TextView) findViewById(R.id.id_of_the_textview)
tv.setText("text");
from within the onCreate() Method of the Activity after the initialize() Method, i get an Exception.
Okay, after another hour of googling, i think i solves my own question (although i'm sure there is a better method to solve that)
I now hold all the Data that is displayed by the fragments in the MainActivity and make the Fragmets consume this Data in their onCreateView() Method by using public Methods of the Activity.
In the PagerAdapter, i overwrote getItemPosition() to:
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Now, everytime i update some of the Data, i also call mAdapter.notifyDataSetChanged() which leads into a recreation of all fragments.
It works, although it looks like a poor hack for me. Im sure there must be a better solution because now i have to recreate all fragments for changing one TextView of one Fragment, what is surely not the way it is intended to be done.

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