Android Fragments lose date - android

Hiho!
I use a ViewPager with fragmenst in my Android App. The fragments are working, but lose the displayed data. So at the firts call off my View Adapter, I can set data to the LinearLayout from fragments 1 and 2, the fragment 3 is not available. So I put data on fragment 1 and 2. When I now switch the fragmenst from one to three, the fragment on number one loses the data and get blank. How can I fix the data to display that it es displayed all of the time? If to create the information dynamicly and not in a xml file.
I hope you understand me and can help me.
public class PageAdapter extends FragmentStatePagerAdapter {
private int num_pages;
private String[] titles;
public PageAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int pos) {
PageFragment f = new PageFragment(pos);
return f;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return num_pages;
}
#Override
public CharSequence getPageTitle(int position){
return titles[position];
}
public void set_num_pages(int num){
num_pages=num;
}
public void set_titles(String[] a_titles){
titles=a_titles;
}
}
Next class:
public class PageFragment extends Fragment {
private int fragmentNR;
public PageFragment(){}
public PageFragment(int nr) {
this.fragmentNR = nr;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = new View(getActivity());
if (fragmentNR == 0)
v = inflater.inflate(R.layout.info_1, container, false);
else if (fragmentNR == 1)
v = inflater.inflate(R.layout.info_2, container, false);
else if (fragmentNR == 2)
v = inflater.inflate(R.layout.info_3, container, false);
return v;
}
}
Next class:
public class MannschaftInfos extends FragmentActivity {
private String mannschaftInfos;
private int mannschaftID;
private int anzahl;
private String[] titel = new String[3];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the callback listener, to receive a message when an ad was loaded
mannschaftID = getIntent().getExtras().getInt("id");
titel[0]=(String) this.getText(R.string.Info);
titel[1]=(String) this.getText(R.string.aufstellung);
titel[2]=(String) this.getText(R.string.miStatistik);
anzahl=3;
new AbrufMannschaftInfo(this).laden(mannschaftID);
AbrufMannschaftInfo.setMannschaftListesListener(new Datenlistener());
}
private class Datenlistener implements MannschaftInfosListener {
public void mannschaftInfosListenerrueck(String rueck) {
setContentView(R.layout.info_mannschaft);
PageAdapter mPageAdapter = new PageAdapter(getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
mPageAdapter.set_num_pages(anzahl);
mPageAdapter.set_titles(titel);
mViewPager.setAdapter(mPageAdapter);
mannschaftInfos=rueck;
LinearLayout llf1 = (LinearLayout) findViewById(R.id.ll_fragment1);
llf1.removeAllViews();
llf1.setPadding(5, 5, 5, 5);
llf1.setOrientation(LinearLayout.VERTICAL);
LinearLayout llf2 = (LinearLayout) findViewById(R.id.ll_fragment2);
llf2.removeAllViews();
llf2.setPadding(5, 5, 5, 5);
llf2.setOrientation(LinearLayout.VERTICAL);
LinearLayout llf3 = (LinearLayout) findViewById(R.id.ll_fragment3);
llf3.removeAllViews();
llf3.setPadding(5, 5, 5, 5);
llf3.setOrientation(LinearLayout.VERTICAL);
View ruler_1 = new View(MannschaftInfos.this); ruler_1.setBackgroundColor(Color.parseColor("#FFFFFF"));
View ruler_2 = new View(MannschaftInfos.this); ruler_2.setBackgroundColor(Color.parseColor("#FFFFFF"));
View ruler_3 = new View(MannschaftInfos.this); ruler_3.setBackgroundColor(Color.parseColor("#FFFFFF"));
View ruler_4 = new View(MannschaftInfos.this); ruler_4.setBackgroundColor(Color.parseColor("#FFFFFF"));
MannschaftInfosAufbereiten mInfos = new MannschaftInfosAufbereiten(mannschaftInfos);
mInfos.show_wappen(llf1, MannschaftInfos.this);
llf1.addView(ruler_1,new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, 3));
mInfos.show_stadion(llf1, MannschaftInfos.this);
llf1.addView(ruler_2,new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, 3));
mInfos.show_ligen(llf1, MannschaftInfos.this);
mInfos.show_stat(llf2, MannschaftInfos.this);
}
}
}

Related

Two fragment using same adapter in TabLayout not working

Only the first fragment is populated with the image, the second fragment is blank. I am using the same adapter for both fragments. I am not sure where is the problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mSectionsPagerAdapter.addFragment(PopularMoviesFragment.newInstance(SORT_POPULAR), "MOST POPULAR");
mSectionsPagerAdapter.addFragment(RatingMoviesFragment.newInstance(SORT_RATING), "TOP RATING");
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public void switchToDetail(Intent intent){
startActivity(intent);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
static class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
First fragment
public static PopularMoviesFragment newInstance(String sort) {
PopularMoviesFragment fragment = new PopularMoviesFragment();
Bundle args = new Bundle();
args.putString("sort", sort);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sortOrder = getArguments().getString("sort");
mContext = getActivity();
if (savedInstanceState != null) {
mPopularList = savedInstanceState.getParcelableArrayList(POPULAR_LIST);
for (Movie m : mPopularList) {
Log.d(LOG_TAG, "onCreate: " + m.getTitle());
}
} else {
FetchPopularMovies pm = new FetchPopularMovies();
pm.execute(SORT_POPULAR);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View pView = inflater.inflate(R.layout.fragment_popular_movies, container, false);
mAdapter = new MoviePosterAdapter(mContext, mPopularList);
mProgressBar = (ProgressBar) pView.findViewById(R.id.movies_progress_bar);
RecyclerView mRecyclerView = (RecyclerView) pView.findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return pView;
}
Second fragment
public static RatingMoviesFragment newInstance(String sort) {
RatingMoviesFragment fragment = new RatingMoviesFragment();
Bundle args = new Bundle();
args.putString("sort", sort);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sortOrder = getArguments().getString("sort");
mContext = getActivity();
if (savedInstanceState != null) {
Log.d(LOG_TAG, "Has saved instance");
mRatingList = savedInstanceState.getParcelableArrayList(RATING_LIST);
} else {
FetchRatingMovies rm = new FetchRatingMovies();
rm.execute(SORT_RATING);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_rating_movies, container, false);
ratingAdapter = new MoviePosterAdapter(mContext, mRatingList);
mProgressBar = (ProgressBar) view.findViewById(R.id.movies_progress_bar);
RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(ratingAdapter);
return view;
}
MoviePosterAdapter
public class MoviePosterAdapter extends RecyclerView.Adapter<MoviePosterAdapter.ViewHolder> {
private final String LOG_TAG = MoviePosterAdapter.class.getSimpleName();
final Context mContext;
private ArrayList<Movie> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
//public final View mView;
public final ImageView mImageView;
public ViewHolder(View view) {
super(view);
mImageView = (ImageView) view.findViewById(R.id.imageView);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MoviePosterAdapter(Context context, ArrayList<Movie> myDataset) {
this.mContext = context;
mDataset = myDataset;
}
public void setMoviesData(ArrayList<Movie> moviesData){
mDataset = moviesData;
}
// Create new views (invoked by the layout manager)
#Override
public MoviePosterAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(mContext).inflate(R.layout.movie_poster, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Movie mMovie = mDataset.get(position);
//Creating URL for image
final String POSTER_BASE_URL = "http://image.tmdb.org/t/p/";
final String SIZE_PATH = "w185";
String IMG_PATH = mMovie.getImg();
//Loading image using Glide
Glide.with(holder.mImageView.getContext())
.load(POSTER_BASE_URL + SIZE_PATH + IMG_PATH)
.placeholder(R.color.grid_placeholder_bg)
.into(holder.mImageView);
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext, DetailActivity.class);
i.putExtra("id", mMovie.getId());
i.putExtra("title", mMovie.getTitle());
if (mContext instanceof MainActivity) {
MainActivity main= (MainActivity) mContext;
main.switchToDetail(i);
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
Please help me!
EDIT: Both the arrays are not empty. Here is the issue I think, only one fragment gets populated, maybe because there is some problem with the adapter(not sure). If I try to stop first fragment to get populated(commenting out the notifyDatasetChanged()), then the second fragment works fine.
The image wasn't populating in the second fragment because it was an issue with Glide library. Switched to Picasso. Works fine.
I checked your code and i found that everything is fine. I tried with dummy data so i am damn sure that the mistake is in your data or adapter where you are setting data. Just try once with dummy data so you will be more clear or if still you are getting blank screen then let me know.
Generally blank screen comes because of there is no data. so please check once..

swipe tabs inside a fragment with pages from same class

I created a swipe tab view inside a fragment. I tested this in a FragmentActivity with no issues. I tested with pages that consisted of different fragment classes and fragments all from the same class... again no issues.
Then, I changed the FragmentActivity to a Fragment. I tested again with different Fragment classes representing each page and had no problem. Finally, i repeated the test with fragments of the same class and ran into issues.
There are 3 pages right now representing three weeks. At first week 1 shows up. I swipe to week 2 and there is nothing. I swipe to week 3 and nothing again. When I swipe back to week 1, the only viewable page ends up being the middle page. Is this an issue with fragment life cycles? I'm not sure how to debug this special circumstance. I'm looking for possible causes so I can start solving this issue.
public class WeeklyScrollTab extends Fragment {
private ViewPager my_view_pager;
private View my_layout;
private int my_current_page;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
my_layout = inflater.inflate(R.layout.weekly_scroll_tabs, container, false);
return my_layout;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
//Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
//my_current_page = data.getInt("week_val", 0);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
my_view_pager = (ViewPager)my_layout.findViewById(R.id.week_list_pager);
FragmentManager manager = getActivity().getSupportFragmentManager();
//FragmentManager manager = getChildFragmentManager();
my_view_pager.setAdapter(new WeeklyScrollAdapter(manager));
super.onActivityCreated(savedInstanceState);
}
public int getCurrentPage(){
return my_current_page;
}
public class WeeklyScrollAdapter extends FragmentStatePagerAdapter {
public WeeklyScrollAdapter(FragmentManager the_manager){
super(the_manager);
}
#Override
public Fragment getItem(int the_position) {
Fragment fragment1 = null;
if(the_position == 0){
fragment1 = new MyNflPlayerList();
Bundle args1 = new Bundle();
args1.putInt("week_val"+the_position, the_position);
fragment1.setArguments(args1);
}
if(the_position == 1){
fragment1 = new MyNflPlayerList();
Bundle args2 = new Bundle();
args2.putInt("week_val"+the_position, the_position);
fragment1.setArguments(args2);
}
if(the_position == 2){
fragment1 = new MyNflPlayerList();
Bundle args3 = new Bundle();
args3.putInt("week_val"+the_position, the_position);
fragment1.setArguments(args3);
}
return fragment1;
}
/**
*
* #return number of total pages
*/
#Override
public int getCount() {
return 3;
}
/**
* gets title for tab
*/
#Override
public CharSequence getPageTitle(int position) {
if(position ==0){
return "Week 1";
}
if(position == 1){
return "Week 2";
}
if(position == 2){
return "Week 3";
}
return super.getPageTitle(position);
}
public class NflPlayerAdapter extends BaseAdapter {
private ArrayList<NflPlayerModel> my_list;
private Context my_context;
public NflPlayerAdapter(Context c){
my_context = c;
my_list = new ArrayList<NflPlayerModel>();
my_list.add(new NflPlayerModel("T.","Brady","NE","QB",56));
my_list.add(new NflPlayerModel("A.","Peterson","MN","RB",24));
my_list.add(new NflPlayerModel("D.","Bryant","DAL","WR",18));
my_list.add(new NflPlayerModel("M.","Gattica","TB","K",9));
}
#Override
public int getCount() {
return my_list.size();
}
#Override
public NflPlayerModel getItem(int i) {
return my_list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting the data and injecting it into the each row view
View row = convertView;
NflPlayerHolder holder = null;
if(row == null){
LayoutInflater inflater = (LayoutInflater)my_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.my_nfl_player_row,parent, false);
holder = new NflPlayerHolder(row);
row.setTag(holder);
}
else{
holder = (NflPlayerHolder) row.getTag();
}
NflPlayerModel temp = my_list.get(position);
holder.getFname().setText(temp.getFname());
holder.getLname().setText(temp.getLname());
holder.getTeam().setText(temp.getTeam());
holder.getPosition().setText(temp.getPosition());
holder.getPoints().setText(Integer.toString(temp.getPoints()));
return row;
}
class NflPlayerHolder {
/**
* TextView object in my_league_row xml.
*/
private TextView my_fname;
private TextView my_lname;
private TextView my_team;
private TextView my_position;
private TextView my_points;
/**
* Constructor. Converts the xml txt_league_name to Java object.
* #param v
*/
public NflPlayerHolder(View v){
my_fname = (TextView)v.findViewById(R.id.player_fname);
my_lname = (TextView)v.findViewById(R.id.player_lname);
my_team = (TextView)v.findViewById(R.id.player_team);
my_position = (TextView)v.findViewById(R.id.player_position);
my_points = (TextView)v.findViewById(R.id.player_points);
}
public TextView getFname(){
return my_fname;
}
public TextView getLname(){
return my_lname;
}
public TextView getTeam(){
return my_team;
}
public TextView getPosition(){
return my_position;
}
public TextView getPoints(){
return my_points;
}
public class MyNflPlayerList extends Fragment implements AdapterView.OnItemClickListener{
private View my_layout;
private ListView my_list_view;
private static HomeActivityCommunicator my_communicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
my_layout = inflater.inflate(R.layout.my_nfl_player_list, container, false);
return my_layout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
my_list_view = (ListView)getActivity().findViewById(R.id.nfl_player_list_view);
NflPlayerAdapter adapter = new NflPlayerAdapter(getActivity());
my_list_view.setAdapter(adapter);
my_list_view.setOnItemClickListener(this);
super.onActivityCreated(savedInstanceState);
}
public void setHomeActivityCommunicator(HomeActivityCommunicator the_communicator){
my_communicator = the_communicator;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("mike", "the player index is " + i);
my_communicator.onMyNflPlayerListSelection(i);
}

How to edit a fragment and save its state?

I have to add TextViews and EditTexts in a Fragment ( Details() ) when i click in a button ( Button add ).
I was able to insert them, but when i swipe my 6 fragments and return in the first fragment this items disappear.
Can someone help me?
FragmentActivity class:
public class SubActivityTab extends FragmentActivity
{
SectionsPagerAdapter spa;
ViewPager vp;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scrolltab_layout);
spa = new SectionsPagerAdapter(getSupportFragmentManager(), this);
vp = (ViewPager) findViewById(R.id.pager);
vp.setAdapter(spa);
}
}
FragmentPagerAdapter class:
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
Context c;
public SectionsPagerAdapter(FragmentManager fm, Context c) {
super(fm);
this.c = c;
}
#Override
public Fragment getItem(int position) {
switch(position)
{
case 0:
return Details.newInstance();
...
}
return null;
}
#Override
public int getCount() {
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position)
{
case 0:
return c.getString(R.string.tab1).toUpperCase(l);
...
}
return null;
}
}
Fragment class:
public final class Details extends Fragment {
public static View layout;
public static LinearLayout ll;
public static Details newInstance()
{
return new Details();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
layout = inflater.inflate(R.layout.details, container, false);
ll = (LinearLayout) layout.findViewById(R.id.linearlayout2);
Button add = (Button) layout.findViewById(R.id.button_add);
add.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
insertLine();
insertClassEditText();
insertLevel();
}});
return layout;
}
private void insertLine()
{
View temp = (View) layout.findViewById(R.id.line);
View v = new View(temp.getContext());
v.setBackgroundColor(Color.rgb(209, 209, 209));
v.setId(0);
v.setLayoutParams(temp.getLayoutParams());
ll.addView(v);
}
private void insertClassEditText()
{
TextView label_classe = (TextView) layout.findViewById(R.id.textView10);
EditText edit_classe = (EditText) layout.findViewById(R.id.editText9);
TextView new_label_classe = new TextView(label_classe.getContext());
EditText new_edit_classe = new EditText(edit_classe.getContext());
new_label_classe.setId(1);
new_edit_classe.setId(2);
new_label_classe.setText("Label");
new_label_classe.setTextAppearance(new_label_classe.getContext(), android.R.style.TextAppearance_Medium);
ll.addView(new_label_classe);
new_edit_classe.setInputType(edit_classe.getInputType());
new_edit_classe.setLayoutParams(edit_classe.getLayoutParams());
ll.addView(new_edit_classe);
}
private void insertLevel()
{
TextView label_lv = (TextView) layout.findViewById(R.id.textView11);
EditText edit_lv = (EditText) layout.findViewById(R.id.editText10);
TextView new_label_lv = new TextView(label_lv.getContext());
EditText new_edit_lv = new EditText(edit_lv.getContext());
new_label_lv.setId(3);
new_edit_lv.setId(4);
new_label_lv.setText(label_lv.getText());
new_label_lv.setTextAppearance(new_label_lv.getContext(), android.R.style.TextAppearance_Medium);
ll.addView(new_label_lv);
new_edit_lv.setInputType(edit_lv.getInputType());
new_edit_lv.setLayoutParams(edit_lv.getLayoutParams());
ll.addView(new_edit_lv);
}
}
I believe ViewPager recycles the views as you swipe and therefore when you go back, it rebuilds from onCreateView.
I would suggest setting some tags and passing to onSaveInstanceState.
private void onSaveInstanceState(Bundle b) {
if (label_classe != null) {
b.putBoolean("label_classe", true);
}
}
Then in onCreateView you take savedInstanceState, check what elements were created and re-create them.
So in Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
....
if (savedInstanceState.getBoolean("label_classe")) {
insertClassEditText();
}
....
}
And just to be sure, in Activity:
public class SubActivityTab extends FragmentActivity
{
SectionsPagerAdapter spa;
ViewPager vp;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scrolltab_layout);
spa = new SectionsPagerAdapter(getSupportFragmentManager(), this);
vp = (ViewPager) findViewById(R.id.pager);
vp.setSaveState(true);
vp.setSaveFromParentEnabled(true);
vp.setAdapter(spa);
}
}
Try to change your onCreateView method to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
if(layout ==null){
layout = inflater.inflate(R.layout.details, container, false); //Dont inflate every time.layout saved, data of layout,like EidtText also saved.
}
ViewParent parent = mLayout.getParent();
if(parent!=null){
((ViewGroup)parent).removeView(layout);//the view will be add to NoSaveStateFrameLayout after onCreateView,so remove self everytime
}
return layout;
}

Fragment member variables getting null when accessed in onPageSelected()

I'm using FragmentPagerAdapter with FragmentActivity to create swipe-able Fragments.
My first fragment in that pagerAdapter look like this.
public class MySummaryFragment extends CommonFragment implements OnPageChangeListener
{
private Context mContext;
private View mMyView;
LinearLayout mDetailLayout;
TextView mDateTxtView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("onCreateView() Market summary");
mMyView = inflater.inflate(R.layout.my_page_summary_fragment_layout, container,false);
mDetailLayout = (LinearLayout)mMyView.findViewById(R.id.SummaryDetailLayout);
mDateTxtView = (TextView) mMyView.findViewById(R.id.txtDate);
Account_Id = AccountDetails.getInstance(mContext).getClientCodes().get(0);
sendRequest(Account_Id);
return mMyView;
}
#Override
public void onPageSelected(int arg0) {
System.out.println("inside onPageScrollStateChanged()");
System.out.println("mMyView is null ? = "+(mMyView==null));
mDateTxtView = (TextView) mMyView.findViewById(R.id.txtMarketSummaryDate);
Account_Id = AccountDetails.getInstance(mContext).getClientCodes().get(0);
mDateTxtView.setText("");
sendRequest(Account_Id);
}
}
The problem here is I'm getting NullPointerException when swipe-out to 5-6 fragments and swiping back to first fragment.
When I try to debug, I found that
mMyView is null ? = true
Why so?
Please help me.
Here is my Fragment contains the FragmentPagerAdapter,
public class MyPageDetailViewFragment extends CommonFragment {
private View mView;
Context mContext;
OnPageChangeListener pageChangeListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.my_page_fragments, null);
mContext = getActivity();
setHasOptionsMenu(false);
setupSearchBarComponent();
PagerTabStrip pagerTabStrip = (PagerTabStrip)mView. findViewById(R.id.pager_title_strip);
pagerTabStrip.setDrawFullUnderline(true);
pagerTabStrip.setTabIndicatorColor(Color.BLACK);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) mView.findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = ((HomeScreenActivity)mContext).getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
final MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(0);
pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageSelected(int selectedIndex) {
System.out.println("selectedIndex = "+selectedIndex);
Object page = pagerAdapter.getItem(selectedIndex);
if( page instanceof OnPageChangeListener){
((OnPageChangeListener) page).onPageSelected(selectedIndex);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
pager.setOnPageChangeListener(pageChangeListener);
return mView;
// return super.onCreateView(inflater, container, savedInstanceState);
}
And here is my implementation MyFragmentPagerAdapter,
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int index) {
System.out.println("getItem = "+index);
Bundle data = new Bundle();
data.putInt("current_page", index + 1);
CommonFragment fragment = getFragment(index);
fragment.setArguments(data);
return fragment;
}
public CommonFragment getFragment(int index) {
CommonFragment fragment = null;
if(fragment == null){
if(index == 0){
fragment = new MySummaryFragment();
}else if(index == 1){
fragment = new FragmentOne();
}else if(index == 4){
fragment = new FragmentFour();
}else if(index == 5){
fragment = new FragmentFive();
}else{
fragment = new MyFragment();
}
}
return fragment;
}
/** Returns the number of pages */
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
pagerAdapter.getItem(selectedIndex) actually creates a new instance of the fragment.
See this answer: https://stackoverflow.com/a/23843743/1271907
You have to keep a reference to the actual fragment.
It looks like you are calling the wrong method on the inflater.
Try to change this line:
mView = inflater.inflate(R.layout.my_page_fragments, null);
to:
mView = inflater.inflate(R.layout.my_page_fragments,container, null);

How to make Vertical View pager in fragment?

I want to make a vertically side view pager in my fragment
i tried Like this, but i don't know to how to pass view back to women class form TestFragment class
This is my main class
public class women extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstance)
{
startActivity(new Intent(getActivity(), women_activity.class));
return null;
}
public class women_activity extends FragmentActivity{
View view;
#SuppressLint("ShowToast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frgment_1);
//Set up the pager
DirectionalViewPager pager = (DirectionalViewPager)findViewById(R.id.pager);
pager.setAdapter(new TestFragmentAdapter(getSupportFragmentManager()));
pager.setOrientation(DirectionalViewPager.VERTICAL);
}
}
TestFragmentAdapter class
public class TestFragmentAdapter extends FragmentPagerAdapter {
protected static final String[] CONTENT = new String[] { "This", "Is Is", "A A A", "Test", };
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return CONTENT.length;
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
return TestFragment.newInstance(CONTENT[position]);
}
}
TestFragment Class
public class TestFragment extends Fragment{
View mView,layout ;
ViewPager mViewPager;
private String mContent="????";
private static final String KEY_CONTENT = "TestFragment:Content";
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
//mView = inflater.inflate(R.layout.frgment_1, container,false);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mContent = savedInstanceState.getString(KEY_CONTENT);
}
TextView text = new TextView(getActivity());
text.setText(mContent);
text.setTextSize(20 * getResources().getDisplayMetrics().density);
text.setPadding(20, 20, 20, 20);
text.setGravity(Gravity.CENTER);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
layout.setGravity(Gravity.CENTER);
layout.addView(text);
return layout;
}
public static TestFragment newInstance(String content) {
TestFragment fragment = new TestFragment();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 30; i++) {
builder.append(content).append(" ");
}
builder.deleteCharAt(builder.length() - 1);
fragment.mContent = builder.toString();
return fragment;
}

Categories

Resources