Show new page in ViewPager - android

I'm having a ViewPager with a FragmentStatePagerAdapter that shows items from a ContentProvider via a CursorAdapter. So there is a callback when data is changed in the content provider that automatically creates/removes pages.
When I create a new item via ContentResolver.insert() from another fragment I want to show the created page in the ViewPager.
To show a page I call ViewPager.setCurrentItem(). But it seems that directly after the insert call the ViewPager is not yet updated. When and where do I call that?
Edit:
Here is my MainActivity:
I'm having one fragment for creation of items (on position 0) and several items from the content provider. From the creation fragment I call insert on the content resolver.
public class MainActivity extends FragmentActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
SectionsPagerAdapter mSectionsPagerAdapter;
SimpleCursorAdapter mCommitmentAdapter;
private static final byte LOADER_ID = 0;
private static final String TAG = MainActivity.class.getName();
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adapter for commitment names and ids
mCommitmentAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null,
new String[] { Commitment.Columns.NAME },
new int[] { android.R.id.text1 }, 0);
// Adapter for the saved commitments
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager(), mCommitmentAdapter);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public final Loader<Cursor> onCreateLoader(int id, final Bundle args) {
....
}
#Override
public final void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCommitmentAdapter.swapCursor(cursor);
}
#Override
public final void onLoaderReset(Loader<Cursor> loader) {
mCommitmentAdapter.swapCursor(null);
}
public final void showPageWithCommitmentId(long id) {
// this is called after contentresolver.insert
// but it does not work
mViewPager.setCurrentItem(mSectionsPagerAdapter.getItemPosition(id));
}
#Override
protected void onDestroy() {
if (mSectionsPagerAdapter != null) {
mSectionsPagerAdapter.destroy();
}
getLoaderManager().destroyLoader(LOADER_ID);
super.onDestroy();
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
final CursorAdapter wrappedAdapter;
final DataSetObserver subObserver;
public SectionsPagerAdapter(FragmentManager fm,
SimpleCursorAdapter adapter) {
super(fm);
this.wrappedAdapter = adapter;
subObserver = new DataSetObserver() {
#Override
public void onChanged() {
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
// Probably destroying the loader
}
};
if (wrappedAdapter != null)
wrappedAdapter.registerDataSetObserver(subObserver);
}
public void destroy() {
if (wrappedAdapter != null) {
wrappedAdapter.unregisterDataSetObserver(subObserver);
}
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Fragment fragment = CreateCommitmentSectionFragment
.getInstance(position);
return fragment;
} else {
// create new ShowCommitSectionFragment
Fragment fragment = ShowCommitmentSectionFragment.getInstance(
getItemId(position), getPageTitle(position).toString());
return fragment;
}
}
public long getItemId(int position) {
long id = 0;
if (wrappedAdapter != null && position > 0) {
Cursor c = (Cursor) wrappedAdapter.getItem(position - 1);
if (c != null && !c.isAfterLast() && !c.isBeforeFirst()) {
id = c.getLong(0);
}
}
return id;
}
#Override
public int getCount() {
if (wrappedAdapter != null)
return 1 + wrappedAdapter.getCount();
else
return 1;
}
#Override
public CharSequence getPageTitle(int position) {
if (position >= getCount())
return null;
if (position == 0) {
return MainActivity.this.getString(R.string.main_create_create);
}
Cursor c = (Cursor) wrappedAdapter.getItem(position - 1);
if (c != null && !c.isAfterLast() && !c.isBeforeFirst()) {
return c.getString(1);
}
return null;
}
#Override
public int getItemPosition(Object object) {
Fragment f = (Fragment) object;
long listId = 0;
if (f instanceof ShowCommitmentSectionFragment) {
listId = f.getArguments().getLong(
ShowCommitmentSectionFragment.ARG_COMMITMENT_ID);
}
return getItemPosition(listId);
}
/**
* Get the position of the given commitment id.
*
* #param commitmentId
* #return
*/
public int getItemPosition(final long commitmentId) {
int length = getCount();
int result = POSITION_NONE;
int position;
for (position = 0; position < length; position++) {
if (commitmentId == getItemId(position)) {
result = position;
break;
}
}
return result;
}
}
}

Related

How to destroy a Fragment programmatically in FragmentStatePagerAdapter

I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}

How does findFragmentByTag work in a parent Fragment to know which child fragment is currently showing with ViewPagerAdapter?

My MainFragment is like
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1;
int position_tab = 0;
Bundle args;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(4);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(3);
// changeTab();
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
pager.setCurrentItem(position_tab);
}
Log.e("Fragment", fragment + "" +pager.getCurrentItem());
//
return view;
}
public void changeTab(){
pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss" ,(Fragment) maps.get(position).get(KEY_FRAGMENT) +"");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
#Override
public int getCount() {
return maps.size();
}
}
}
Here I can get that this fragment is visible by using findFragmentByTag. I wanna know how I can use same thing for the child of this Fragment which are added using FragmentPagerAdapter.
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
Log.e("Fragment", fragment + "" +pager.getCurrentItem()); }
So now I wanna do same thing and get name of current selected Fragment out of 3 which are mentioned above in FragmentPagerAdapter as AdvisoryPagerFragment,TopAdvisoryPagerFragment and ExperViewPagerFragment.
Try this
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if(fragment instanceOf Fragment1){
// Do something
}else if(fragment instanceOf Fragment2){
// Do something
}else{
// Do something
}

ViewPager + FragmentStatePagerAdapter: How to recreate all fragment with new adapter

I'm using the v4 compatibility library. I have a Fragment Tabhost, the first tab have a ViewPager using FragmentStatePagerAdapter. The problem is when I switch to other tabs, change data of the first tab's ViewPager, then return to the first tab, recreate new Adapter with new data and set it to ViewPager, but the first 3 fragments in ViewPager still hold reference to old data.
My code in the first tab to create adapter (called in onCreateView method):
private void setPagerData() {
if (mPager == null || AppConfig.getInstance().todayData == null)
return;
if (AppConfig.getInstance().todayData != null && !AppConfig.getInstance().todayData.isEmpty()) {
//
mPager.setOffscreenPageLimit(AppConfig.PAGER_OFFSCREEN_PAGE_LIMIT);
mPager.setAlwaysDrawnWithCacheEnabled(true);
//
mAdapter = new TodayPagerAdapter(getChildFragmentManager(), AppConfig.getInstance().todayData);
mPager.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
if (mAdapter.getCount() == 1)
mPager.setCurrentItem(0);
else
mPager.setCurrentItem(1);
text_currentpage.setText("1");
text_totalpage.setText(String.valueOf(mAdapter.getCount() - 2));
anim_numpage = AnimationUtils.loadAnimation(TodayFragment.this.getActivity(), R.anim.fade_numpage);
layout_numpage.setVisibility(View.INVISIBLE);
image_nextpage.setOnClickListener(this);
image_prevpage.setOnClickListener(this);
//
mPager.setOnPageChangeListener(this);
} else
onNoData(true);
}
onDestroyView():
public void onDestroyView() {
AppUtils.Log("Destroy view Today Fragment");
mAdapter = null;
mPager = null;
super.onDestroyView();
}
My Adapter:
public class TodayPagerAdapter extends FragmentStatePagerAdapter {
private List<PostDTO> posts;
private FragmentManager fm;
public TodayPagerAdapter(FragmentManager fm, List<PostDTO> posts) {
super(fm);
this.fm = fm;
this.posts = posts;
if (posts == null)
posts = new ArrayList<PostDTO>();
}
#Override
public Fragment getItem(int page) {
if (page == 0 && posts.size() > 1)
return TodayPagerFragment.init(posts.size() - 1, posts.get(posts.size() - 1));
if (page == posts.size() + 1)
return TodayPagerFragment.init(0, posts.get(0));
if (posts.size() > 1)
return TodayPagerFragment.init(page - 1, posts.get(page - 1));
return TodayPagerFragment.init(page, posts.get(page));
}
#Override
public int getCount() {
if (posts.size() <= 1)
return posts.size();
return posts.size() + 2;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
My ViewPager's Fragment:
public class TodayPagerFragment extends AbstractFragment implements View.OnClickListener {
int page;
private ImageView iv_image;
private LikeButton button_like;
private PostDTO data;
public static TodayPagerFragment init(int val, PostDTO data) {
TodayPagerFragment frm = new TodayPagerFragment();
Bundle args = new Bundle();
args.putInt("page", val);
frm.setArguments(args);
frm.data = data;
return frm;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments() != null ? getArguments().getInt("page") : 0;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_today_viewpager, container, false);
setupView(view);
iv_image = (ImageView) view.findViewById(R.id.today_viewpager_image);
button_like = (LikeButton) view.findViewById(R.id.today_button_like);
button_like.setUp(true);
initViews();
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.today_viewpager_image:
((BaseContainerFragment) getParentFragment().getParentFragment()).replaceFragment(TodayDetailFragment.init(this.data), true);
break;
case R.id.today_button_like:
if (!AppConfig.getInstance().isLoggedIn || AppConfig.getInstance().appUser == null) {
AppUtils.openLogin(getActivity());
} else {
String ms = getString(R.string.do_you_want_to_like_this_post_);
if (data.isLiked())
ms = getString(R.string.do_you_want_to_unlike_this_post_);
new MyDialogHandler().confirm(getActivity(), getString(R.string.like_confirm), ms, getString(R.string.no), getString(R.string.yes), new Runnable() {
#Override
public void run() {
new PostLikeTask(button_like, data, !data.isLiked()).execute();
// data.setLiked(!data.isLiked());
}
}, null);
}
break;
default:
break;
}
}
// Setup view data
private void initViews() {
iv_image.setOnClickListener(this);
button_like.setOnClickListener(this);
if (this.data != null) {
AppUtils.Log("Current: //////// " + (data.toString().equals(AppConfig.getInstance().todayData.get(page))));
// if (AppConfig.getInstance().appUser != null &&
// AppConfig.getInstance().isLoggedIn)
// new GetLikedTask().execute();
// else
button_like.setData(data.getLikes(), data.isLiked());
// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL
// + this.data.getImage(), iv_image);
// onLoading(true);
UrlImageViewHelper.setUrlDrawable(iv_image, AppConfig.SERVER_IMAGE_URL + this.data.getImage());
}
}
}

ViewPager Cursor position

I am writing a simple news app as a learning exercise. Display a listfragment driven by a SQLite cursor. Click and go to detail screen. Now trying to convert detail screen to ViewPager. I do not want to pass the Cursor from listfragment to ViewPager activity, so I pass the current position in the cursor instead and then create a new Cursor. Can't seem to get the position right though. If I set it in the Activity and not getItem() it goes to the correct position but never changes. If I set it in getItem, it always starts at position 0. The key lines are
// cp.getCursor().moveToPosition(mStartPosition);
// cp.notifyDataSetChanged();
Thanks for any help.
public class ViewPagerActivity extends FragmentActivity {
private static final int NUM_PAGES = 5;
private static String mSectionSelected = "";
private static int mStartPosition;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager);
// Instantiate a ViewPager and a PagerAdapter.
mSectionSelected = (String)this.getIntent().getSerializableExtra("SECTION");
mPager = (ViewPager) this.findViewById(R.id.pager);
CursorPagerAdapter cp = new CursorPagerAdapter( getSupportFragmentManager(), mSectionSelected);
mPager.setAdapter(cp);
// cp.getCursor().moveToPosition(mStartPosition);
// cp.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
}
And here is the adapter - the key line is cursor.moveToPosition(position);
public class CursorPagerAdapter extends FragmentStatePagerAdapter {
private Cursor cursor;
private static String mSectionSelected;
public CursorPagerAdapter(FragmentManager fm, String mSection) {
super(fm);
mSectionSelected = mSection;
this.cursor = NewsManager.get(ApplicationContext.getInstance()).queryNews(mSectionSelected);
}
#Override
public PagerDetailFragment getItem(int position) {
if (cursor == null) // shouldn't happen
return null;
cursor.moveToPosition(position);
PagerDetailFragment frag;
try {
frag = PagerDetailFragment.newInstance();
String mTitle = cursor.getString(NewsDatabaseHelper.COLNUM_TITLE);
String mSection = cursor.getString(NewsDatabaseHelper.COLNUM_CATEGORY);
String mSource = cursor.getString(NewsDatabaseHelper.COLNUM_SOURCE);
String mPublishedDate = cursor.getString(NewsDatabaseHelper.COLNUM_PUBLISHDATE);
String mThumbnail = cursor.getString(NewsDatabaseHelper.COLNUM_THUMBNAIL);
String mBody = cursor.getString(NewsDatabaseHelper.COLNUM_CONTENT);
Bundle args = new Bundle();
args.putString(NewsDatabaseHelper.COLUMN_TITLE, mTitle);
args.putString(NewsDatabaseHelper.COLUMN_CATEGORY, mSection);
args.putString(NewsDatabaseHelper.COLUMN_SOURCE, mSource);
args.putString(NewsDatabaseHelper.COLUMN_PUBLISHDATE, mPublishedDate);
args.putString(NewsDatabaseHelper.COLUMN_THUMBNAIL, mThumbnail);
args.putString(NewsDatabaseHelper.COLUMN_CONTENT, mBody);
frag.setArguments(args);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return frag;
}
#Override
public int getCount() {
if (cursor == null)
return 0;
else
return cursor.getCount();
}
public void swapCursor(Cursor c) {
if (cursor == c)
return;
this.cursor = c;
notifyDataSetChanged();
}
public Cursor getCursor() {
return cursor;
}
}

Unable to reset FragmentAdapter to ViewPager in onActivityResult(...)

I am using a FragmentActivity in that ViewPager, in onCreate(...) method i am setting FragmentPagerAdapter adapter to ViewPager it is working fine here but when i try to reset new FragmentPagerAdapter to ViewPager in onActivityResult(...) method only the constructor of the adapter is getting calling and public Fragment getItem(int position); is not getting called because of which i am getting fragment null. so when i try to get the current visible fragment after reseting the adapter in onActivityResult(...) i am getting null.
This is what I am doing in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.blocked_list);
lable = getIntent().getStringExtra("ItemName");
blocked_list_lable = (TextView) findViewById(R.id.blocked_list_lable);
add_Contact = (Button) findViewById(R.id.add);
mAdapter = new CallManagerFragmentAdapter(getSupportFragmentManager(), lable);
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
addNewContact = new AddNewContactPopup(this);
addNewContact.setPopDimentions((int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 320, getResources()
.getDisplayMetrics()), (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 280, BlackList.this.getResources()
.getDisplayMetrics()));
blocked_list_lable.setText(lable);
setListener(add_Contact);
}
This is what I am doing in onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CALLS_SMS_LOGS || requestCode == CONTACTS_LIST) {
if (resultCode == RESULT_OK) {
String result = data.getStringExtra("dbUpdateSucess");
if (result.equals("Success")) {
Logger.log("Info", TAG,
"Update from call logs is Sucess...");
//Cursor cursor = getCursor(lable);
mAdapter = new CallManagerFragmentAdapter(getSupportFragmentManager(), lable);
mPager.setAdapter(mAdapter);
//adapter = new BlackListAdapter(this, cursor);
//blocked_List.setAdapter(adapter);
return;
} else {
Logger.log("Error", TAG, "Update from call logs failed...");
}
}
}
}
Here is my FragmentAdapter code;
class CallManagerFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "Call Logs", "Blacklist No"};
protected static final String[] BLACK_LIST_SMS_CONTENT = new String[] { "SMS Logs", "Blacklist No"};
protected static final String[] WHITELIST_CALLS_CONTENT = new String[] { "Call Logs", "Whitelist No"};
protected static final String[] WHITELIST_SMS_CONTENT = new String[] { "SMS Logs", "Whitelist No"};
protected static final String[] PRIVATE = new String[] { "SMS Logs", "Call Logs", "Private No"};
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera/*,
R.drawable.perm_group_device_alarms,
R.drawable.perm_group_location*/
};
private int mCount = CONTENT.length;
private String lable;
public HashMap<Integer, CallManagerFragment> fragmentMap;
public CallManagerFragmentAdapter(FragmentManager fm, String lable) {
super(fm);
this.lable = lable;
fragmentMap = new HashMap<Integer, CallManagerFragment>();
}
#Override
public Fragment getItem(int position) {
String content;
CallManagerFragment fragment = CallManagerFragment.newInstance(content, lable);
fragmentMap.put(position, fragment);
return fragment;
}
public CallManagerFragment getFragment(int key) {
return fragmentMap.get(key);
}
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
fragmentMap.remove(position);
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
if(lable.equals("Whitelist Calls")) {
return CallManagerFragmentAdapter.WHITELIST_CALLS_CONTENT[position % WHITELIST_CALLS_CONTENT.length];
} else if (lable.equals("Whitelist SMS")) {
return WHITELIST_SMS_CONTENT[position % WHITELIST_SMS_CONTENT.length];
} else if(lable.equals("Private")) {
return PRIVATE[position % PRIVATE.length];
} else if(lable.equals("Blacklist SMS")) {
return BLACK_LIST_SMS_CONTENT[position % BLACK_LIST_SMS_CONTENT.length];
}
return CallManagerFragmentAdapter.CONTENT[position % CONTENT.length];
}
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}

Categories

Resources