Reputation: 1706
I'm using a ViewPager
in my Activity which has multiple Fragments. in the onCreate
method of my Activity, I want to add multiple views to one of those fragments so that they can be seen at start. the problem is that i can not find a way to access that fragment. how to do that? I have tried to access the RecyclerView
of that fragment at this way:
public class CaafeFragment extends Fragment {
private RecyclerView recyclerView = null;
public CaafeFragment() {
// 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_caafe, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.caafeRecyclerView);
return view;
}
public RecyclerView getRecyclerView() {
return (RecyclerView) getView().findViewById(R.id.caafeRecyclerView);
}
}
but it returns null when i call getRecyclerView()
from the onCreate()
of my activity
// activity
public void onCreate()
{
.
.
.
CaafeFragment caafeFragment=new CaafeFragment();
caafeRecyclerView = caafeFragment.getRecyclerView(); // here it returns null
}
Upvotes: 1
Views: 901
Reputation: 911
CaafeFragment caafeFragment=new CaafeFragment();
caafeFragment points to nothing, it should refer a fragment, this line just creates fragment object. You are trying to get something that it does not contain. You should specify which fragment that object holds:
CaafeFragment caafeFragment=(CaafeFragment) getFragmentManager().findFragmentById(R.id.YOUR_FRAGMENT_ID);
caafeRecyclerView = caafeFragment.getRecyclerView();
Now the caafeFragment object contains something you can access from.
EDIT
You should return the private RecyclerView recyclerView
object that you set via "view" in OnCreate(),
in getRecyclerView()
replace return (RecyclerView) getView().findViewById(R.id.caafeRecyclerView);
by:
public RecyclerView getRecyclerView() {
return recyclerView;
}
What is certain here is that recyclerView object holds view that is instantiated, and this line can be tracked to make sure that, in onCreate(),
recyclerView = (RecyclerView) view.findViewById(R.id.caafeRecyclerView);
Has value or not.
Upvotes: 1
Reputation: 22945
After the onCreate()
is called (in the Fragment), the Fragment's onCreateView()
is called due to this is throws error as you have declared recycleview in onCreate() method.
Check onCreate(), onCreateView() difference for more detail.
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.<specific_function_name>();
Upvotes: 1