It's hard for me to get fragments in order to update their views ... In particular, fragments that exist in 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(); } 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(); } }
What I call this snippet from my FragmentActivity is in the following ...
SearchFragment searchInterests = new SearchFragment();
My views in the snippet are correctly set up on first run, but when I call something like ...
searchInterests.update();
from FragmentActivity to update some views, getView () from
TextView tv = (TextView) getView().findViewById(R.id.results);
returns null and does not work. I'm trying to understand why this is so .. Someone told me that this is because my fragment is not attached to anything ... I do not quite understand this part, and not only that, but I just do not understand why getView () points to null if onCreateView was successful the first time? Does getView () get the view returned by onCreateView? Here is the full code: https://gist.github.com/1369653
source share