Currently I have made 3 tabs. On each tab (fragment) there is a thread to fetch content and display it with a listview through an ArrayAdapter.
Now when you scroll through the tabs the thread gets executed again and again (not necessary).
Is there a way to stop this ? Or do I need to write the content to external storage for faster access ?
Also sometimes I see the same data on different tabs , how to avoid this ?
Thanks in advance
This is some code that I use inside my fragment which that is called multiple times when swiping :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
rootView = inflater.inflate(R.layout.leadlist, container, false);
profielen = new ArrayList<Profile>();
new getLeaderboards().execute(url);
lv = (ListView) rootView.findViewById(android.R.id.list);
lbadapter = new LeaderBoardAdapter(this.getActivity(), R.layout.item_layout, profielen);
return rootView;
}
public static class getLeaderboards extends AsyncTask<String, Void, JsonObject> {
#Override
protected JsonObject doInBackground(String... urls) {
JsonObject x = parseURL.GetJSON(urls[0]);
return x;
}
#Override
protected void onPostExecute(JsonObject obj) {
Gson gson = new Gson();
System.out.println(obj.toString());
JsonArray arr = obj.get("rows").getAsJsonArray();
for (int i=0;i<10;i++) {
Profile pat = gson.fromJson( arr.get(i) , Profile.class);
profielen.add(pat);
}
lv.setAdapter(lbadapter);
}
}
My FragmentActivity :
public class LeaderboardsActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Tab1", "Tab2", "Tab3" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.leaderboard);
Intent i = getIntent();
String region = i.getStringExtra("region");
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(),region);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Related
when i run this code,the toast in two different fragments are displayed on one tab. when i swipe to next tab nothing is displayed.
this is is my main tab activity:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Offers", "Distance", "Happy Hours","Shop List" };
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
this is adapter class :
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
Bundle bundle = new Bundle();
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
Fragment of = new OfferFragment();
bundle.putString("OfferFragment", "OfferFragment");
of.setArguments(bundle);
return of;
case 1:
Fragment df = new DistanceFragment();
bundle.putString("DistanceFragment", "DistanceFragment");
df.setArguments(bundle);
return df;
case 2:
Fragment hf = new HappyHoursFragment();
bundle.putString("HappyHoursFragment", "HappyHoursFragment");
hf.setArguments(bundle);
return hf;
case 3:
Fragment sf = new ShoplistFragment();
bundle.putString("ShoplistFragment", "ShoplistFragment");
sf.setArguments(bundle);
return sf;
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
this is my first fragment :
public class OfferFragment extends Fragment {
private String name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// public static final String ARG_OBJECT = "object";
View rootView = inflater.inflate(R.layout.offerfragment, container,
false);
Bundle args = getArguments();
TextView txtview = (TextView) rootView.findViewById(R.id.offer);
name = args.getString("OfferFragment");
txtview.setText(args.getString("OfferFragment"));
display();
return rootView;
}
private void display() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
}
this is my second fragment :
public class DistanceFragment extends Fragment {
private String name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.distancefragment, container, false);
Bundle args = getArguments();
TextView txtview = (TextView) rootView.findViewById(R.id.distance);
name = args.getString("DistanceFragment");
txtview.setText(args.getString("DistanceFragment"));
display();
return rootView;
}
private void display() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
}
any suggestions are appreciated. am stuck with this.
This is because next fragment is created by pager
before showing toast check if that fragment is visible or not
if(fragmentName.this.isVisible())
{
// do your stuff here
}
Write onResume() in every fragment class.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//Display Toast message here
}
}
hi,
it is my project in the photo. my project has custom listView in every page and listViews are filled with json data.
i writed every tab's onCreateView event Toast message to clarify problem and see what has happened.
for example, when i click 2.th tab, i get "2 worked" then "3 worked" as toast message. also add same data to listview over and over again btw.
sorry if i couldn't explain my problem.
here is my codes.
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new VasitaTurFragment();
.
.
.
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 6;
}
MainActivity:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "1", "2", "3","4","5","6" };
ModelFragment mF= new ModelFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Fragment:
public class MenseiFragment extends Fragment {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<Mensei> menseiList = new ArrayList<Mensei>();
private ListView listView;
private menseiCLA adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.mensei, container, false);
listView = (ListView) rootView.findViewById(R.id.listView1);
adapter = new menseiCLA(getActivity(), menseiList);
listView.setAdapter(adapter);
Toast.makeText(getActivity(),"2 worked",
Toast.LENGTH_LONG).show();
JsonArrayRequest commonReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject objAna = response.getJSONObject(i);
Mensei mensei = new Mensei();
.
.
menseiList.add(mensei);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(commonReq);
return rootView;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}}
This is the default behavior of viewpager, so if you click on each tab the two neighbors of it automatically created and both run in onResume. if you really want they do something only when they are visible use below function for each tab fragment:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisible()){
if(isVisibleToUser){
Log.d("MyTag","My Fragment is visible");
}else{
Log.d("MyTag","My Fragment is not visible");
}
}
}
I succeeded in make a Tabbed Layout, but I have a concern. tabs appear but disappear just after loading the first fragment. i dont have lot of idea it is due to what. This the code to try to find the error.
The onCreateView of the fragment which on i display the cotaint.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_clubs_pages, container, false);
// Initilization
viewPager = (ViewPager) v.findViewById(R.id.pager);
actionBar = getActivity().getActionBar();
mAdapter = new TabsPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
return v;
}
The Main Class :
public class ClubsPages extends android.support.v4.app.Fragment implements ActionBar.TabListener {
private OnFragmentInteractionListener mListener;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = {"Clubs", "Pages"};
// TODO: Rename and change types and number of parameters
public static ClubsPages newInstance() {
ClubsPages fragment = new ClubsPages();
return fragment;
}
public ClubsPages() {
// Required empty public constructor
}
#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
View v = inflater.inflate(R.layout.fragment_clubs_pages, container, false);
// Initilization
viewPager = (ViewPager) v.findViewById(R.id.pager);
actionBar = getActivity().getActionBar();
mAdapter = new TabsPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
/*viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});*/
actionBar.show();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
I said that the tabs disappear just after loading the first fragment. so any help please ?
I have an ActionBar that contains 11 tabs and 1 fragment. I also have a ViewPager to display the fragment(s). When a tab is clicked it creates the same fragment. The tabs display dates so they change everyday. What I need is to send the text of the tab (ie. .getTabText()) to the fragment, this will change the content of the fragment. I am having so much trouble trying to figure out how to do this. Here is all my code:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private ArrayList<TopRatedFragment> myFragmentList = new ArrayList<TopRatedFragment>();
// Tab titles
String[] tabs = {this.getCurrentDate(-5).toString(),this.getCurrentDate(-4).toString(),this.getCurrentDate(-3).toString(), this.getCurrentDate(-2).toString(),this.getCurrentDate(-1).toString(),
this.getCurrentDate(0).toString(),
this.getCurrentDate(1).toString(), this.getCurrentDate(2).toString(), this.getCurrentDate(3).toString(), this.getCurrentDate(4).toString(), this.getCurrentDate(5).toString(),};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (String tab_name : tabs) {
TopRatedFragment fm = new TopRatedFragment();
fm.getTabs(tab_name);
myFragmentList.add(fm);
}
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), myFragmentList);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
actionBar.setSelectedNavigationItem(5);
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
public String getTab(Tab tab) {
return tab.getText().toString();
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
public String getCurrentDate(int offset) {
String calAsString;
DateFormat formatter = new SimpleDateFormat("MM/dd");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, offset);
calAsString = formatter.format(cal.getTime());
return calAsString;
}
}
Here is my FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
ArrayList<TopRatedFragment> myList;
public TabsPagerAdapter(FragmentManager fm, ArrayList<TopRatedFragment> myList) {
super(fm);
this.myList = myList;
}
#Override
public Fragment getItem(int index) {
return myList.get(index);
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return myList.size();
}
And here is my simple fragment (for now):
public class TopRatedFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void getTabs(String tabs) {
Log.e("TRF", tabs);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
}
Create a static newInstance method to create fragment and bundle the args for the fragment. Pull the args in the fragment.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (String tab_name : tabs) {
TopRatedFragment fm = new TopRatedFragment.newInstance(tab_name);
fm.getTabs(tab_name);
myFragmentList.add(fm);
}
public class TopRatedFragment extends Fragment {
public static Fragment newInstance(String position) {
TopRatedFragment f = new TopRatedFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("num", position);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle b = getArguments();
if (b!=null){
String someText = b.containsKey("num")?b.getString("num"):null;
}
I would like to create a new fragment every time when I click its tab.
I tried to get the tab and to create a fragment. But it doesn't seem to work.
Here is my code.
Main Activity
public class MainActivity extends FragmentActivity {
private static ViewPager viewPager;
private static TabsPagerAdapter mAdapter;
private static ActionBar actionBar;
// Tab titles
private String[] tabs = { "TopRated", "Hots", "NEW"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
//actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(tabListener));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
static ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
};
TabsPagerAdapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new TopRatedFragment();
case 1:
return new HotStoryFragment();
case 2:
return new AllClassFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
One of the fragments
public class HotStoryFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Refresh_F","(2) HotStory");
View rootView = inflater.inflate(R.layout.fragment_hotstory, container, false);
TextView tvStudy = (TextView)rootView.findViewById(R.id.text);
return rootView;
}