Android Fragment Issues

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(); } /* * 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(); } } 

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

+4
source share
1 answer

So, after some time I realized this ... The problem was how the FragmentPagerAdapter returned the fragment ...

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

This returned a NEW fragment every time getItem () was called. However, I also had ...

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

What created a new fragment before adding it to the adapter. Thus, the adapter received a new fragment And returned a new fragment instead of returning the same one that I gave it. So I just changed the getItem () function to return a NEW fragment if none of the same class already exists.

+3
source

Source: https://habr.com/ru/post/1381449/


All Articles