Progress bars and Fragments - android

Im trying to update the progress bar based on the swiping of fragments , totally there are three fragments , and three circular progress bar , im getting the progress bar along with the test values no problem about that , but im not getting the fragments displayed ,this is the code please let me know where im wrong .
public class History extends Fragment {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
public static final String ARG_PAGE = "ARG_PAGE";
private static final int NUM_PAGES = 3;
String medicinename,medicinepercentage,numberdosages,time;
String date,day,daypercentage;
String month,monthdata;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
private int selectedPage; // set selected page
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
DonutProgress dp;
DonutProgress dp2;
DonutProgress dp3;
public static History newInstance(int page) {
Log.e("History ", String.valueOf(page));
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
History fragment = new History();
fragment.setArguments(args);
return fragment;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public History() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment History.
*/
// TODO: Rename and change types and number of parameters
public static History newInstance(String param1, String param2) {
Log.e("History2 ", param1+param2);
History fragment = new History();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_history, container, false);
dp = (DonutProgress) v.findViewById(R.id.donut_progress1);
dp2 = (DonutProgress) v.findViewById(R.id.donut_progress2);
dp3 = (DonutProgress) v.findViewById(R.id.donut_progress3);
new Progress(100).execute();
new Progress2(20).execute();
new Progress3(30).execute();
new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();
new Progress(50).execute();
new Progress2(10).execute();
new Progress3(30).execute();
/* new Progress(0).execute();
new Progress2(0).execute();
new Progress3(0).execute();*/
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mPager = (ViewPager) v.findViewById(pager); //the UI pager
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager()) {
#Override
public int getCount()
{
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
};
mPager.setAdapter(mPagerAdapter);
// mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation
selectedPage = 0; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 1; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 2; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
mPager.setCurrentItem(selectedPage);
mPager.setOffscreenPageLimit(0);
//set the current page
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position)
{
// Check if this is the page you want.
getItem(position);
Log.e("Started","hello");
}
public Fragment getItem(int position) {
int i = 0;
switch (position) {
case 0: { // Fragment # 0 - This will show FirstFragment
if (!(i < 3)) {
}
++i;
return SlideFragment.newInstance(String.valueOf(0), " ");
}
case 1: { // Fragment # 1 - This will show SecondFragment
Log.e("Fragment", "Fragment 2");
if (!(i < 3)) {
/*new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();*/
}
++i;
return Slidetwo.newInstance(String.valueOf(1), " ");
}
case 2: { // Fragment # 1 - This will show SecondFragment
Log.e("Fragment", "Fragment 3");
if (!(i < 3)) {
/* new Progress(50).execute();
new Progress2(10).execute();
new Progress3(0).execute();*/
}
++i;
return SlideThree.newInstance(String.valueOf(2), " ");
}
default:
return null;
}
}
});
return v;
}
class Progress extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp.setMax(100);
// Progress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#C0D000"), android.graphics.PorterDuff.Mode.SRC_ATOP);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress2 extends AsyncTask<Void, Integer, Integer> {
int dummyVariable =0;
Progress2(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp2.setMax(100);
}
#Override
protected Integer doInBackground(Void... params) {
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try {
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp2.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress3 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable =0;
Progress3(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp3.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp3.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
private class ScreenSlidePagerAdapter extends PagerAdapter {
public ScreenSlidePagerAdapter(Object fragmentManager) {
}
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
// TODO: Rename method, update argument and hook method into UI event
}
`

Related

Using Fragments in View pager

I am Creating an application which uses different fragments inside a view pager , there are three progress bars on the left of view pager in which the data changes in according to the fragments ,But when i run the application all data assigned to the progress bars are getting displayed , without swiping the fragments and while swiping the fragments the data is not changed in the progress bars, here is my code
public class History extends Fragment {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
public static final String ARG_PAGE = "ARG_PAGE";
private static final int NUM_PAGES = 3;
String medicinename,medicinepercentage,numberdosages,time;
String date,day,daypercentage;
String month,monthdata;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
private int selectedPage; // set selected page
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
DonutProgress dp;
DonutProgress dp2;
DonutProgress dp3;
public static History newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
History fragment = new History();
fragment.setArguments(args);
return fragment;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Paint progressPaint = new Paint();
private int lineHeight = 30;
private Paint incompletePaint = new Paint();
public History() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment History.
*/
// TODO: Rename and change types and number of parameters
public static History newInstance(String param1, String param2) {
History fragment = new History();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_history, container, false);
dp = (DonutProgress) v.findViewById(R.id.donut_progress1);
dp2 = (DonutProgress) v.findViewById(R.id.donut_progress2);
dp3 = (DonutProgress) v.findViewById(R.id.donut_progress3);
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mPager = (ViewPager) v.findViewById(R.id.pager); //the UI pager
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
// mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation
selectedPage = 0; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 1; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 2; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 3; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
mPager.setCurrentItem(selectedPage);//set the current page
mPager.setOffscreenPageLimit(4);
return v;
// return inflater.inflate(R.layout.fragment_history, container, false);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
int i = 0;
#Override
public Fragment getItem(int position)
{
if(position==0){
Log.e("Fragment","Fragment 1::"+String.valueOf(i));
new Progress(100).execute();
new Progress2(20).execute();
new Progress3(30).execute();
return SlideFragment.newInstance(0, " ");}
if(position==1){
Log.e("Fragment","Fragment 2");
new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();
return Slidetwo.newInstance(String.valueOf(0), " ");}
if (position==2)
Log.e("Fragment","Fragment 3");
new Progress(50).execute();
new Progress2(10).execute();
new Progress3(40).execute();
return SlideThree.newInstance(String.valueOf(0), " ");
}
#Override
public int getCount()
{
return NUM_PAGES;
}
}
class Progress extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
dp.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer)
{
super.onPostExecute(integer);
}
}
class Progress2 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress2(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp2.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try {
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp2.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress3 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress3(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp3.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp3.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
Don't change the progress in pager adapter. for that add below code and in the onPageSelected() method based on the position change the progress.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Progress bar update on Swiping fragments

Im creating an application to show data in progress bar based on the selected fragment , so if particular fragment is selected the progress bar should show the data in that fragment and so on , in my application there are three fragments the data in progress bar gets updated for two fragments and not working for the third one ,ive tried with log everything looks fine ,,Ive tried giving logs and what ive figued out is that the fragment that is being opened is only two of them and im not getting the third log , even when i open the third fragment,and im getting an indication of opening the third fragment if i again move back to the second fragment,i cant figure out where im missing it . below is my code
public class History extends Fragment {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
public static final String ARG_PAGE = "ARG_PAGE";
private static final int NUM_PAGES =3;
String medicinename,medicinepercentage,numberdosages,time;
String date,day,daypercentage;
String month,monthdata;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
private int selectedPage; // set selected page
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
DonutProgress dp;
DonutProgress dp2;
DonutProgress dp3;
public static History newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
History fragment = new History();
fragment.setArguments(args);
return fragment;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Paint progressPaint = new Paint();
private int lineHeight = 30;
private Paint incompletePaint = new Paint();
public History() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment History.
*/
// TODO: Rename and change types and number of parameters
public static History newInstance(String param1, String param2) {
History fragment = new History();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_history, container, false);
dp = (DonutProgress) v.findViewById(R.id.donut_progress1);
dp2 = (DonutProgress) v.findViewById(R.id.donut_progress2);
dp3 = (DonutProgress) v.findViewById(R.id.donut_progress3);
new Progress(0).execute();
new Progress2(0).execute();
new Progress3(0).execute();
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mPager = (ViewPager) v.findViewById(R.id.pager); //the UI pager
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
// mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation
selectedPage = 0; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 1; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 2; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 3; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
mPager.setCurrentItem(selectedPage); //set the current page
return v;
// return inflater.inflate(R.layout.fragment_history, container, false);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
int i = 0;
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
Log.e("Fragment","Fragment 1::"+String.valueOf(i));
new Progress(100).execute();
new Progress2(20).execute();
new Progress3(30).execute();
return SlideFragment.newInstance(String.valueOf(0), " ");
case 1: // Fragment # 1 - This will show SecondFragment
Log.e("Fragment","Fragment 2");
new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();
return Slidetwo.newInstance(String.valueOf(1), " ");
case 2: // Fragment # 1 - This will show SecondFragment
Log.e("Fragment","Fragment 3");
new Progress(50).execute();
new Progress2(10).execute();
new Progress3(0).execute();
return SlideThree.newInstance(String.valueOf(2), " ");
default:
return null;
}
}
#Override
public int getCount()
{
return NUM_PAGES;
}
}
class Progress extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 1;
Progress(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp.setMax(100);
// Progress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#C0D000"), android.graphics.PorterDuff.Mode.SRC_ATOP);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress2 extends AsyncTask<Void, Integer, Integer> {
int dummyVariable = 0;
Progress2(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp2.setMax(100);
}
#Override
protected Integer doInBackground(Void... params) {
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try {
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp2.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress3 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress3(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp3.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp3.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
// TODO: Rename method, update argument and hook method into UI event
}
Did you set offscreenPaginglimit?
Try setting
yourViewPager.setOffScreenPagingLimt=2;
Let me know if this helps out!

How to destroy a Fragment programmatically in FragmentStatePagerAdapter

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

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

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

GridView TabView not working in when i am json parsing

It's working fine in single GridView Json Object,when i am calling to tabView my tabs will displaying but my Gridview not set into my Tabs.
Please any one help me
Main Activity
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#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) {
}
}
MyAdapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Kids();
case 2:
// Movies fragment activity
return new Kids();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
this activity not displaying in my Tabview,it will working fine in my single gridview activity,when i am calling in tabview it will not diisplaed my gridview
kids.java
public class Kids extends Fragment {
ListAdapter adapter;
private ArrayList<Pojo> gridData;
GridView grd;
private ProgressBar mProgressBar;
private String Sam_URL = "http://example.in/rest/jsoMain/document?name=Rekapalli";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
System.out.println("Servce Called");
gridData=new ArrayList<Pojo>();
grd =(GridView)rootView.findViewById(R.id.gridview);
Async as=new Async(getActivity(),grd);
as.execute(Sam_URL);
mProgressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
// grd.setBackgroundColor(Color.CYAN);
grd.setVerticalSpacing(7);
grd.setHorizontalSpacing(7);
return super.onCreateView(inflater, container, savedInstanceState);
}
class Async extends AsyncTask<String, Void, Integer>{
Context context;
GridView gridView;
public Async(Context context,GridView gridView) {
// TODO Auto-generated constructor stub
this.context=context;
this.gridView=gridView;
}
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
Integer result = 0;
try {
// Create Apache HttpClient
//HttpClient httpclient = new DefaultHttpClient();
URL url = new URL(Sam_URL);
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
// int statusCode =
// httpResponse.getStatusLine().getStatusCode();
// 200 represents HTTP OK
if (true) {
String response = streamToString(in);
parseResult(response);
result = 1; // Successful
} else {
result = 0; // "Failed
}
} catch (Exception e) {
}
return result;
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == 1) {
gridView.setAdapter(new MyAdapter(context,gridData));
gridView.setVisibility(View.VISIBLE);
}mProgressBar.setVisibility(View.GONE);
}
private void parseResult(String result) {
try {
Log.d("MainActivity", "JSON Result : " + result);
JSONArray response = new JSONArray(result);
for (int i = 0; i < response.length(); i++)
{
JSONObject obj = response.getJSONObject(i);
String Doc_name = obj.getString("documentName");
Log.d("documentName",Doc_name);
String Doc_file = obj.getString("documentFile");
String Doc_content = obj.getString("documentContent");
String Doc_offer=obj.getString("offer");
String Doc_address=obj.getString("address");
//Log.d("documentName","JSON Result : " + result);
Pojo gd = new Pojo();
gd.setDocumentName(Doc_name);
gd.setDocumentFile(Doc_file);
gd.setOffer(Doc_offer);
gd.setDocumentContent(Doc_content);
gd.setAddress(Doc_address);
gridData.add(gd);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Change from:
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Kids();
case 2:
// Movies fragment activity
return new Kids();
}
return null;
}
To:
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Games();
case 2:
// Movies fragment activity
return new Movies();
}
return null;
}
Hope that Helps!!!

Categories

Resources