So I have a class which has a tabbed layout of 4 fragments each with a list of checkboxes. I need to save the state of those checkboxes in a sqlite database, but I am not able to access them at all with findViewById from the activity (throws a nullpointerexception). How would I go about doing this? Thanks!
Asked
Active
Viewed 325 times
3 Answers
0
You can't access view elements in your fragment from your activity, it simply wasn't created for this. And why would you need to?
You can simply save the values of your checkboxes inside your fragment code, where you have full access to the entire view. You can still access your sqlite database inside a fragment, it doesn't have to be an activity.

Moonbloom
- 7,738
- 3
- 26
- 38
0
In a fragment you can override the onCreateView and inflate the view. http://developer.android.com/training/basics/fragments/creating.html
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.article_view, container, false);
TextView textView = (TextView) v.findViewById(R.id.testelement);
return v;
}
And find the elements by doing this.

PsykoGert
- 48
- 4
0
When you first add or replace any fragment.. add a tag for it.. then later use this is acticity
fragment f1 = getfragmentmanager.findfragmentByTag("tag1");
then you can get and save
f1.getCheckbox1().ischecked()...
amd so on... you can use getFragmentManager.getFragments...

challenger
- 2,184
- 1
- 18
- 25
-
How would I do this if I am working with a viewpager instead? I don't use transactions at all, so there isn't an add or replace used. – Milan Parikh Aug 27 '15 at 17:52
-
use Fragment f = getFragmentManager().findFragmentByTag("android:switcher:"+R.id.pager+":"+indexPage); – challenger Aug 27 '15 at 18:06
-
you may have to use getSupportFragmentManager() instead of getFragmentManager()... depends on how did you define your pagerAdapter – challenger Aug 27 '15 at 18:12
-
Thank you for your answers, but the problem I have is that I don't know where to add the tag... – Milan Parikh Aug 27 '15 at 18:21
-
you dont add the tag... the viewpager add the tags to its fragments – challenger Aug 27 '15 at 18:25
-
it is doing that.. all what you have to do is to get the visible fragment.. using what i told you in the previous comment – challenger Aug 27 '15 at 18:27
-
check this http://stackoverflow.com/questions/8785221/retrieve-a-fragment-from-a-viewpager – challenger Aug 27 '15 at 18:31