Fragment + ViewPager fail when orientation change - android

I have one FragmentActivity, with one ViewPager and one FragmentStatePagerAdapter. When i change the screen orientation screen on viewPager, i can see the viewPager but not the fragments. I test all post on Stackoverflow.
FragmentStatePagerAdapter
public class PageAdapter extends FragmentStatePagerAdapter{
private static final String[] CONTENT = new String[] { "All", "Installed"};
List<Application> applicationList;
public PageAdapter(FragmentManager fm,List<Application> applicationList) {
super(fm);
this.applicationList = applicationList;
}
#Override
public Fragment getItem(int position) {
return ListAppFragment.newInstance(CONTENT[position % CONTENT.length],applicationList);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {return CONTENT.length;}
}
Fragment
public class ListAppFragment extends Fragment {
public static final String APPS_LIST = "APPS_LIST";
public static final String VIEW_TYPE = "VIEW_TYPE";
private GoogleCardAdapter mGoogleCardAdapter;
private ListView listView;
private Utils utils;
String typeView;
public static ListAppFragment newInstance(String typeView,List<Application> applicationList) {
ListAppFragment listAppFragment = new ListAppFragment();
Bundle bundle = new Bundle();
bundle.putString(VIEW_TYPE, typeView);
bundle.putParcelableArrayList(APPS_LIST, (ArrayList<Application>) applicationList);
listAppFragment.setArguments(bundle);
return listAppFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
utils = new Utils((Context)getActivity().getApplicationContext());
typeView = getArguments().getString(VIEW_TYPE);
View v = inflater.inflate(R.layout.list_app_fragment, container, false);
listView = (ListView)v.findViewById(R.id.activity_googlecards_listview);
ArrayList<Application> applicationList = getArguments().getParcelableArrayList(APPS_LIST);
setApplicationList(applicationList, typeView);
return v;
}
private void setApplicationList(List<Application> applicationList,String typeView) {
if(typeView=="Installed"){
applicationList = utils.getAppsAlreadyInstalled(applicationList);
}
mGoogleCardAdapter = new GoogleCardAdapter(getActivity().getApplicationContext(),applicationList);
AlphaInAnimationAdapter alphaInAnimationAdapter = new AlphaInAnimationAdapter(new AlphaInAnimationAdapter(mGoogleCardAdapter));
alphaInAnimationAdapter.setInitialDelayMillis(300);
alphaInAnimationAdapter.setAbsListView(listView);
listView.setAdapter(alphaInAnimationAdapter);
}
}
Call to adapter in FragmentActivity:
public void getApplicationListFromApi(List<Application> applicationList) {
this.applicationList = applicationList;
pageAdapter= new PageAdapter(getSupportFragmentManager(),this.getApplicationList());
pager.setAdapter(pageAdapter);
//Bind the title indicator to the adapter
TitlePageIndicator titleIndicator = (TitlePageIndicator)findViewById(R.id.titles);
titleIndicator.setViewPager(pager);
}

The problem is "android support v4" library, i am using version r7 (in Maven repository is outdated), and this not work. I changed with version r13 and work fine (refactor proyect to Gradle).

Related

Android tabs show wrong fragments

Hello, I'm trying to implement an Activity with tabs. Some tabs contain a fragment that shows simple list, others a tree view like list.
The fragments with simple list work fine, while I'm having troubles with the one which shows tree view like list: the tree are build properly, but I get them in the wrong tabs. In the first tab I always see the content of the second one, and swiping back or expanding/collapsing the tree produces a new unwanted substitution of the whole tree.
I'm struggling to understand what I'm doing wrong. I hope you can suggest me what to do. Thanks in advance!
Here's my code:
Pager Adapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
private final List<ListFragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager)
{
super(manager);
}
#Override
public ListFragment getItem(int index) {
return mFragmentList.get(index);
}
#Override
public int getCount()
{
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(int index, boolean tree) {
Bundle b=new Bundle();
String category= Items.getCategoryByIndex(index);
b.putString(Items.CATEGORY,category);
ListFragment fragment;
if(!tree) {
fragment = new ContentFragment();
} else {
fragment = new TreeFragment();
}
fragment.setArguments(b);
mFragmentList.add(fragment);
mFragmentTitleList.add(Items.getCategoryByIndex(index));
}
}
This is the TreeFragment class:
public class TreeFragment extends TreeViewFragment {
TreeListAdapter mAdapter;
public TreeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle b = getArguments();
String category = (String) b.get(Items.CATEGORY);
GlobalVariables.dataList = Items.getTreeNodeByCategory(category);
GlobalVariables.nodes = TreeViewLists.LoadInitialNodes(GlobalVariables.dataList);
TreeViewLists.LoadDisplayList();
mAdapter = new TreeListAdapter(inflater.getContext());
setListAdapter(mAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
and in the activity:
public class MyActivity extends AppCompatActivity {
private ViewPager mViewPager;
private PagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mAdapter = new PagerAdapter(getSupportFragmentManager());
// (...) Content creation (...)
mAdapter.addFragment(0, true);
mAdapter.addFragment(1, true);
mAdapter.addFragment(2, true);
mAdapter.addFragment(3, true);
mAdapter.addFragment(4, false);
mAdapter.addFragment(5, false);
mViewPager.setAdapter(mAdapter);
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(mViewPager);
}

ViewPager and dynamic fragments : re-instaciation gives NPE

I faced an issue with ViewPager and ViewPagerAdapter in Android.
I use a viewpager with 2 static fragments (one using a textEdit and the second one using a listview). Theyr are working pretty good.
But i have a problem with the third fragment which is dynamic.
It uses the camera and has to be instanciated, destroyed, re-instanciated following a scenario. So, the ViewPagerAdapter could contain 2 or 3 framents.
The problem appears when I re-instaciate the third fragment, I got a NPE after OnCreateView() (the main layout view is null after this method, but is not null inside the method).
There is the code for the main activity :
mViewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager();
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
The setupViewPager() :
private void setupViewPager() {
mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mTabFragmentDocument = new TabFragmentDocument();
mTabFragmentDocument.setApp(this);
mTabFragmentText = new TabFragmentText();
mTabFragmentText.setApp(this);
mViewPagerAdapter.addFragment(mTabFragmentText, AbstractDefiner.TEXT);
mViewPagerAdapter.addFragment(mTabFragmentDocument, AbstractDefiner.DOCUMENT);
mViewPager.setAdapter(mViewPagerAdapter);
}
To create the third fragment :
mTabFragment = new TabFragment();
mTabFragment .setApp(this);
mViewPagerAdapter.addFragment(mTabFragment, "THIRD");
mViewPagerAdapter.notifyDataSetChanged();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(2);
mViewPagerAdapter.notifyDataSetChanged();
mTabFragment .setParams(tmp[1], tmp[2], tmp[3], tmp[4]);
mTabFragment .setupView();
mTabFragment .startWork();
}
}, 1000);
And to destroy it :
mViewPager.setCurrentItem(0);
mViewPager.removeViewAt(2);
mTabFragment .onDestroy();
mViewPagerAdapter.remove(2);
mViewPagerAdapter.notifyDataSetChanged();
mTabFragment = null;
Then, the Adapter code :
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void remove(int index) {
mFragmentList.remove(index);
mFragmentTitleList.remove(index);
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Finally, the code of the third fragment :
public class TabFragment extends Fragment implements SurfaceHolder.Callback,
GLSurfaceView.Renderer {
private static final String LOGCAT = "WEB_RTC_VISIO";
private HomeActivity mApp;
private String p1;
private String p2;
private String p3;
private String p4;
private VideoSource mLocalVideoSource;
private VideoRenderer.Callbacks mLocalRenderer;
private VideoRenderer.Callbacks mRemoteRenderer;
private GLSurfaceView mVideoView;
private SurfaceView mDrawView;
private SurfaceHolder mDrawHolder;
private ImageView mCursor;
private String mBgBytesString;
private ImageView mImgView;
private View mV;
public TabFragment() {
// Required empty public constructor
}
public void setApp(HomeActivity app) {
mApp = app;
}
public void setParams(String p1, String p2, String p3,
String p4) {
this.p1= p1;
this.p2= p2;
this.p4= p4;
this.p3= p3;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mV = inflater.inflate(R.layout.third_layout, container, false);
return mV;
}
#Override
public void onDetach() {
super.onDetach();
}
public void setupView() {
RequestUserPermission requestUserPermission = new RequestUserPermission(mApp);
requestUserPermission.verifyStoragePermissions();
mImgView = (ImageView) mV.findViewById(R.id.img_display); // NPE HERE
TextView mTest1= (TextView) mV.findViewById(R.id.test1);
mRequestLabelTextView.setText("test 1");
TextView mTest2= (TextView) mV.findViewById(R.id.test2);
mEquipmentSerialTextView.setText("test 2");
// View that displays the view from the camera
mVideoView = (GLSurfaceView) mV.findViewById(R.id.gl_surface);
// View that displays the cursor and drawing associated
mDrawView = (SurfaceView) mV.findViewById(R.id.draw_surface);
mDrawHolder = mDrawView.getHolder();
mDrawHolder.setFormat(PixelFormat.TRANSPARENT);
mDrawHolder.addCallback(this);
// Image of the cursor
mCursor = (ImageView) mV.findViewById(R.id.mouseCursor);
// Some more inits
}
public void startWork() {
//SOME WORK
}
}
So, the first instanciation is ok, but at the second, I got the NPE on getting the ImageView...
Someone can help me understanding this problem please ?
Thanks in advance !
Try using FragmentStatePagerAdapter not FragmentPagerAdapter it will solve many problems. Hope it will gonna work for you too.

Unable to get position of selected tab on viewpager

How many tabs will be created it depends on web service. It means I cannot discover how many Tabs are going to be Created until web service is called.
The tabs contain the products which I want to show in grid view.
In my project I have ShopProductsPageFragments.java where tabs get created. Please have look below code :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CatPosition = getArguments().getInt("CatPosition");
StoreID = getArguments().getString("StoreID");
System.out.println("getStoreID in ShopProductsPageFragments="+ StoreID);
System.out.println("getCatPosition in ShopProductsPageFragments="+ CatPosition);
try {
ShopCategoryData = (GetProductCategoriesByStoreResponsePojo) getArguments().getSerializable("ShopCatNames");
}catch (Exception e){
e.printStackTrace();
}
assert ShopCategoryData != null;
List<Datum> shopcatdata = ShopCategoryData.getData();
for (int i = 0; i < shopcatdata.size(); i++) {
System.out.println("ShopCategoryData in ShopProductsPageFragments "+ shopcatdata.get(i).getCatName());
}
ShopProductsPageView = inflater.inflate(R.layout.activity_product_page_fragment ,container ,false);
viewPager = (ViewPager)ShopProductsPageView.findViewById(R.id.product_viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout)ShopProductsPageView.findViewById(R.id.product_tabs);
tabLayout.setupWithViewPager(viewPager);
return ShopProductsPageView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
List<Datum> shopcatdata = ShopCategoryData.getData();
for (int i = 0; i < shopcatdata.size(); i++) {
CommanShopProductFragment commanShopProductFragment = CommanShopProductFragment.newInstance(i);
String CatName = shopcatdata.get(i).getCatName();
Bundle bundle = new Bundle();
bundle.putString("StoreID",StoreID);
bundle.putString("CatName",CatName);
commanShopProductFragment.setArguments(bundle);
System.out.println("ShopCategoryData in ShopProductsPageFragments "+ shopcatdata.get(i).getCatName());
adapter.addFrag(commanShopProductFragment, shopcatdata.get(i).getCatName());
}
adapter.notifyDataSetChanged();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(CatPosition);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
FragmentManager fragmentManager;
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
fragmentManager = manager;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Here, you can see how tabs are created. I am using same fragment for showing data in Tabs as follows:
public class CommanShopProductFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
View CategoryTabFragmentView;
GetStoreProductsByCategoriesPresenterImpl presenter;
RestClient service;
GridView gridView;
List<Datum> shopProduct;
ProductByCategoryGridViewAdapter mAdapter;
public CommanShopProductFragment() {
// Required empty public constructor
}
public static CommanShopProductFragment newInstance(int position) {
CommanShopProductFragment f = new CommanShopProductFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String CatName = getArguments().getString("CatName");
String StoreID = getArguments().getString("StoreID");
assert CatName != null;
System.out.println("CommanShopProductFragment >>>>>>>> CatName="+CatName);
assert StoreID != null;
System.out.println("CommanShopProductFragment >>>>>>>> StoreID="+StoreID);
CategoryTabFragmentView = inflater.inflate(R.layout.activity_category_tab_fragment ,container ,false);
service = ((LilubiApplication) getActivity().getApplication()).getNetworkService();
presenter = new GetStoreProductsByCategoriesPresenterImpl(this, service);
String page = "1", itemsPerPage = "10";
try {
presenter.GetStoreProductsByCategories(CatName, StoreID, page, itemsPerPage);
}catch (Exception e){
e.printStackTrace();
}
return CategoryTabFragmentView;
}
public void getStoreProductsByCategories(ProductByCategoriesResponsePojo productByCategoriesResponsePojo){
System.out.println("CategoryTabFragment in getMessage="+productByCategoriesResponsePojo.getMessage());
System.out.println("CategoryTabFragment in getStatus="+productByCategoriesResponsePojo.getStatus());
// prepared arraylist and passed it to the Adapter class
shopProduct = productByCategoriesResponsePojo.getData();
mAdapter = new ProductByCategoryGridViewAdapter(getActivity(),shopProduct);
// Set custom adapter to gridview
gridView = (GridView) CategoryTabFragmentView.findViewById(R.id.category_tab_view_grid_view);
gridView.setAdapter(mAdapter);
}
Now what I want is when user selects a tab then list of products should be displayed according to selected category from the tabs.
All product data also comes from web service. Let me know if I missed any thing to explain. Thank you.
I am editing my previous answer
Edit:
you can use viewpager.getCurrentItem() to get current position //include this in your activity with viewpager

How to add custom view in ViewPager for walkthrough

I've used ViewPagerIndicator to get WalkThrough like most popular application. But I can't understand how to add Pictures in ViewPager which shows how to use the application.
What I want is like these Walk Through.
What i got till now.
I dunno
How to add Custom View like ImageView and TextView in ViewPager?
Any guidance would be most welcome.
Since the question really old, I'll just write a short general guideline:
To populate viewpager with content, you add fragments to an adapter and then you set the adapter to the viewpager. You can do pretty much any layout in the fragment, putting there images/text etc..
As Inteist suggest, one can put any layout in fragment and supply that fragment to adapter.
Fragment:
public final class SelectModelFragment extends Fragment {
private static final String KEY_CONTENT = "SelectModelFragment:Content";
private static String TAG = SelectModelFragment.class.getSimpleName();
private SelectModel mSelectModelObj;
private CircularImageView mImageView;
public static SelectModelFragment newInstance(SelectModel obj) {
SelectModelFragment fragment = new SelectModelFragment();
fragment.mSelectModelObj =obj;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mSelectModelObj = savedInstanceState.getParcelable(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_select_model, container, false);
mImageView = (CircularImageView)view.findViewById(R.id.fragment_select_model_iv);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_CONTENT, mSelectModelObj);
}
}
Fragment Adapter :
public class SelectModelAdapter extends FragmentPagerAdapter {
ArrayList<SelectModel> mList;
private int mCount;
private static final String TAG = SelectModelAdapter.class.getSimpleName();
public SelectModelAdapter(FragmentManager fm, ArrayList<SelectModel> mList) {
super(fm);
this.mList = mList;
mCount = mList.size();
}
#Override
public Fragment getItem(int position) {
return SelectModelFragment.newInstance(mList.get(position));
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TAG;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
Activity: Where ViewPager has Fragment Adapter which feeds Fragment.
public class SelectModelActivity extends BaseSliderActivity {
private ViewPager mPager;
private SelectModelAdapter mAdapter;
private ArrayList<SelectModel> mList;
private void setAdapter() {
mAdapter = new SelectModelAdapter(getSupportFragmentManager(), mList);
mPager.setAdapter(mAdapter);
mIndicator.setViewPager(mPager);
}
}

listview item onclick into pageview in next activity

I have a listview containing item apple, banana, orange ...in second screen activity
when i click on particular item on apple it navigates to Details screen
here output has to appear like apple ..if i swipe page then banana and for nextswipe orage
apple-->banana-->orange
but am getting output like apple-->apple-->apple.
Intent detailIntent =new Intent(SecondScreen.this, Details.class);
startActivity(detailIntent);
public class MyApplication extends Application {
ArrayList<String> totalvalue = new ArrayList<String>();
}
public class Details extends FragmentActivity{
MyApplication app;
ViewPager pager;
MyFragmentPagerAdapter pagerAdapter;
public static int position ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.detail);
app = ((MyApplication) getApplicationContext());
pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
pagerAdapter = new MyFragmentPagerAdapter(fm,app.totalvalue);
pager.setAdapter(pagerAdapter);
}
public static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private static ArrayList<String> temperList;
public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<String> totalvalue ) {
super(fm);
this.temperList = totalvalue;
}
public Fragment getItem(int position) {
return ThingFragment.newInstance((temperList.get(position)));
}
#Override
public int getCount(){
return temperList.size();
}
private static class ThingFragment extends Fragment {
private String name1;
static ThingFragment newInstance(String string ) {
ThingFragment f = new ThingFragment();
Bundle args = new Bundle();
args.putString("name",temperList.get(position) );
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name1 = getArguments().getString("name");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
TextView t = (TextView)v.findViewById(R.id.prodcutt);
t.setText(""+ name1);
return v;
}
}
}
}
args.putString("name",temperList.get(position) ); shouldn't be possible inside your ThingFragment as its static.
That should be args.putString("name",string);
Also your temperList shouldn't be static in your adapter (no reason to, your passing it as a param) just make it final - private final ArrayList<String> temperList;
If that doesn't fix it please post more structured separated code so we can see how your application is built up a bit more. The adapter looks fine, so it maybe a case that your writing/overwriting the array at some point.

Categories

Resources