Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9070213
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T17:37:47+00:00 2026-06-16T17:37:47+00:00

My setup is as follows. I have a FragmentPagerAdapter called from my Activity which

  • 0

My setup is as follows.

I have a FragmentPagerAdapter called from my Activity which loads two fragments. This is setup within onCreate.

In onResume I call an ASyncTask which loads data from a database, and then calls a callback in my activity onLoadComplete via a load data listener.

    @Override
public void onLoadComplete(JSONArray data) {
    // TODO Auto-generated method stub


    LocalFragment fragmentB = (LocalFragment)getSupportFragmentManager().findFragmentByTag(ListTag);
    fragmentB.setList(data);

    LMapFragment fragmentA = (LMapFragment)getSupportFragmentManager().findFragmentByTag(MapTag);

    GoogleMap our_map = fragmentA.getMap();
    fragmentA.plotP(myLocation,data);

}

The fragments are initialized by the Pager, and within each fragments code I set the respective tag e.g in LocalFragment

    @Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);

    String myTag = getTag();



        ((PagerTest) activity).setListTag(myTag);
        Log.d("what",myTag);


}

This allows me to access the fragment, call a function within it which populates a list or populates a map. It works.

What I am now trying to do is account for screen orientation changes.. If while the ASyncTask is running the orientation is changed, the app crashes.

As suggested here: Hidden Fragments I have been trying to implement a hidden fragment which saves the state of my ASyncTask. So what I have done is set it up so in onResume of my Activity i call a function

    static LoadDataFromURL the_data = null;
static JSONArray pub_data = null;
private static final String TAG = "RetainFragment";

public RetainFragment() {}

public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {

    RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
    if (fragment == null) {
        fragment = new RetainFragment();
        fm.beginTransaction().add(fragment, TAG).commit(); // add this
    }
    return fragment;
}

which essentially saves my data.

Basically what this means is that if i rotate my screen i dont call my ASyncTask again.. the screen just rotates.. it works perfectly.

If however I go back to the main menu and then click on the activity again the screen returns blank (but does not crash). My understanding is that the data is retained as an object in the fragment, but on reloading the activity afresh the data needs to be set again.. I.E onLoadComplete needs to be called to populate the list/map..

So i concluded that if initially after the ASyncTask completes i save the returned data in my hidden fragment onRetainInstance, then i could simply call onLoadComplete and pass it..

The problem is, in this situation seemingly the fragment has not been called yet, as such the tags are null, and calling the callbacks within onLoadComplete crashes the app.

I have been banging my head over this for ages.

My ASyncTask is in a seperate class: LoadDataFromURL
What i want to achieve is as follows – a fragmentviewpager whereby on screen rotate the ASyncTask is retained on rotate/attached to the new activity, and if it has completed before it shouldn’t be run again..

Could anyone advise.

Many Thanks

EDIT

Having changed the variables in my secret fragment to public variables, everything has seemingly come together.. BUT because im not 100% sure how/when things are called, I dont fully understand WHY it works..

So.. I call findOrCreateRetainFragment and it either creates a new ‘secret’ fragment or returns the current instance.

If it is returning a current instance, i dont call my async task again. If it is not, I call my asynctask and load the data.

With this setup, when i load the activity and rotate the screen, it rotates as expected woop.

Now, when i go back to the main menu and then click the activity again, it calls the async task.

My understanding is that on rotate the async task is not called again, and the viewpager is somehow saving the fragments.

On the other hand, when i go back my activity is destroyed, as is my secret fragment, and as such when i click on it again it loads the data. THis is essentially what i want..

Have i understood this correctly?

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T17:37:49+00:00Added an answer on June 16, 2026 at 5:37 pm

    There are a few issues here that you’re experiencing (I think).

    First of all, the reason your callbacks crash is because they’re attached to an old Activity that no longer “exists” after a screen orientation and/or Activity push. If you use onAttach() to attach a callback to your fragment, you must use onDetach() to detach that callback when the Fragment is removed from the Activity. Then, whenever you call the callback, check for a null so you don’t send data to a dead object.

    Basically, the logic you’re trying to use here is:

    1. Start Activity.

    2. Check if your Fragment exists. If it does, grab it. Else, create it.

    3. Retrieve the data if it exists. If not, wait for the callback.

    Because of the nature of callbacks (depending on your implementation), you will not receive data until the event fires. However, if the Activity is gone and the event has already fired, the callback won’t execute. Thus, you have to retrieve the data manually. When using setRetainInstance(), it’s helpful to think of it as this entity detatched from your Activity. It will exist as long as you don’t pop the current Activity or push a new Activity. However, your current Activity will be destroyed upon screen orientation changes while the Fragment won’t. As such, the Fragment shouldn’t rely on the existence of the Activity.

    A much more elegant solution to the problem that you may want to look in to is implementing the Android Loader API. Loaders are handy tools that are handled by the system that work is roughly the same way but are more in-tune with asynchronously retrieving data. They work effectively the same way. You simply start your loader and the system with either create one if it doesn’t exist or re-use one that already exists. It will remain in the system by the LoaderManager upon configuration changes.

    EDIT:

    To answer your edit, I guess I’ll explain what’s happening. It’s convoluted, so just tell me if anything needs clarification.

    Fragments aren’t technically speaking part of your currently running Activity. When you create an instance of the Fragment, you have to call beginTransation() and commit() on the FragmentManager. The FragmentManager is a singleton that exists within the realm of your application. The FragmentManager holds on to the instance of the Fragment for you. The FragmentManager then attaches the Fragment to your Activity (see onAttach()). The Fragment then exists within the FragmentManager which is why you never really have to hold a reference to it within your application. You can just call findFragmentByTag/Id() to retrieve it.

    Under normal circumstances, when your Activity is being destroyed, the FragmentManager will detach the instance of your Fragment (see onDetach()) and just let it go. The Java garbage collect will detect that no reference to your Fragment exists and will clean it up.

    When you call setRetainInstace(), you’re telling the FragmentManager to hold on to it. Thus, when your Activity is being destroyed on a configuration change, the FragmentManager will hold on to the reference of your Fragment. Thus when your Activity is rebuilt, you can call findFragmentByTag/Id() to retrieve the last instance. So long as it didn’t keep any context of the last Activity, there shouldn’t be any problems.

    Traditionally, one would use it to keep references to long standing data (as you are) or to keep connection sockets open so a phone flip doesn’t delete it.

    Your ViewPager has nothing to do with this. How it retrieves the Fragments is completely dependent on how you implement that Adapter that it’s attached to. Usually, retained Fragments don’t have Views themselves because Views hold Context data of the Activity they were created in. You would just basically want to make it a data bucket to hold on to the data for the Views to pull from when they’re being inflated.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Pjs sketch, which looks as follows: void setup(){ //setup stuff among
I have a simple listview and listadapter setup as follows: listAdapter = new ArrayAdapter<MyDomainObject>(this,
I have a dict of dict setup as follows: from collections import namedtuple Point
Our setup as follows: We have a local development server running Ubuntu, with a
I have two classes set up as follows: class Point { protected: double coords[3];
I have an asynchronous UISearchBar setup as follows: Inherit UISearchDisplayDelegate & set it up
I have a MySQL table setup as follows: +---------------+-------------+------+-----+---------+----------------+ | Field | Type |
I have a form partial current setup like this to make new blog posts
Sorry, this is along one to document.. OLD SETUP I have a J2ME client
I currently have a repository setup that loads forms a person would need to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.