give initial data to fragments (with page adapter) - android

I have a problem,I want to send one argument extraData from my activityVenteActivity to one of his fragmentPageAdjuFragment at the creation of the activity.
I have 3 fragments on this activity for slide between them, for the moment I work only on PageAdjuFragment.
I see on stackoverflow how to use newinstantiate() for passing a bundle in argument for a new instance of PageAdjuFragment but that don't work for me :(.
You can see here my activity:
public class VenteActivity extends FragmentActivity {
private PagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.viewpager2);
creationPage();
//Recovery
Intent sender=getIntent();
String extraData=sender.getExtras().getString("message");
Log.v("nivyolo",extraData);//this is the argument which i would send
//Sending
PageAdjuFragment.newInstance(extraData); // the problem start here
}
public void creationPage() {
// Creation of the list
List<Fragment> fragments = new Vector<Fragment>();
// Add Fragments in a list
fragments.add(Fragment.instantiate(this,PageOffreFragment.class.getName()));
fragments.add(Fragment.instantiate(this,PageAdjuFragment.class.getName()));
fragments.add(Fragment.instantiate(this,PageNewPartFragment.class.getName()));
// Creation of theadapter
this.mPagerAdapter = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager2);
// Affectation on the ViewPager
pager.setAdapter(this.mPagerAdapter);
}
}
My fragment that I want to pass an argument to the creation
public class PageAdjuFragment extends Fragment {
public static PageAdjuFragment newInstance(String vente) {
PageAdjuFragment myFragment = new PageAdjuFragment();
Bundle args = new Bundle();
args.putString("vente", vente);
myFragment.setArguments(args);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
final View v=inflater.inflate(R.layout.page_adju_layout, container, false);
final Button b=(Button)v.findViewById(R.id.btconf);
final RadioGroup radiopmt = (RadioGroup) v.findViewById(R.id.radiopmt);
final RadioButton rb1 = (RadioButton)v.findViewById(R.id.rb1);
final RadioButton rb2 = (RadioButton)v.findViewById(R.id.rb2);
final AutoCompleteTextView tv1 = (AutoCompleteTextView)v.findViewById(R.id.actv1);
final AutoCompleteTextView tv2 = (AutoCompleteTextView)v.findViewById(R.id.actv2);
final EditText tv3 = (EditText)v.findViewById(R.id.edt);
////START PROBLEM////////
String vente;
// Recovery of the parameter
Log.v("adju","before recup");
Bundle arg = getArguments(); // the problem
Log.v("adju","after recup");
if (arg == null) {// all the time arg is null
Log.v("args","arguments is null ");
vente = "yolo";
} else {
Log.v("args2","arguments not null ");
vente= arg.getString("vente");
Log.v("nivyolobonnepage",vente);
}
tv3.setText(vente); //just a test
////END PROBLEM////////
//Data adaptation on TextAuto
List<String> OBJET = null;
List<String> PARTI = null;
try {
OBJET = InitObjet();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
PARTI = InitPart();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, OBJET);
tv1.setAdapter(adapter);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, PARTI);
tv2.setAdapter(adapter2);
Log.v("papaouté","ici"); //Listerner Boutton Confirmer
b.setOnClickListener(new OnClickListener() {...});
//Listener on the widget value's changes
tv1.addTextChangedListener(new TextWatcher() {...});
tv2.addTextChangedListener(new TextWatcher() {...});
tv3.addTextChangedListener(new TextWatcher() {...});
radiopmt.setOnCheckedChangeListener(new OnCheckedChangeListener() {...});
return v;
}
//Create the List of object
public List<String> InitObjet() throws IOException{...}
//Create the List of participant
public List<String> InitPart() throws IOException {...}
//Write in the CSV FILE "achat"
public void ecrire() throws IOException{...}
}
And finally the Page Adapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragments;
//On fournit à l'adapter la liste des fragments à afficher
public MyPagerAdapter(FragmentManager fm, List fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int pos) {
return this.fragments.get(pos);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
and the wiewpager2.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/viewpager2">
</android.support.v4.view.ViewPager>
the logCat
05-14 10:13:51.919: V/nivyolo(10005): vente1
05-14 10:13:52.169: V/adju(10005): before recup
05-14 10:13:52.169: V/adju(10005): after recup
05-14 10:13:52.169: V/args(10005): arguments is null
05-14 10:13:52.209: V/papaouté(10005): ici
The argument arg is always null

PageAdjuFragment.newInstance(extraData); // the problem start here
Yes there is your problem, because you're instantiating a Fragment and are not using it.
public class VenteActivity extends FragmentActivity {
private PagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.viewpager2);
creationPage();
}
public void creationPage() {
// Creation of the list
List<Fragment> fragments = new Vector<Fragment>();
// Add Fragments in a list
fragments.add(Fragment.instantiate(this,PageOffreFragment.class.getName()));
//Recovery
Intent sender=getIntent();
String extraData=sender.getExtras().getString("message");
Log.v("nivyolo",extraData);//this is the argument which i would send
//Sending
Fragment frag = PageAdjuFragment.newInstance(extraData); // no problem anymore
fragments.add(frag);
fragments.add(Fragment.instantiate(this,PageNewPartFragment.class.getName()));
// Creation of theadapter
this.mPagerAdapter = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager2);
// Affectation on the ViewPager
pager.setAdapter(this.mPagerAdapter);
}
}
That's it. :-)
And why are you using Fragment.instantiate()? It's the same as using new Fragment(), but adds performance loss by using Java Reflection (approx. 2 times longer than using plain constructor). Better use the empty constructor or Fragment.newInstance(), if you defined that static method.

Related

Same fragment called multiple time in ViewPager

I have a View pager. The user can choose how many differents pages he can have.
The pages are all the same layout but it will just load different data.
Here is my fragment adapter :
public class FragmentAdapter extends FragmentPagerAdapter
{
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return lstFragment.get(i);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
#Override
public int getCount() {
return lstTitles.size();
}
public void AddFragment (Fragment fragment , String title)
{
lstFragment.add(fragment);
lstTitles.add(title);
}
}
And here is the code to call the fragment multiple time :
FragAdapter = new FragmentAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.main_tabs_pager);
toolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
tabLayout = (TabLayout) findViewById(R.id.main_tabs);
String[] Fragments = {"Frag1", "Frag2", "Frag3", "Frag4"};
for (int i=0; i<Fragments.length; i++)
{
((FragmentAdapter) FragAdapter).AddFragment(new MenuFragment(),Fragments[i]);
}
viewPager.setAdapter(FragAdapter);
tabLayout = (TabLayout) findViewById(R.id.main_tabs);
tabLayout.setupWithViewPager(viewPager);
So it works fine. But the only problem is that I don't know how to know the difference in code between the differents fragments.
Exemple :
The frag1 must load 5 pictures about the sea
The frag2 must load 8 pictures about the sun
How can I tell the fragment what to do? I tried to pass in the constructeur the arguments by exemple
public MenuFragment(int numberofpictures, String picturesthemes)
{
// Required empty public constructor
}
but the constructors must be empty because it is not called again when fragment is destroyed and recreated...
does anyone has an idea? thanks
UPDATE
I don't know if that is the good way but here is the way I did it :
In main activity I created :
for (int i=0; i<Fragments.length; i++)
{
Bundle parameters = new Bundle();
parameters.putInt("myInt", i);
Fragment menuFragment = new MenuFragment();
menuFragment.setArguments(parameters);
((FragmentAdapter) FragAdapter).AddFragment(menuFragment, Fragments[i]);
}
Which give a everyfragment the the int i which is a reference to the title.
Then I simply wrote this function :
public String getName (int i)
{
return Fragments[i];
}
which return the title based on the int that the fragment got thanks to the bundle
Then, In the MenuFragment() I used this :
private void fillinthelist()
{
myInt = getArguments().getInt("myInt");
String test = ((MainActivity) getActivity()).getName(myInt);
ListOfProgrammes.add(new Modele_carte(test));
}
so it gets the int from the bundle and make a like to it thanks to the function in MainActivity
Is it the good way to do it? It seems to work
You can attach a Bundle containing the parameters with setArguments(Bundle) :
Bundle parameters = new Bundle();
parameters.putInt("myInt", <int_value>);
Fragment menuFragment = new MenuFragment();
menuFragment.setArguments(arguments);
((FragmentAdapter) FragAdapter).AddFragment(menuFragment, Fragments[i]);
A common practice is to build and attach the Bundle in a fragment's class static factory method.
The fragment can use getArguments() to retrieve the parameters.
private int myInt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myInt = getArguments().getInt("myInt");
}

Unable to design viewpager in the layout with dynamic data

I'm new in android and want an app with viewpager. I am unable to design the viewpager in the layout. The layout fetch the data dynamatically. I want to create a matreial UI viewpager which swipes the page left or right like a paper.I have made a view which shows the data but is unable to swipe like a viewpager left or right...
The code is as below:
public class DetailNewsActivity extends AppCompatActivity {
private PullToZoomScrollViewEx scrollView;
private ArrayList<NewsItemModel> newsArr;
private TextView tvNewsTitle;
private TextView tvNewsPublishDate;
private TextView tvNewsFull;
private int newsPosition = 0;
private ImageView ivYoutubeEnable;
private SharedPreferences sharedPref;
int textSize = 16;
boolean isHighQuality = false;
private Typeface typeface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_news);
init();
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("5745FD6726ACCBEE8324DB158D021FA5")
.build();
mAdView.loadAd(adRequest);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_detail_news, container, false);
return view;
}
private void init() {
typeface = Typeface.createFromAsset(getAssets(), "AnmolUni.ttf");
// newsArr = (ArrayList<NewsItemModel>) getIntent().getSerializableExtra("newsArray");
newsArr = AppController.getAppController().getMainNewsArr();
AppController.getAppController().setMainNewsArr(null);
newsPosition = getIntent().getIntExtra("newsPosition", 0);
findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
findViewById(R.id.iv_share).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generateBranchURL(newsPosition);
}
});
sharedPref = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
textSize = sharedPref.getInt("text_size", 16);
isHighQuality = sharedPref.getBoolean("isHighQuality",false);
loadViewForCode();
scrollView = (PullToZoomScrollViewEx) findViewById(R.id.scroll_view);
setNewsFromArray(newsPosition);
// ((ImageView) scrollView.getZoomView().findViewById(R.id.iv_zoom)).setImageResource(android.R.drawable.arrow_down_float);
(scrollView.getZoomView().findViewById(R.id.iv_zoom)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DetailNewsActivity.this, ImageVideoActivity.class);
intent.putExtra("viewType", "image");
if(isHighQuality)
intent.putExtra("imageArr", newsArr.get(newsPosition).getImage());
else
intent.putExtra("imageArr", newsArr.get(newsPosition).getMedium());
startActivity(intent);
}
});
DisplayMetrics localDisplayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
int mScreenHeight = localDisplayMetrics.heightPixels;
int mScreenWidth = localDisplayMetrics.widthPixels;
LinearLayout.LayoutParams localObject = new LinearLayout.LayoutParams(mScreenWidth, (int) (9.0F * (mScreenWidth / 16.0F)));
scrollView.setHeaderLayoutParams(localObject);
scrollView.setParallax(true);
// scrollView.getPullRootView().findViewById(R.id.container_layout).setOnTouchListener(new OnSwipeTouchListener(DetailNewsActivity.this) {
scrollView.getPullRootView().setOnTouchListener(new OnSwipeTouchListener(DetailNewsActivity.this) {
#Override
public void onSwipeLeft() {
if (newsPosition < newsArr.size() - 1) {
newsPosition++;
setNewsFromArray(newsPosition);
} else {
CommonUtils.showToast(DetailNewsActivity.this, "No more news");
}
}
#Override
public void onSwipeRight() {
if (newsPosition > 0) {
newsPosition--;
setNewsFromArray(newsPosition);
} else {
CommonUtils.showToast(DetailNewsActivity.this, "This is the first news");
}
}
});
scrollView.setOnPullZoomListener(new PullToZoomBase.OnPullZoomListener() {
#Override
public void onPullZooming(int newScrollValue) {
Log.d("MainActivity", "onPullZooming: " + newScrollValue);
// Intent intent = new Intent(DetailNewsActivity.this, ImageVideoActivity.class);
// intent.putExtra("viewType", "image");
// intent.putExtra("imageArr", newsArr.get(newsPosition).getImage());
// startActivity(intent);
}
#Override
public void onPullZoomEnd() {
}
});
}
void setNewsFromArray(int position) {
if (position >= newsArr.size()) {
finish();
return;
}
if (!newsArr.get(position).getMedium().get(0).isEmpty()) {
if(isHighQuality)
Picasso.with(DetailNewsActivity.this).load(newsArr.get(position).getImage().get(0)).placeholder(R.drawable.logo).error(R.drawable.logo).
into((ImageView) scrollView.getZoomView().findViewById(R.id.iv_zoom));
else
Picasso.with(DetailNewsActivity.this).load(newsArr.get(position).getMedium().get(0)).placeholder(R.drawable.logo).error(R.drawable.logo).
into((ImageView) scrollView.getZoomView().findViewById(R.id.iv_zoom));
} else {
((ImageView) scrollView.getZoomView().findViewById(R.id.iv_zoom)).setImageResource(R.drawable.logo);
}
tvNewsTitle.setText(newsArr.get(position).getTitle());
tvNewsPublishDate.setText(newsArr.get(position).getPublish_dt());
//String style = "<html><body style='text-align:justify'>";
//Log.i("RAJEEV",style + newsArr.get(position).getFullnews());
tvNewsFull.setText(Html.fromHtml( newsArr.get(position).getFullnews()));
if (newsArr.get(position).getYoutube_video().isEmpty()) {
ivYoutubeEnable.setVisibility(View.GONE);
} else {
ivYoutubeEnable.setVisibility(View.VISIBLE);
}
ivYoutubeEnable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DetailNewsActivity.this, ImageVideoActivity.class);
intent.putExtra("viewType", "youtube");
intent.putExtra("youtube_code", newsArr.get(newsPosition).getYoutube_video());
startActivity(intent);
}
});
}
private void loadViewForCode() {
PullToZoomScrollViewEx scrollView = (PullToZoomScrollViewEx) findViewById(R.id.scroll_view);
View headView = LayoutInflater.from(this).inflate(R.layout.ptz_head_view, null, false);
View zoomView = LayoutInflater.from(this).inflate(R.layout.ptz_zoom_view, null, false);
View contentView = LayoutInflater.from(this).inflate(R.layout.ptz_content_view, null, false);
scrollView.setHeaderView(headView);
scrollView.setZoomView(zoomView);
scrollView.setScrollContentView(contentView);
tvNewsTitle = (TextView) scrollView.getPullRootView().findViewById(R.id.tv_news_title);
tvNewsPublishDate = (TextView) scrollView.getPullRootView().findViewById(R.id.tv_news_publish_date);
tvNewsFull = (TextView) scrollView.getPullRootView().findViewById(R.id.tv_news_full);
tvNewsFull.setTextSize(textSize);
if (!AppController.isPunjabiSupported()) {
tvNewsTitle.setTypeface(typeface);
tvNewsFull.setTypeface(typeface);
}
ivYoutubeEnable = (ImageView) scrollView.getHeaderView().findViewById(R.id.iv_youtube_header);
}
void generateBranchURL(final int newsPosition) {
// String imageUrl = "";
// if (newsArr.get(newsPosition).getMedium().size() <= 1)
// imageUrl = newsArr.get(newsPosition).getMedium().get(0);
BranchUniversalObject branchUniversalObject = new BranchUniversalObject()
.setCanonicalIdentifier("NewsDetails")
///.setCanonicalUrl("https://branch.io/deepviews")
//.setTitle("" + newsArr.get(newsPosition).getTitle())
//.setContentDescription("" + newsArr.get(newsPosition).getIntro())
//.setContentImageUrl("" + imageUrl)
// You use this to specify whether this content can be discovered publicly - default is public
.setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC);
// Here is where you can add custom keys/values to the deep link data
//.addContentMetadata("property1", "blue")
//.addContentMetadata("property2", "red");
LinkProperties linkProperties = new LinkProperties()
.addControlParameter("$desktop_url", "http://www.newsnumber.com/news/share/" + newsArr.get(newsPosition).getFn_id())
.addControlParameter("$ios_url", "itms-apps://itunes.apple.com/us/app/newsnumber/id1022442357?mt=8")
.addControlParameter("NewsId", "" + newsArr.get(newsPosition).getFn_id())
.addControlParameter("CatId", "" + newsArr.get(newsPosition).getCat_id())
.addControlParameter("$og_title", newsArr.get(newsPosition).getTitle())
.addControlParameter("$og_description", newsArr.get(newsPosition).getIntro())
.addControlParameter("$og_image_url", newsArr.get(newsPosition).getImage().get(0))
.addControlParameter("$twitter_title", newsArr.get(newsPosition).getTitle())
.addControlParameter("$twitter_description", newsArr.get(newsPosition).getIntro())
.addControlParameter("$twitter_image_url", newsArr.get(newsPosition).getImage().get(0))
;
branchUniversalObject.generateShortUrl(this, linkProperties, new Branch.BranchLinkCreateListener() {
#Override
public void onLinkCreate(String url, BranchError error) {
if (error == null) {
Log.i("MyApp", "got my Branch link to share: " + url);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "News Number\n");
sharingIntent.putExtra(Intent.EXTRA_TEXT, url);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
}
});
}
}
can anyone help??
thanks in advance.
It seems like you might be trying to make a new Activity for each "page" of a ViewPager. The Android support library already has their own ViewPager that uses fragments.
You basically need three things to use a ViewPager:
The ViewPager itself
An adapter for the ViewPager
The fragment that will be used in the ViewPager (esentially the "template" that will be used for each "page" in the ViewPager)
First, we'll create the fragment. This is just a simple example that uses only one TextView, but it will work for any amount of views and data. You'll notice that static method "newInstance()" that creates and returns an instance of this fragment. Google recommends using this method to instantiate new Fragments for a ViewPager as it makes passing data to the fragment much easier. All fragments have a "setArguments()" method that lets you pass in a Bundle when you instantiate it with whatever data you want. The method "getArguments()" can be used to access that bundle and get the values out of it in onCreate() or onCreateView(). This is how you pass in an object or objects to bind its data to the views. In this example, were just passing in a String and setting that String to a TextView. You'll see how it's used when we create the adapter for the ViewPager.
//You should be using android.support.v4.app.Fragment here
public class ExampleFragment extends Fragment {
private static final String DAY_NAME_KEY = "day_name";
private TextView dayName;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_example, container, false);
dayName = (TextView) fragmentView.findViewById(R.id.day_name);
return fragmentView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Set the name of the day to the dayName TextView
String day = getArguments().getString(DAY_NAME_KEY);
dayName.setText(day);
}
public static ExampleFragment newInstance(String day) {
Bundle bundle = new Bundle();
bundle.putString(DAY_NAME_KEY, day);
ExampleFragment fragment = new ExampleFragment();
fragment.setArguments(bundle);
return fragment;
}
}
Now, we need to make an adapter that will create the views when the ViewPager is swiped. You need to extend either FragmentPagerAdapter or FragmentStatePagerAdapter. FragmentPagerAdapter is used for a small number of static fragments and it will use more memory. So you only want to use this if you have 4 or 5 pages and aren't adding any more dynamically.
For your case, it sounds like you want to swipe through a variable number of pages that are dynamically added, so you want to use FragmentStatePagerAdapter. It's optimized for memory efficiency and it will handle the saving and restoring of the fragments' state for you.
The adapter is simple.
First, you need to make your constructor match the super class's constructor. What that means is that your constructor must have a FragmentManager parameter. All you do with that is pass it to the super class. (You'll see below.)
Secondly, you have to implement just 2 methods from the FragmentStatePagerAdapter class:
public Fragment getItem(int position)
and
public int getCount()
getItem will be automatically called by the ViewPager when it is swiped. You just have to tell it what type of fragment to return. We'll be using the newInstance() method from the ExampleFragment class here.
getCount is the number of views that your ViewPager will be using. For example, I will have an ArrayList that will contain 7 strings (one for each day of the week). I want each one of those strings to be displayed on a different page of my ViewPager. So I'm just going to return the size of the ArrayList for this method.
Here's the class:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
//A reference to the array of data that will be used to populate
//each fragment. In this case it's an array of Strings, but it
//could be any type of object. The Strings within this array are what
//we'll be passing to the newInstance() method of each fragment.
private ArrayList<String> days;
//Constructor must take a FragmentManager to match the superclass.
public ViewPagerAdapter(FragmentManager fm, ArrayList<String> days) {
//All you have to do with the fragment manager is pass it to super
super(fm);
//The array will be passed in when we create the Adapter in our Activity
this.days = days;
}
#Override
public Fragment getItem(int position) {
/*
Automatically called when another page is needed.
The adapter will keep track of the position of the current page
so the first time this is called, it will be 0, then when a
swipe occurs, it will be one. If it is swiped backward, it will go back to 0.
So when the position is 0, a new Fragment will be created and the
String at days.get(0) ("Monday") will be passed to it.
*/
return ExampleFragment.newInstance(days.get(position));
}
#Override
public int getCount() {
return days.size();
}
}
Now we just have to set the adapter for the ViewPager in our Activity and it will automatically handle swipes for us.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> daysOfWeek = new ArrayList<>();
daysOfWeek.add("Monday");
daysOfWeek.add("Tuesday");
daysOfWeek.add("Wednesday");
daysOfWeek.add("Thursday");
daysOfWeek.add("Friday");
daysOfWeek.add("Saturday");
daysOfWeek.add("Sunday");
ViewPager pager = findViewById(R.id.view_pager);
//Pass the activity's fragmentmanager by calling getSupportFragmentManager().
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), daysOfWeek);
pager.setAdapter(adapter);
}
}
This is what we get (I've added some padding and color to make it clear):
As for changing the way the pages "turn" (for example, like a newspaper), you need to look into PageTransformer

Android Weird Error : Fragement Dosen't Recreats The View

HERE IS THE VIDEO:
https://www.youtube.com/watch?v=eush2bY0XlQ&feature=youtu.be&hd=1
So here is the plot :
1) I have a navigation drawer.
2) By Clicking on one of the list item a tab layout (fragment) is inflated .
3) So I get a tab layout (with 6 tabs) working besides navigation drawer i.e navigation drawer and tab_layout can be used simultaneously.
4) Content of every tab is a Different fragement.
Problem :
When I launch the application and click the list-item with the tab fragment the content of the tab_fragment is inflated normally.
But when i click it again all the content of the first and second tab dissappear.
And reappear only when when i swipe till the third tab and swipe back again .
In simple words ,
On Calling the static new Instance method of Tab_Fragment for the first time is works fine .
On Calling it again the content of the first and second tab disappear and reappear
only when I swipe till the 3rd tab and come back.
I know it sounds weird.
Code:
My Tab_Fragment To Create it I call its New Instance From MainActivity.
public class Tab_Activity extends Fragment {
private final Handler handler = new Handler();
public PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
public final static String TAG = Tab_Activity.class.getSimpleName();
public Tab_Activity() {
// TODO Auto-generated constructor stub
}
public static Tab_Activity newInstance() {
return new Tab_Activity();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_layout, container, false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(v, savedInstanceState);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
pager = (ViewPager) v.findViewById(R.id.pager);
adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
tabs.setIndicatorColorResource(R.color.grey);
tabs.setTextColorResource(R.color.black);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { " ELECTRONICS ", " IT ", " COMPUTER "," EXTC ", "INSTRUMENTATION"," MCA " };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return Courses.newInstance(position);
}
}
}
The Courses Fragment :
public class Courses extends Fragment {
LinearLayout ll ;
private static final String ARG_POSITION = "position";
public static PagerSlidingTabStrip tab ;
private int position;
public static Courses newInstance(int position) {
Courses f = new Courses();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dept_main,container,false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(v, savedInstanceState);
// generate ID's :
TextView h_name = (TextView) v.findViewById(R.id.tv_dept_name);
TextView f_info = (TextView) v.findViewById(R.id.tv_dept_info);
TextView h_vision = (TextView) v.findViewById(R.id.header_vision);
TextView f_vision = (TextView) v.findViewById(R.id.footer_vision);
TextView h_mission = (TextView) v.findViewById(R.id.header_mission);
TextView f_mission = (TextView) v.findViewById(R.id.footer_mission);
TextView h_eoe = (TextView) v.findViewById(R.id.header_EOE);
TextView f_eoe = (TextView) v.findViewById(R.id.footer_EOE);
TextView h_intake = (TextView) v.findViewById(R.id.header_intake);
TextView f_intake = (TextView) v.findViewById(R.id.footer_intake);
h_intake.setText(R.string.h_intake);
h_mission.setText(R.string.h_mission);
h_vision.setText(R.string.h_vision);
h_eoe.setText(R.string.h_eoe);
switch(position){
case 0 :
//Electronics
h_name.setText("Electronics");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_etrx);
f_mission.setText(R.string.m_etrx);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_etrx);
break ;
case 1 :
h_name.setText("Information Technology");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_it);
f_mission.setText(R.string.m_it);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_it);
break ;
case 2 :
h_name.setText("Computer Science");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_coms);
f_mission.setText(R.string.m_coms);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_coms);
break ;
case 3 :
h_name.setText("Electronics And Telecommunication");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_extc);
f_mission.setText(R.string.m_extc);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_extc);
break ;
case 4 :
h_name.setText("Instrumentation");
f_info.setText(R.string.ug_course);
f_vision.setText(R.string.v_it);
f_mission.setText(R.string.m_it);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_it);
break ;
case 5 :
h_name.setText("Master of Computer Applications");
f_info.setText("Post Graduation Course.(PG)");
f_vision.setText(R.string.v_mca);
f_mission.setText(R.string.m_mca);
f_eoe.setText("1984");
f_intake.setText(R.string.intake_mca);
break;
}
}
}
(Comment for any clarifications ! )
Found My Answer ==> https://stackoverflow.com/a/12582529/3475933
Only Changed FragmenPagerAdapter to FragmentStatePagerAdapter and eveything worked fine.
Hope it helps .!

ViewPagerIndicator with two ListFragment slow when loading data

I have an app with ViewPager and ViewPagerIndicator. I have two tabs made ​​with TabPageIndicator. Each tab loads a listivew with data of Internet. When I run the app loads the data from tab 1 and 2, this causes very slow to show the view.
I want that when I started my app only load data tab 1 and when I move or click on tab 2 load the data for that tab.
Can you help me?
Thank you.
My code:
MainActivity
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Releases", "Artists" };
private ListView listRls;
private List<Fragment> listaFragments;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
listaFragments = new ArrayList<Fragment>();
listaFragments.add(new FragmRls());
listaFragments.add(new FragmArt());
MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),
listaFragments);
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
}
class MyFragmentAdapter extends FragmentStatePagerAdapter {
//Implementacion del fragmentStateADapter
private List<Fragment> fragments;
public MyFragmentAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
// TODO Auto-generated constructor stub
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
return fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragments.size();
}
}//fin adapter
}//fin class
Code in one of the classes that extend from ListFragement, the other is identical.
public class FragmRls extends ListFragment{
JSONParser jParser = new JSONParser();
private static String url_all_post = "http://adeptlabel.com/listReleaseforTab.php";
private static String url_all_art = "http://adeptlabel.com/listArtists.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_posts = "wp_posts";
private static final String TAG_TITULO = "titulo";
private static final String TAG_IMAGEN = "imagen";
JSONArray posts = null;
private ArrayList <ElementosList> elementos = new ArrayList <ElementosList>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragmrls, null);
}//Fin On CreateView
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
elementos.clear();
loadDataJsonRls();
for(int i=0;i<ListViewConfig.getResim_list_txt().size();i++)
{
elementos.add(new ElementosList(ListViewConfig.getResim_list_txt().get(i),
ListViewConfig.getResim_list_img().get(i)));
}
ArrayAdapter<ElementosList>adaptador = new AdaptadorList(getActivity(),elementos);
setListAdapter(adaptador);
}
public void loadDataJsonRls()
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_post, "GET", params);
// Check your log cat for JSON reponse
Log.d("All releases: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
posts = json.getJSONArray(TAG_posts);
//Borramos los arrayList
ListViewConfig.deleteResim_list_img();
ListViewConfig.deleteResim_list_txt();
// looping through All post
for (int i = 0; i < posts.length(); i++) {
boolean repite = false;
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String titulo = c.getString(TAG_TITULO);
String imagen = c.getString(TAG_IMAGEN);
for(int j=0;j<ListViewConfig.getResim_list_txt().size();j++)
{
if(titulo.equals(ListViewConfig.getResim_list_txt().get(j)))
{
repite = true;
}
}
if(repite==false)
{
ListViewConfig.addImageUrls(imagen);
ListViewConfig.addTextUrls(titulo);
}
}
} else {
//Log.d("MainActivity.class", "No success Json");
}
} catch (JSONException e) {
e.printStackTrace();
}
}//fin cargarDatosJsonRls()
}//fin class
If you want to load data associated with second tab when user switch to that tab, try to move code that loads data from onCreate to a public method. Then set OnPageChangeListener and load data when onPageSelected is called.
Furthermore, make sure that you load data asynchronously, for example using AsyncTask.
You are making your network calls on the UI thread, this is why your UI is slow. You may want to use an AsyncTask, effectively moving your network activity to another thread. Its doInBackground method will handle the network things, and the onPostExecute method allows you to update your UI when the execution of the Task is finished. More details in the official documentation here.
Additionally, depending on your needs and time, you could either pre-load the data so the loading time when the user is presented with the screen is reduced, or show a ProgressBar while you are loading the data, then update the UI when loading is done.
The solution to my problem I found here:
(ViewPager, ListView, and AsyncTask, first page blank, all data in the second page
However, thanks for your attention Nartus and 2Dee.

Updating the ListView in a Fragment from a Dialog in FragmentActivity(using a ViewPager)

I have a FragmentActivity (main) which creates 3 Fragments and also a menu. Pretty straight forward, and from the examples in the Android SDK.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbh = new DBHelper(this);
// Create the adapter that will return a fragment for each of the
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
// code //
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position){
case 0:
fragment = new DaySectionFragment(Main.this, dbh);
break;
case 1:
fragment = new WeekSectionFragment(Main.this, dbh);
break;
case 2:
fragment = new FoodListSectionFragment(Main.this, dbh);
break;
case 3:
fragment = new AboutSectionFragment();
break;
}
return fragment;
}
//more code
From the menu in the main activity I have a dialog with an editText. The value from this textfield is suppose to be stored in a database, which works fine, and also pop up in the listview in the fragment (not i ListFragment, but a fragment with a listview in it). The simple way would be to call notifyDataSetChanged() on the ListView adapter. However I can't do that.
This is the fragment with the ListView:
public class FoodListSectionFragment extends Fragment {
private Context context;
private DBHelper dbh;
private ArrayList<FoodData> listItems = new ArrayList<FoodData>();
private FoodAdapter adapterFoodList;
private AdapterView.AdapterContextMenuInfo adapterInfo;
private ListView lvItems;
public FoodListSectionFragment() {
}
public FoodListSectionFragment(Context context, DBHelper dbh) {
this.context = context;
this.dbh = dbh;
//setTag("FoodListFragment");
}
public void updateList(){
adapterFoodList.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = getLayoutInflater(null).inflate(R.layout.food_list, null);
listItems.clear();
listItems = (ArrayList<FoodData>) dbh.selectAllFood();
adapterFoodList = new FoodAdapter(context, R.layout.list_row_food, listItems);
lvItems = (ListView)myView.findViewById(R.id.listFood);
lvItems.setAdapter(adapterFoodList);
adapterFoodList.notifyDataSetChanged();
return myView;
}
}
Here is where I'm trying to update the ListView, although this won't work.
dialogAddFood = new Dialog(Main.this);
dialogAddFood.setContentView(R.layout.dialog_add_food);
dialogAddFood.setTitle(R.string.menu_add_food);
dialogAddFood.setCancelable(true);
Button btnSave = (Button) dialogAddFood.findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText edtFood = (EditText)dialogAddFood.findViewById(R.id.edtFood);
RatingBar ratingGrade = (RatingBar)dialogAddFood.findViewById(R.id.ratingGrade);
RatingBar ratingDiff = (RatingBar)dialogAddFood.findViewById(R.id.ratingDiff);
if(edtFood.getText().toString().length() > 0){
dbh.insertFood(edtFood.getText().toString(), (int)ratingGrade.getRating(), (int)ratingDiff.getRating());
Toast.makeText(Main.this, "Maträtt tillagd", Toast.LENGTH_LONG).show();
//FoodListSectionFragment f = (FoodListSectionFragment)Main.this.getSupportFragmentManager().findFragmentByTag("FoodList");
//f.updateList();
ListView l = (ListView)mSectionsPagerAdapter.getItem(2).getView().findViewById(R.id.listFood);
FoodAdapter a = (FoodAdapter)l.getAdapter();
a.notifyDataSetChanged();
}
dialogAddFood.cancel();
}
});
Button btnCancel = (Button) dialogAddFood.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialogAddFood.cancel();
}
});
dialogAddFood.show();
Help, please.
Your code doesn't work because the line:
mSectionsPagerAdapter.getItem(2)
doesn't return the Fragment at position 2 from the ViewPager, it creates a new Fragment for that position and calling update methods on this Fragment instance will obviously not make any changes as this Fragment isn't attached to your Activity(is not the visible one).
Try to look for that Fragment using the FragmentManager like below and see how it goes:
// ...
Toast.makeText(Main.this, "Maträtt tillagd", Toast.LENGTH_LONG).show();
//FoodListSectionFragment f = (FoodListSectionFragment)Main.this.getSupportFragmentManager().findFragmentByTag("FoodList");
//f.updateList();
FoodListSectionFragment fr = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.theIdOfTheViewPager + ":2");
if (fr != null && fr.getView() != null) {
fr.updateList();
}

Categories

Resources