Using FirebaseUI for firebase recyclerView in android - firebase

i am a new comer in android development and facing some problems using firebase ui.
i wanted to retrieve data from my firebase database and show it on my recyclerView.
but i am constantly getting an error while making FirebaseRecyclerAdapter.
Here is My Code Sample:
public class UsersActivity extends AppCompatActivity {
private Toolbar userToolbar;
private RecyclerView usersList;
private DatabaseReference mUsersDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
userToolbar = (Toolbar) findViewById(R.id.users_toolbar);
setSupportActionBar(userToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Users");
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
usersList = (RecyclerView) findViewById(R.id.users_list);
usersList.setHasFixedSize(true);
usersList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.single_user_list_layout,
UsersViewHolder.class,
mUsersDatabase
) {
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
holder.setName(model.getName());
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
};
usersList.setAdapter(firebaseRecyclerAdapter);
}
public static class UsersViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name)
{
TextView userNameView = (TextView) mView.findViewById(R.id.single_user_name);
userNameView.setText(name);
}
}
}
The Error i'm getting is this:
please help!!

Sorry wanted to comment but i ain't got enough points to do so.
Try this first, if it doesnt work try using FirebaseRecyclerOptions
(The latest version (3.x) of FirebaseUI implements a different method ofinitializing a FirebaseRecyclerAdapter than previous versions.)
Make your " firebaseRecyclerAdapter " variable global, so you would have something like this.
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.single_user_list_layout,
UsersViewHolder.class,
mUsersDatabase
)

Related

Android Studio FirestoreRecyclerAdapter Comment with Replies (nested recyclerview)

I wanted to make a Comment & Reply function for social media app
something like instagram
enter image description here
is there a way to have a nested recyclerview by using FirestoreRecyclerAdapter?
here is my plan
enter image description here
and here is the structure of my FirestoreRecyclerAdapter
homeRecycler = findViewById(R.id.homeRecycler);
linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
homeRecycler.setLayoutManager(linearLayoutManager);
homeRecycler.setItemAnimator(null);
StorageReference profileRef = storageReference.child("ProfileImage/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(prof_img);
}
});
Query query = fStore.collection("Post")
.orderBy("homePostDate", Query.Direction.DESCENDING)
.limit(50);
FirestoreRecyclerOptions<HomeModel> options = new FirestoreRecyclerOptions.Builder<HomeModel>()
.setQuery(query, HomeModel.class)
.build();
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onRefresh() {
adapter.notifyDataSetChanged();
swipeRefresh.setRefreshing(false);
}
});
adapter = new FirestoreRecyclerAdapter<HomeModel, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull HomeModel model) {
holder.bind(model);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.home_each, group,false);
return new ViewHolder(view);
}
};
homeRecycler.setAdapter(adapter);
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView author, title, body, authorUid, docId, timestamp, upvotecount, downvotecount;
Button addcoment;
ToggleButton upvote, downvote;
ImageView prof_img;
HomeModel model;
RecyclerView replyRecycler;
public ViewHolder(#NonNull View itemView) {...}
public void bind(HomeModel homeModel) {...}
edit:
I tried just duplicating everything within the firestorerecycleradapter viewholder but couldnt make it work and dont even know if this is the proper way..
commentRecycler = findViewById(R.id.commentRecycler);
linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
commentRecycler.setLayoutManager(linearLayoutManager);
commentRecycler.setItemAnimator(null);
Query query = fStore.collection("Post")
.document(pdocId.getText().toString()).collection("comment")
.orderBy("commentPostDate", Query.Direction.DESCENDING)
.limit(50);
FirestoreRecyclerOptions<CommentModel> options = new FirestoreRecyclerOptions.Builder<CommentModel>()
.setQuery(query, CommentModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<CommentModel, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull CommentModel model) {
holder.bind(model);
linearLayoutManager2 = new LinearLayoutManager(HomeView.this, RecyclerView.VERTICAL, false);
holder.replyRecycler.setLayoutManager(linearLayoutManager2);
holder.replyRecycler.setItemAnimator(null);
Query query2 = fStore.collection("Post")
.document(pdocId.getText().toString()).collection("comment")
.document(model.docId).collection("reply")
.orderBy("commentPostDate", Query.Direction.DESCENDING)
.limit(50);
FirestoreRecyclerOptions<ReplyModel> options2 = new FirestoreRecyclerOptions.Builder<ReplyModel>()
.setQuery(query2, ReplyModel.class)
.build();
adapter2 = new FirestoreRecyclerAdapter<ReplyModel, ViewHolder2>(options2) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder2 holder, int position, #NonNull ReplyModel model) {
holder.bind(model);
Toast.makeText(HomeView.this, "this is test", Toast.LENGTH_SHORT).show();
}
#NonNull
#Override
public ViewHolder2 onCreateViewHolder(#NonNull ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.comment_each, group,false);
return new ViewHolder2(view);
}
};
holder.replyRecycler.setAdapter(adapter2);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.comment_each, group,false);
return new ViewHolder(view);
}
};
commentRecycler.setAdapter(adapter);
and then added another viewholder class
class ViewHolder extends RecyclerView.ViewHolder{
TextView author, body, authorUid, docId, timestamp, pReply, upvotecount, downvotecount;
TextInputLayout tilpReply;
ImageView prof_img;
Chip replyChip;
ToggleButton upvote, downvote;
ToggleButton replypop;
Button replyBtn;
CommentModel model;
RecyclerView replyRecycler;
public ViewHolder(#NonNull View itemView){...}
public void bind(CommentModel commentModel){...}
}
class ViewHolder2 extends RecyclerView.ViewHolder{
TextView author, body, authorUid, docId, timestamp, pReply, upvotecount, downvotecount;
TextInputLayout tilpReply;
ImageView prof_img;
Chip replyChip;
ToggleButton upvote, downvote;
ToggleButton replypop;
Button replyBtn;
CommentModel model;
RecyclerView replyRecycler;
public ViewHolder2(#NonNull View itemView){...}
public void bind(CommentModel commentModel){...}

Multiple class in Firebase, and when I get it by Recycler Adapter, the "adapter" declare in different if else statement. onStart and onStop not works

I am a newbie in Android Studio and I having some problem in Firebase Recycler Adapter. I got different database in Firebase and it follow to the user ID which is eBay(Example) and Kog. I want to work like if eBay having item, it will shows and else if Kog having item, it shows too. But in the code, I only declare adapter in if...else statement. This make onStart and onStop could not listening. Here is the code. Thanks all of you...
public RecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_history);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
database = FirebaseDatabase.getInstance();
requests = database.getReference("Users");
recyclerView = (RecyclerView)findViewById(R.id.order_history);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
loadOrders(common.currentUser.getUid());
}
private void loadOrders(String uid) {
DatabaseReference historyRef = FirebaseDatabase.getInstance().getReference("Users/orderHistory");
historyRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild("eBay")) {
FirebaseRecyclerAdapter<ebay_Order, orderViewHolder> adapter;
FirebaseRecyclerOptions<ebay_Order> options = new FirebaseRecyclerOptions.Builder<ebay_Order>()
.setQuery(requests.child(uid).child("eBay"), ebay_Order.class).build();
adapter = new FirebaseRecyclerAdapter<ebay_Order, orderViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull orderViewHolder holder, int position, #NonNull ebay_Order model) {
holder.txtOrderName.setText(model.getEbayId());
holder.txtOrderAmount.setText(model.getEbayAmount());
holder.txtOrderServices.setText(model.getOrderChoice());
}
#NonNull
#Override
public orderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_history, parent, false);
return new orderViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
if (snapshot.hasChild("KOG")){
FirebaseRecyclerAdapter<kog_Order, orderViewHolder> adapter;
FirebaseRecyclerOptions<kog_Order> options = new FirebaseRecyclerOptions.Builder<kog_Order>()
.setQuery(requests.child(uid).child("KOG"), kog_Order.class).build();
adapter = new FirebaseRecyclerAdapter<kog_Order, orderViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull orderViewHolder holder, int position, #NonNull kog_Order model) {
holder.txtOrderName.setText(model.getKogUsername());
holder.txtOrderAmount.setText(model.getKogAmounts());
holder.txtOrderServices.setText(model.getOrderChoice());
}
#NonNull
#Override
public orderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_history, parent, false);
return new orderViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this, InterPayMain.class);
orderHistory.this.finish();
startActivity(intent);
}
And the code for order View Holder
public class orderViewHolder extends RecyclerView.ViewHolder {
public TextView txtOrderName, txtOrderAmount, txtOrderServices;
public LinearLayout root;
public orderViewHolder(#NonNull View itemView) {
super(itemView);
root = itemView.findViewById(R.id.list_root);
txtOrderName = itemView.findViewById(R.id.order_id);
txtOrderAmount = itemView.findViewById(R.id.order_amount);
txtOrderServices = itemView.findViewById(R.id.order_choice);
}
And the error is
error: cannot find symbol adapter.startListening();
Is that got anyway to declare adapter in begining and able to work for different class.
As mentioned in the answer to this question: How to set two adapters to one RecyclerView?, a single RecyclerView can have only one adapter. You can create an adapter that has two different ViewHolders and chooses between them via overriding getItemViewType - see the question I linked for more information on implementing that solution.
An alternative is to have two separate RecyclerViews: one for each of your lists (eBay and Kog).

Getting Data from firebase and binding to recycler view

First im using this version of database : implementation 'com.firebaseui:firebase-ui-database:6.2.1'
Im trying this code and getting error at the bold statement error is : Expected 1 arguments but found 4.
code is :
private void loadMenu() {
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>**(Category.class,R.layout.menu_item,MenuViewHolder.class,category)** {
#Override
protected void onBindViewHolder(#NonNull MenuViewHolder holder, int position, #NonNull Category model) {
}
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
}}
Edited one :
private void loadMenu() {
FirebaseRecyclerOptions<Category> options=new FirebaseRecyclerOptions.Builder<Category>()
.setQuery(category,Category.class)
.build();
FirebaseRecyclerAdapter adapter= new FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView= LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_item,parent,false);
return new MenuViewHolder(itemView);
}
#Override
protected void onBindViewHolder(#NonNull MenuViewHolder viewHolder, int position, #NonNull Category model) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem=model;
viewHolder.setItemClickListener...
}
}
};
}
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtMenuName;
public ImageView imageView;
private ItemClickListener itemClickListener;
public MenuViewHolder(#NonNull View itemView) {
super(itemView);
txtMenuName=(TextView)itemView.findViewById(R.id.menu_name);
imageView= (ImageView)itemView.findViewById(R.id.menu_image);
}
#Override
public void onClick(View view) {
}
}
The latest version (3.x) of FirebaseUI implements a different method of initializing a FirebaseRecyclerAdapter than previous versions. From the using the FirebaseRecyclerAdapter documentation:
First, configure the adapter by building FirebaseRecyclerOptions. In this case we will continue with our chat example:
FirebaseRecyclerOptions<Chat> options =
new FirebaseRecyclerOptions.Builder<Chat>()
.setQuery(query, Chat.class)
.build();
Next create the FirebaseRecyclerAdapter object. You should already have a ViewHolder subclass for displaying each item.
So, for your example, you'll need to do something similar to:
FirebaseRecyclerOptions<image_details> options =
new FirebaseRecyclerOptions.Builder<image_details>()
.setQuery(myRef, image_details.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<image_details, BlogViewHolder>(options) {
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.individual_row, parent, false);
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(BlogViewHolder holder, int position, image_details model) {
// Bind the image_details object to the BlogViewHolder
// ...
}
};
Finally, the FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. To begin listening for data, call adapter.startListening() and adapter.stopListening() to stop the listener. It's recommended to call these in onStart() and onStop() respectively. Further details on this are available in the FirebaseRecyclerAdapter lifecycle documentation. taken from: firebaserecycleradapter() cannot be applied to FirebaseRecyclerAdapter

Firestore into recyclerview using FirebaseUI, no data displayed

I just got started with Firestore. So I tried fitting my data directly into a recyclerview, here's the code I used for reference.
Here's my UserRecyclerView Fragment :
public class UserRecyclerView extends Fragment{
private ArrayList<User> user;
RecyclerView mRecyclerView;
public UserRecyclerView(){}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_view,container,false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
FirestoreRecyclerAdapter adapter = getFirestoreRecyclerAdapter();
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
#NonNull
private FirestoreRecyclerAdapter getFirestoreRecyclerAdapter() {
Query query = FirebaseFirestore.getInstance()
.collection("users");
FirestoreRecyclerOptions<User> options = new FirestoreRecyclerOptions.Builder<User>()
.setQuery(query, User.class).build();
return new FirestoreRecyclerAdapter<User, UserViewHolder>(options) {
#Override
protected void onBindViewHolder(UserViewHolder holder, int position, User model) {
Log.d("USER", "DATA: "+model.getName());
holder.BindView(position, model);
}
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list, parent, false);
return new UserViewHolder(view);
}
};
}
private class UserViewHolder extends RecyclerView.ViewHolder{
TextView info;
UserViewHolder(View itemView) {
super(itemView);
info = (TextView) itemView.findViewById(R.id.info_text);
}
void BindView(int position, User model){
info.setText(model.getName()+" , "+model.getId());
}
}
There's nothing in my MainActivity except for starting the above fragment. I don't know what's wrong with my code. It shows no errors, when I run the app it doesn't crash. It just enters into the recyclerview layout, I checked it by placing a textview field for being sure(now removed). I want you to help me out with the code. It's probably because of the adapter? Help me figure out. I have also uploaded a snippet of my database.
Thanks in advance!
Make sure you call startListening on the adapter to initiate the connection to Cloud Firestore, otherwise no data will be loaded.
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
See:
https://github.com/firebase/FirebaseUI-Android/blob/master/firestore/README.md#firestorerecycleradapter-lifecycle
Create recyclerview like below:
FirestoreRecyclerAdapter adapter = getFirestoreRecyclerAdapter();
//add below line
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

Getting a Fragment inside a ViewPager in Android using getRegisteredFragment returns null

I've been searching a lot and I can't make it work.
I have a problem trying to get fragments inside a viewpager with a tabstrip.
I've implemented a SparseArray as I read here and several methods that I found here but I can't make it work.
The thing is that everytime I call adapter.getRegisteredFragment(position).. I always receive null unless I made it inside the onPageSelected event of the tabsStrip, there it works.. but I don't want to get the fragments there.
Those are my classes:
My fragment:
public class WeekFragment extends Fragment implements View.OnClickListener
{
private static final String ARG_POSITION = "position";
private int position;
private LinearLayout[] btns;
public static WeekFragment newInstance(int position) {
WeekFragment f = new WeekFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
fillFragment();
}
private void fillFragment()
{
// Irrelevant stuff..
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
return inflater.inflate(R.layout.week_fragment, container, false);
}
#Override
public void onClick(View v)
{
// Irrelevant stuff
}
public LinearLayout[] getBtns()
{
return btns;
}
public void setBtns(LinearLayout[] btns)
{
this.btns = btns;
}
}
My adapter:
public class WeekAdapter extends FragmentPagerAdapter
{
Calendar cal;
Context context;
SparseArray<Fragment> registeredFragments;
private String[] TITLES = new String[6];
public WeekAdapter(FragmentManager fm, Context context)
{
super(fm);
registeredFragments = new SparseArray<>();
this.context = context;
fillTitles();
}
private void fillTitles()
{
// Fill titles
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
return WeekFragment.newInstance(position);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
and my activity:
public class MyActivity extends FragmentActivity
{
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private WeekAdapter adapter;
private List<DayResumeItem> listDayResumesItems;
private User u;
private View mProgressView;
private View mRotaView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rota2);
mProgressView = findViewById(R.id.view_progress);
mRotaView = findViewById(R.id.view_rota);
this.u = this.getIntent().getExtras().getParcelable(getString(R.string.parcel_user));
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
adapter = new WeekAdapter(getSupportFragmentManager(), getApplicationContext());
pager.setAdapter(adapter);
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is not null. Here I can work, but I don't want to.
}
#Override
public void onPageSelected(int position)
{
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is null and I can't work.
}
#Override
protected void onResume()
{
super.onResume();
getList();
}
}
It is everytime I call adapter.getRegisteredFragment(position) on my activity where it crash because it always return null..
I swear that I've been searching a lot but I'm unable to make it work.
Thank you very much everybody!
I think my problem was that I was calling this adapter.getRegisteredFragment(position) in the onCreate of my activity, and in the onCreate, the viewpager is still not fully loaded and the registeredFragments aren't still instantiated, so the list is still empty..
If you move this callings to another place when the viewpager is fully loaded, it will work.
The items in registeredFragments are initialized in instantiateItem() method, which should be called during the process of drawing views. And this drawing process happens after onCreate()/onResume().
I am not sure what stuff you want to do by getting Fragment in onCreate(), but generally it is not a good idea since the Fragment is not initialized at that moment. You should access the fragment in onPageSelected() as you said.

Resources