onCreate called for two tabs each time one tab is selected - android

I have a tabbed application built with fragments and ActionBarSherlock. I have 7 tabs. Here's what's happening.
When I select any tab, the onCreate method for the associated fragment is called as expected. The problem is that the onCreate method is called for the next adjacent tab as well. For instance:
App starts in tab1 and onCreate is called as expected
tab2 onCreate is called as well (should not happen)
-------
Click on tab2 and onCreate is called as expected (even though it's already been called)
tab3 onCreate is called as well (should not happen)
-------
Click on tab6 and onCreate is called as expected
tab7 onCreate is called as well (should not happen)
-------
And really weird, click on tab7 (the last tab)
tab6 (2nd to last tab) onCreate is called as well (should not happen)
I've read a couple of possible problems and checked to make sure it's not happening here:
Not using unique tag for each tab (they are unique)
Emulator has bug that calls onCreate twice (I get the same behavior on my ICS device)
So it's not the two previous possibilities and I'll completely out of ideas. The program runs fine but loading two fragments (which are webviews) takes too much time and isn't the behavior I expected.
Here's my code for the main activity onCreate which creates the tab host:
EDITED:
public class SynergyWorldwideActivity extends SherlockFragmentActivity
{
//TabHost mTabHost;
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up the view pager
setContentView(R.layout.fragment_tabs_pager);
mViewPager = (ViewPager)findViewById(R.id.pager);
// Set up action bar
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(true);
//bar.setDisplayShowHomeEnabled(false);
// Creat tabs with bundled URLs
Bundle tab1Args=new Bundle(), tab2Args=new Bundle(), tab3Args=new Bundle(),
tab4Args=new Bundle(), tab5Args=new Bundle(), tab6Args=new Bundle(), tab7Args=new Bundle();
tab1Args.putString("tabURL", getString(R.string.webtab1_URL));
tab2Args.putString("tabURL", getString(R.string.webtab2_URL));
tab3Args.putString("tabURL", getString(R.string.webtab3_URL));
tab4Args.putString("tabURL", getString(R.string.webtab4_URL));
tab5Args.putString("tabURL", getString(R.string.webtab5_URL));
tab6Args.putString("tabURL", getString(R.string.webtab6_URL));
tab7Args.putString("tabURL", getString(R.string.webtab7_URL));
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(getString(R.string.webtab1_name)),
WebTabFragment.MyWebviewFragment.class, tab1Args);
mTabsAdapter.addTab(bar.newTab().setText(getString(R.string.webtab2_name)),
WebTabFragment.MyWebviewFragment.class, tab2Args);
mTabsAdapter.addTab(bar.newTab().setText(getString(R.string.webtab3_name)),
WebTabFragment.MyWebviewFragment.class, tab3Args);
mTabsAdapter.addTab(bar.newTab().setText(getString(R.string.webtab4_name)),
WebTabFragment.MyWebviewFragment.class, tab4Args);
mTabsAdapter.addTab(bar.newTab().setText(getString(R.string.webtab5_name)),
WebTabFragment.MyWebviewFragment.class, tab5Args);
mTabsAdapter.addTab(bar.newTab().setText(getString(R.string.webtab6_name)),
WebTabFragment.MyWebviewFragment.class, tab6Args);
mTabsAdapter.addTab(bar.newTab().setText(getString(R.string.webtab7_name)),
WebTabFragment.MyWebviewFragment.class, tab7Args);
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
/**
* This is a helper class that implements the management of tabs and all
* details of connecting a ViewPager with associated TabHost. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct paged in the ViewPager whenever the selected
* tab changes.
*/
public static class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener{
private final Context mContext;
//private final TabHost mTabHost;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = ((SherlockFragmentActivity) activity).getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public int getCount()
{
int iCount = mTabs.size();
return iCount;
}
#Override
public Fragment getItem(int position)
{
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state)
{
}
#Override
public void onTabSelected(Tab tab)
{
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab)
{
}
#Override
public void onTabReselected(Tab tab)
{
}
}
}
Here's the code for the tab fragments:
EDITED:
public class WebTabFragment extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null)
{
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentById(android.R.id.content) == null) {
MyWebviewFragment myWebView = new MyWebviewFragment();
fm.beginTransaction().add(android.R.id.content, myWebView).commit();
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//outState.putString("tabNumber", mTabNumber);
}
public static class MyWebviewFragment extends SherlockFragment {
final static private String tag = MyWebviewFragment.class.getSimpleName();
String mTabURL;
private WebView mWebView = null;
static final int REFRESH_ID = Menu.FIRST;
private ProgressDialog spinnerDlg;
#Override
public void onSaveInstanceState(Bundle outState)
{
if(mWebView.saveState(outState) == null)
Log.i(tag,"Saving state FAILED!");
else
Log.i(tag, "Saving state succeeded.");
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(Menu.NONE, REFRESH_ID, 0, getString(R.string.refresh_string))
.setIcon(R.drawable.ic_action_refresh)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case REFRESH_ID:
if(mWebView != null)
mWebView.reload();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Tell the framework to try to keep this fragment around
// during a configuration change.
setRetainInstance(true);
mTabURL = getArguments() != null ? getArguments().getString("tabURL") : "http://www.google.com";
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create view object to return
View v = inflater.inflate(R.layout.webview_layout, container, false);
// Set up webview object
if (mWebView != null) {
mWebView.destroy();
}
mWebView = (WebView)v.findViewById(R.id.webview_fragment);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setOnKeyListener(new OnKeyListener(){
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return false;
}
});
// Check to see if it has been saved and restore it if true
if(savedInstanceState != null)
{
if (savedInstanceState.isEmpty())
Log.i(tag, "Can't restore state because bundle is empty.");
else
{
if (mWebView.restoreState(savedInstanceState) == null)
Log.i(tag, "Restoring state FAILED!");
else
Log.i(tag, "Restoring state succeeded.");
}
}
else
{
// Load web page
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportZoom(false);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.loadUrl(mTabURL);
}
return v;
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public void onDestroyView()
{
super.onDestroyView();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// YouTube video link
if (url.startsWith("http://youtu.be"))
{
String urlSubString = url.substring("http://youtu.be/".length());
String newURL = String.format("http://www.youtube.com/v/%s", urlSubString);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(newURL)));
return (true);
}
return (false);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if(spinnerDlg == null)
{
spinnerDlg = new ProgressDialog(getActivity());
spinnerDlg.setMessage("Loading....");
spinnerDlg.show();
}
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(spinnerDlg != null)
{
spinnerDlg.dismiss();
}
spinnerDlg = null;
}
}
}
}

Tabs count will start form 0 so in viewPager you have to set the screen limit like below
Example if you have 3 tabs just give
viewPager.setOffscreenPageLimit(2);

Thats one of the properties of tabs. It loads the second one so you aren't swiping to a null tab.. You're welcome to override the tab class and handle that yourself if you want :D.

If you are using fragments, consider using ViewPager. Its much easier to implement and faster in response.
example here,
http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html

You say
onCreate is called as well (should not happen)
But that's exactly what should happen if you use ViewPager. How else would you see the fragment if you swipe it half way between the first and second tab?
If you tap on tab 2, it will be recreated maybe, because it is destroyed. Try to override getItemPosition like this:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}

Related

Getting a null pointer exception when trying to pass a boolean via an interface

I am using an interface, as is standard (best?) practice to communicate between a series of fragments. The business logic requires the app to collect some information in fragment n+1 and if the "next" button is tapped then the user goes to fragment n+2. If the "back" button is tapped then the user goes to fragment n. I am also using a nice sliding animation to display the transition from one fragment to the other depending on the direction. I cannot figure out why this is not working and I am getting the null pointer error on this line:
createPlanListener.onCreatePlan(bundle);
Here is the initial fragment Mealplan.class where I trigger the transition. I have left all of the boiler plate code generated by Android Studio as is:
public class MealplanFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private FloatingActionButton createMealplan;
// bunch of variables
private Bundle bundle;
private OnCreatePlanListener createPlanListener;
public MealplanFragment() {
// Required empty public constructor
}
public static MealplanFragment newInstance(String param1, String param2) {
MealplanFragment fragment = new MealplanFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Other code that has nothing to do with the bundle or the listener
// Floating action bar
createMealplan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bundle.putBoolean("direction", true);
createPlanListener.onCreatePlan(bundle);
}
});
return mealplanView;
}
public void onButtonPressed(Bundle bundle) {
if (createPlanListener != null) {
createPlanListener.onCreatePlan(bundle);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mealplanContext = context;
if (context instanceof OnCreatePlanListener) {
createPlanListener = (OnCreatePlanListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
createPlanListener = null;
}
public interface OnCreatePlanListener {
void onCreatePlan(Bundle bundle);
}
#Override
public void onResume() {
super.onResume();
}
And here is MainActivity.class
public class MainActivity extends AppCompatActivity implements
MealplanFragment.OnCreatePlanListener {
// Non related variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// MealplanFragment is the default fragment at onCreate
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new MealplanFragment(), null).commit();
}
}
#Override
public void onCreatePlan(Bundle bundle) {
if (bundle != null) {
Boolean direction = bundle.getBoolean("direction");
ReceptionFragment fragment = new ReceptionFragment();
openFragment(bundle, fragment, direction);
}
}
private void openFragment(Bundle bundle, Fragment fragment, Boolean direction) {
fragment.setArguments(bundle);
//Starting fragment with animation
if (direction) {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right).replace(R.id.frame_container, fragment, null);
fragmentTransaction.commit();
} else {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_left).replace(R.id.frame_container, fragment, null);
fragmentTransaction.commit();
}
}
}
createMealplan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bundle.putBoolean("direction", true);
createPlanListener.onCreatePlan(bundle);
}
});
This is your click listener. bundle is defined as class variable but never initialized and hence the null pointer exception. I would suggest that you use a local variable -> create a new instance of bundle, add data and then invoke callback. Also, createPlanListener is nullable, so you should add a check for that as well.

Blank fragment after activity recreated

I have an Activity with a ViewPager and TabLayout. I enabled "destroy activities" from Settings in my phone to simulate low memory.
I use getSupportFragmentManager because it's an Activity.
The first time I open the activity, I see my fragments. When I minimize my app and reopen it, I see the tabs but not the content. Inside fragments I call setRetainInstance(true).
Of course if I call super.onCreate(null); instead of super.onCreate(savedInstanceState); it's working fine because the activity is being recreated at all.
If I use FragmentStatePagerAdapter the content is ok but the menu displays duplicated items.
So please, don't suggest FragmentStatePagerAdapter (want all fragments visible), getChildFragmentManager (ViewPager is in an Activity), setRetainInstance (already using it).
public class SystemActivity extends LoadingActivity {
#BindView(R.id.pager)
ViewPager viewPager;
#BindView(R.id.tab_layout)
TabLayout tabLayout;
#BindView(R.id.toolbar)
Toolbar toolbar;
int[] ICONS = {
R.drawable.ic_tab_general,
R.drawable.ic_tab_details
};
int[] TEXTS = {
R.string.general,
R.string.details,
};
private CustomPagerAdapter customPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetch();
}
protected void fetch() {
super.fetch();
final Long systemId = getIntent().getLongExtra(Constants.Intent.SYSTEM_ID, 0);
this.realm = Realm.getDefaultInstance();
this.call = ApiClientHelper.getInstance(this).getSystem(systemId);
call.enqueue(new ApiUICallback<System>(this) {
#Override
public void onError(int code, String message) {
System system = realm.where(System.class).equalTo("id", systemId).findFirst();
if (system == null) {
fail();
} else {
init(system);
}
}
#Override
public void onSuccess(System system) {
realm.beginTransaction();
realm.copyToRealmOrUpdate(system);
realm.commitTransaction();
init(system);
}
});
}
private void init(System system) {
setContentView(R.layout.activity_system);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
customPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), system);
viewPager.setOffscreenPageLimit(TEXTS.length);
viewPager.setAdapter(customPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
CharSequence title = customPagerAdapter.getPageTitle(0);
getSupportActionBar().setTitle(title);
for (int i = 0; i < ICONS.length; i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(R.layout.tab_view);
((ImageView) tab.getCustomView().findViewById(R.id.icon)).setImageResource(ICONS[i]);
}
tabLayout.setOnTabSelectedListener(
new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
CharSequence title = customPagerAdapter.getPageTitle(tab.getPosition());
getSupportActionBar().setTitle(title);
hiddenKeyboard();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
hiddenKeyboard();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
hiddenKeyboard();
}
}
);
}
private void hiddenKeyboard() {
View focus = getCurrentFocus();
if (focus != null) {
focus.clearFocus();
InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.hideSoftInputFromWindow(focus.getWindowToken(), 0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class CustomPagerAdapter extends FragmentPagerAdapter {
private System system;
public CustomPagerAdapter(FragmentManager fm, System system) {
super(fm);
this.system = system;
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case 0:
fragment = new SystemGeneralFragment();
break;
case 1:
fragment = new SystemDetailsFragment();
break;
default:
return null;
}
Bundle bundle = new Bundle();
bundle.putLong(Constants.Intent.SYSTEM_ID, this.system.getId());
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return TEXTS.length;
}
#Override
public CharSequence getPageTitle(int position) {
return getResources().getString(TEXTS[position]);
}
}
}
And one of my fragments:
public class SystemGeneralFragment extends MyFragment {
#BindView(R.id.progress)
View progress;
#BindView(R.id.progress_background)
View progressBackground;
#BindView(R.id.progress_percentage)
TextView percentage;
protected Call call;
protected Realm realm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
realm = Realm.getDefaultInstance();
}
#Override
public void onDestroyView() {
if (this.call != null) {
this.call.cancel();
}
super.onDestroyView();
}
#Override
public void onDestroy() {
realm.close();
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_system_general, container, false);
ButterKnife.bind(this, view);
System system = realm.where(System.class).equalTo("id", getArguments().getLong(Constants.Intent.SYSTEM_ID)).findFirst();
System.Status status = system.getStatus();
percentage.setText(String.format("%d%%", status.getProgress()));
setProgress(progress, status.getColor(getContext()));
setProgress(progressBackground, ContextCompat.getColor(getContext(), R.color.light_gray));
return view;
}
private void setProgress(View view, int color) {
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius(16);
shape.setColor(color);
if (Build.VERSION.SDK_INT >= 16) {
view.setBackground(shape);
} else {
view.setBackgroundDrawable(shape);
}
}
}

Android: Fragments in FragmentPagerAdapter do not display data in landscape after device turned on

I had created tabview with swipe using Fragments and FragmentPagerAdapter. In the fragment's hosting activity, I had added a fragment and that fragment shows tabview using TabHost. 1st tab has a listview that displays data from DB using CursorLoader and the 2nd one is mapView.
Everything works fine in portrait mode.
Problem occurs in following case:
User is using app in landscape mode. He opened tabbed view screen. Data is displayed in the listview from the cursor loader. Mapview is also displayed in the second tab. So far everything is working as required.
He left the app as is.(Means, he did not pressed back button, home button or switched to another app)
Screen went off after some time.
When user unlocks the device, my app's tabbed view will be visible again. But,now listview does not show any data and mapview also disappeared.
ClientListFragment
public class ClientListFragment extends SwipeRefreshListFragment {
private static final String TAG = "ClientListFragment";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate");
setHasOptionsMenu(true);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setColorScheme(R.color.gplus_color_1, R.color.gplus_color_2,
R.color.gplus_color_3, R.color.gplus_color_4);
}
#Override
public void onResume() {
super.onResume();
Log.e(TAG, "onResume");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e(TAG, "onActivityCreated");
}
#Override
public void onPause() {
// Log.i(TAG, "onPause");
super.onPause();
}
#Override
public void onStop() {
super.onStop();
Log.e(TAG, "onStop");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy");
}
}
Map Fragment
public class ClientMapFragment extends Fragment {
private static final String TAG = "ClientMapFragment";
private GoogleMap googleMap;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.map_fragment, container, false);
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.setMyLocationEnabled(true);
return v;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onPause() {
super.onPause();
}
}
Activity
public class ClientActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean isTablet = getResources().getBoolean(R.bool.isTablet);
if (isTablet)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setContentView(R.layout.activity_clients);
ClientFragment clientFragment = new ClientFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("ShouldChangeActionBarTitle", true);
clientFragment.setArguments(bundle);
getFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clientFragment,
getResources().getString(R.string.clients_fragment))
.commit();
}
}
FragmentpagerAdapter
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
private static final String TAG = "TabsPagerAdapter";
private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
FragmentManager fm;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
this.fm = fm;
mFragments.add(new ClientListFragment());
mFragments.add(new ClientMapFragment());
}
#Override
public Fragment getItem(int index) {
Log.e(TAG, "getItem");
return mFragments.get(index);
}
#Override
public int getCount() {
return mFragments.size();
}
}
Update 1
So, after doing hours of research I came to a conclusion that, it is problem with fragment's state in the FragmentPagerAdapter. When screen is turned off fragmentpager's saveState is called.. When the device is unlocked again, fragment's will be restored from previous state. I verified that LoaderManager callbacks are called, and data was also fetched from DB. But, didn't appeared on screen.
I didn't even bothered about looking at my activities code at once. Everytime, a new fragment was created in onCreate(). The fix is very simple.
if (savedInstanceState == null) {
Log.e(TAG, "onCreate savedInstanceState == null");
ClientFragment clientFragment = new ClientFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("ShouldChangeActionBarTitle",
shouldChangeActionBarTitle);
clientFragment.setArguments(bundle);
getFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clientFragment,
getResources().getString(R.string.clients_fragment))
.commit();
}

Android viewpager AsyncTask finish when page changed

I have view pager. My viewpager contains 3 fragments. In the first fragment I have an AsyncTask class. I parsed JSON with AsyncTask and I can show it in listview. (everything is ok)
I have one problem AsyncTask which I have in the first fragment does not finish when I go to the next fragments. When I am in the second fragment my AsyncTask is also running. How can I write code to cancel my AsyncTask when viewpager's page changed?
This is my source (this is the first fragment source; another fragment source is the same but the only difference is the Server Url):
public class StradaChefs1 extends Fragment {
public static CustomerStatistic stat;
private ConnectionDetector con;
private AlertDialogManager alert = new AlertDialogManager();
#SuppressLint("ClickableViewAccessibility")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chefs_1, container,
false);
stat = new CustomerStatistic();
con = new ConnectionDetector(getActivity());
if (!con.isConnectingToInternet()) {
alert.showAlertDialog(getActivity(),
"You have not internet connection");
} else {
stat.execute("my urlllllllll"); // geo
}
return rootView;
}
public class CustomerStatistic extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(), "Please Wait... ",
"Loading... ");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray mainJson = new JSONArray(result);
String first = mainJson.getString(0);
JSONObject jobject = new JSONObject(first);
String image = jobject.getString("image");
String String_title = jobject.getString("title");
String String_name = jobject.getString("name");
String String_desc = jobject.getString("description");
String second = mainJson.getString(1);
} catch (JSONException e) {
e.printStackTrace();
}
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
#Override
public void onResume() {
Log.e("DEBUG", "onResume of HomeFragment");
super.onResume();
}
#Override
public void onStop() {
super.onStop();
if (stat != null && stat.equals(AsyncTask.Status.RUNNING)) {
stat.cancel(true);
Toast.makeText(getActivity(), "finished", Toast.LENGTH_SHORT)
.show();
}
}
}
This is a viewpager java code
public class TabbedActivity1 extends Fragment {
private StradaChefs1 mfragment1;
private StradaChefs2 mfragment2;
private StradaChefs3 mfragment3;
private StradaChefs4 mfragment4;
SectionsPagerAdapter mSe;
public static final String TAG = TabbedActivity1.class.getSimpleName();
ViewPager mViewPager;
private ArrayList<Fragment> fragmentList;
public static TabbedActivity1 newInstance() {
return new TabbedActivity1();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_item_one_1, container, false);
mSe=new SectionsPagerAdapter(getChildFragmentManager());
mViewPager = (ViewPager) v.findViewById(R.id.pager1);
CirclePageIndicator circle=(CirclePageIndicator)v.findViewById(R.id.circleindicator1);
mViewPager.setAdapter(mSe);
circle.setViewPager(mViewPager);
mfragment1 = new StradaChefs1();
mfragment2 = new StradaChefs2();
mfragment3 = new StradaChefs3();
mfragment4 = new StradaChefs4();
fragmentList = new ArrayList<Fragment>();
fragmentList.add(mfragment1);
fragmentList.add(mfragment2);
fragmentList.add(mfragment3);
fragmentList.add(mfragment4);
mViewPager.setPageTransformer(false, new PageTransformer() {
#Override
public void transformPage(View page, float position) {
page.setRotationY(position * -40);
}
});
return v;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
return null;
}
}
}
How can I solve this problem?
The FragmentPagerAdapter keeps additional fragments, besides the one shown, in resumed state, so you can't use onPause and onResume for starting/stopping the AsyncTask. The solution is to implement a custom OnPageChangeListener and create a new method for when the fragment is shown.
1) Create LifecycleManager Interface The interface will have two methods and each ViewPager’s Fragment will implement it. These methods Are as follows:
public interface FragmentLifecycle {
public void onPauseFragment();
public void onResumeFragment();
}
2) Let each Fragment implement the interface
3) Implement interface methods in each fragment - in onPauseFragment stop the AsyncTask, in onResumeFragment start it
4) Call interface methods on ViewPager page change You can set OnPageChangeListener on ViewPager and get callback each time when ViewPager shows another page
5) Implement OnPageChangeListener to call your custom Lifecycle methods
Listener knows the new position and can call the interface method on new Fragment with the help of PagerAdapter. I can here call onResumeFragment() for new fragment and onPauseFragment() on the current one.
I need to store also the current fragment’s position (initially the current position is equal to 0), since I don’t know whether the user scrolled from left to right or from right to left. See what I mean in code:
private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
int currentPosition = 0;
#Override
public void onPageSelected(int newPosition) {
FragmentLifecycle fragmentToShow = (FragmentLifecycle)pageAdapter.getItem(newPosition);
fragmentToShow.onResumeFragment();
FragmentLifecycle fragmentToHide = (FragmentLifecycle)pageAdapter.getItem(currentPosition);
fragmentToHide.onPauseFragment();
currentPosition = newPosition;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
};
I didn't write the code. Full tutorial here
When you start the asynctask set the flag isRunning=true
when you are trying to jump from one fragment to other it mean
as per fragment lifecycle your are pausing and stoping your current fragment
so in onStop method of fragment you can check isRunning flag of asynctask is true if yes the
cancel the asyntask
its my logic hope it will help you to achieve your requirement

How to call notifydatasetchanged when using SherlockFragmentActivity and ListFragments

I have a Sherlock Tab Navigation implemented as the following two classes. Class Dashboard is the main activity. Class DashboardContacts represents one of the tab's fragment.
I am loading HTTP data that gets loaded in a while and when it loads I need the list view in DashboardContacts to reflect the changes brought in from Server and refresh the ListView from blank to filled list. For this i'm calling notifyDataSetChanged method through refresh method in DashboardContacts, but no change relects in ListView until I change the tabs.
public class Dashboard extends SherlockFragmentActivity {
private DashboardContacts contactsTab=new DashboardContacts();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab = getSupportActionBar().newTab();
tab.setText(getResources().getStringArray(R.array.dashboardTabs)[0]);
tab.setTabListener(new DashboardHome());
getSupportActionBar().addTab(tab);
ActionBar.Tab tab2 = getSupportActionBar().newTab();
tab2.setText(getResources().getStringArray(R.array.dashboardTabs)[1]);
tab2.setTabListener(contactsTab);
getSupportActionBar().addTab(tab2);
//CALLS ASYNCLOADER HERE TO LOAD HTTP DATA
}
private void httpSuccessMethod() {
//Does some work and then calls:
contactsTab.refresh(datasource.getAllContacts());
}
Here is the DashboardContacts class layout:
public class DashboardContacts extends SherlockListFragment implements ActionBar.TabListener{
private UserListAdapter listAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
listAdapter=new UserListAdapter(container.getContext(), ApplicationState.getInstance(container.getContext()).getUserCache());
setListAdapter(listAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onTabSelected(Tab tab,android.support.v4.app.FragmentTransaction ft) {
ft.replace(android.R.id.content, this,"contacts");
ft.attach(this);
}
#Override
public void onTabUnselected(Tab tab,android.support.v4.app.FragmentTransaction ft) {
ft.detach(this);
}
#Override
public void onTabReselected(Tab tab,android.support.v4.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public void refresh(List<User> list) {
if(this.listAdapter != null) {
this.listAdapter.setList(list);
this.listAdapter.notifyDataSetChanged();
}
}
The refresh method in the custom list adapter looks like, so I am actually changing the data there too:
public void refresh(List<User> list) {
if(this.listAdapter != null) {
this.listAdapter.setList(list);
this.listAdapter.notifyDataSetChanged();
}
I think this is something I didn't implement, so I did it now and solved the issue:
public void setList(List<ExpensePool> list) {
clear();
addAll(list);
notifyDataSetChanged();
}

Categories

Resources