Java – Android fragment issues

Android fragment issues… here is a solution to the problem.

Android fragment issues

I’m having a hard time getting fragments to update their View… Specifically, fragments that exist in ViewPager with ActionBarSherlock.

Here is my fragment class:

public class SearchFragment extends Fragment{
private String mInterests;
private String mSentence;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.bounty_search_layout, container, false);

public void onResume() {

 * Get the users interests from the underlying
 * data store.
public void getUserInterests() {
    TextView tv = (TextView) getView().findViewById(;
    DatabaseHelper dbHelper = new DatabaseHelper(getActivity());
    SQLiteDatabase db = dbHelper.getReadableDatabase();

Cursor cursor = db.query(DatabaseConstants.TABLE_NAME, null, null, null, null, null, null);
    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);

The way I call this fragment from my FragmentActivity is as follows….

SearchFragment searchInterests = new SearchFragment();

My View in the fragment is set up correctly on first run, but when I call something like… When there is something like that


From FragmentActivity, update some Views, getView().

TextView tv = (TextView) getView().findViewById(;

Returns null and fails. It’s hard for me to understand why this is so… Someone mentioned to me that this is because my fragment doesn’t have anything attached… I don’t quite understand this part, not only that, but I just don’t understand why getView() points to null if onCreateView succeeds for the first time? getView() doesn’t get the View returned by onCreateView? Here is the complete set of code:


So after a while, I figured it out… The problem is how the FragmentPagerAdapter returns fragment


public Fragment getItem(int position) {
    return Fragment.instantiate(mContext, mTabs.get(position), null);

Each time getItem() is called, a new fragment is returned. However, I also have….

searchInterests = new SearchFragment();
selectInterests = new SelectFragment();

It is creating a new fragment before adding it to the adapter. So the adapter is receiving a new fragment and returning a new fragment instead of the same fragment I gave it. So I simply changed the getItem() function to return a new fragment if the same class doesn’t exist.

Related Problems and Solutions