I have a hard time getting fragments to update their views… Specifically, fragments that exist in a ViewPager with ActionBarSherlock.
Here is my fragment class:
public class SearchFragment extends Fragment{
private String mInterests;
private String mSentence;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.bounty_search_layout, container, false);
}
@Override
public void onResume() {
super.onResume();
getUserInterests();
}
/*
* Get the users interests from the underlying
* data store.
*/
public void getUserInterests() {
TextView tv = (TextView) getView().findViewById(R.id.bounty_search_txtResult);
DatabaseHelper dbHelper = new DatabaseHelper(getActivity());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(DatabaseConstants.TABLE_NAME, null, null, null, null, null, null);
cursor.moveToFirst();
mInterests = cursor.getString(cursor.getColumnIndex(DatabaseConstants.INTERESTS));
if(mInterests.length() == 0) {
mSentence = "You have no interests.";
}
else {
mSentence = "Your interests are: ";
mInterests = cursor.getString(cursor.getColumnIndex(DatabaseConstants.INTERESTS));
}
tv.setText(mSentence + mInterests);
cursor.close();
db.close();
dbHelper.close();
}
}
The way I’m calling this fragment from my FragmentActivity is in the following…
SearchFragment searchInterests = new SearchFragment();
My views in the fragment are properly setup when it first runs, but when I call something like…
searchInterests.update();
from the FragmentActivity, to update some views,the getView() of
TextView tv = (TextView) getView().findViewById(R.id.results);
returns null and fails. I’m struggling to understand why this is.. Someone had mentioned to me that It’s because my Fragment is not attached to anything… I don’t quite understand this part and not only that but I just dont understand why getView() points to null if onCreateView was successful the first time? Doesn’t getView() gets the View returned by onCreateView? Here is the full code set: https://gist.github.com/1369653
So after some time, I figured it out… Problem was coming from how the FragmentPagerAdapter was returning the fragment…
This was returning a NEW fragment each time getItem() was called. However, I also had…
Which was creating a new fragment before it was added to the adapter. So the adapter was receiving a new fragment AND returning a new fragment instead of returning the same one I gave it. So I simply changed the getItem() function to return a NEW fragment if none of the same class already exist.