0

When I start my app I show a splashscreen where I show my logo and in the background I'm getting the GPS coordinations (latitude and longitude). Afterwards it goes to my MainFragmentActivity where I set my viewpager, FragmentManager and MyFragmentPagerAdapter. I set the fragments up in MyFragmentPagerAdapter. And that is my problem, I can't seem to get the GPS coordinations to my fragment.

A brief summary: GPS coordinations are calculated in the splashscreen, after splashscreen is done MainFragmentActivity opens up and everything is being setted up so my viewpager works. Then I want to be able to access those GPS coordinations that are calculated in my splashscreen in my fragments. I tried passing them by extra, but my fragment isn't being opened by an intent startActivty. So I'm stuck here.

SplashScreen

//Calculating GPS coordinations ...

     CountDown tik;
     tik = new CountDown(3000, 1000, this, MainActivity.class);
     tik.start();
     StartAnimations();

CountDown

//After SplashScreen is done, start MainActivity
public class CountDown extends CountDownTimer{
    private Activity myActivity;
    private Class myClass;

    public CountDown(long millisInFuture, long countDownInterval, Activity act, Class cls) {
        super(millisInFuture, countDownInterval);
        myActivity = act;
        myClass = cls;
    }

    @Override
    public void onFinish() {
        myActivity.startActivity(new Intent(myActivity, myClass));
        myActivity.finish();
    }

    @Override
    public void onTick(long millisUntilFinished) {}
}

MainActivity

//Setting viewpager up

public class MainActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Tried getting coordinations like this and then passing it to fragment, but didn't succeed.
        /*Bundle extras = getIntent().getExtras();
        myLat = Double.toString(extras.getDouble("lat"));
        myLong = Double.toString(extras.getDouble("lng"));*/

        /** Getting a reference to the ViewPager defined the layout file */
        final ViewPager pager = (ViewPager) findViewById(R.id.pager);

        /** Getting fragment manager */
        FragmentManager fm = getSupportFragmentManager();

        /** Instantiating FragmentPagerAdapter */
        MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);

        /** Setting the pagerAdapter to the pager object */
        pager.setAdapter(pagerAdapter);

        pager.setPageTransformer(true, new ZoomOutPageTransformer());

        PageListener pagelistener = new PageListener();
        pager.setOnPageChangeListener(pagelistener);
}

MyFragmentPagerAdapter

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{

    final int PAGE_COUNT = 6;

    /** Constructor of the class */
    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    /** This method will be invoked when a page is requested to create */
    @Override
    public Fragment getItem(int arg0) {

        switch(arg0){

        case 0:

            return new FragmentOne();           

        case 1:
            return new FragmentTwo();

        case 2:
            return new FragmentThree();

        case 3:
            return new FragmentFour();

        case 4:
            return new FragmentFive();

        case 5:
            return new SettingsFragment();          

        default:
            return null;

        }       
    }

    /** Returns the number of pages */
    @Override
    public int getCount() {
        return PAGE_COUNT;
    }    
}

**Example of a Fragment, in this instance I just used FragmentOne

public class FragmentOneextends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        //Want to be able to access those coordinations here.
        View v = inflater.inflate(R.layout.frag_one, container, false);
    }
}

LocationHelper

    public class LocationHelper extends Activity{
        private static LocationHelper mInstance = new LocationHelper();
        private LatLng mLocation;
        public static double location_latitude;
        public static double location_longitude;
        LocationManager locationManager;
        LocationListener locationListener;

        private LocationHelper() {
        super();
            // start getting location
     // Acquire a reference to the system Location Manager
            locationManager = (LocationManager) this
                    .getSystemService(Context.LOCATION_SERVICE);
    //If I remove 'extends Activity, then I get this error: The method getSystemService(String) is undefined for the type LocationHelper

            // Define a listener that responds to location updates
            locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                    // Called when a new location is found by the network location
                    // provider.
                    location_latitude = location.getLatitude();
                    location_longitude = location.getLongitude();

                    Log.v("Location", "set" + location.getLatitude());

                    if (location.getLatitude() != 0.0) {
                        Log.v("Location", "stop looking");
                        locationManager.removeUpdates(locationListener);

                        FileOutputStream fos;
                        try {
//Getting the same error here The method openFileOutput(String, int) is undefined for the type new LocationListener(){}
                            fos = openFileOutput("my_latitude", Context.MODE_PRIVATE);
                            fos.write((""+location_latitude).getBytes());
                            fos.close();

                            fos = openFileOutput("my_longitude", Context.MODE_PRIVATE);
                            fos.write((""+location_longitude).getBytes());
                            fos.close();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        Log.v("Location", "keep looking");
                    }
                }

                public void onStatusChanged(String provider, int status,
                        Bundle extras) {
                    Log.v("Location", provider + ", " + status + " Status changed");
                }

                public void onProviderEnabled(String provider) {
                    Log.v("Location", provider + " onProviderEnabled");
                }

                public void onProviderDisabled(String provider) {
                    Log.v("Location", provider + " onProviderDisabled");
                }
            };
        }

        public static LocationHelper getInstance() {
            return mInstance;
        }

        public LatLng getLocation() {
            return mLocation;
        }

    }
mXX
  • 3,595
  • 12
  • 44
  • 61

2 Answers2

1

The problem is that you're not putting the lat and lon in the Intent you're using to start your activity. You'd need something like this:

@Override
public void onFinish() {
    Intent intent = new Intent(myActivity, myClass);
    intent.addExtra("lat", latitude);
    intent.addExtra("lon", longitude);
    myActivity.startActivity(intent);
    myActivity.finish();
}

To pass the data from your Activity to your Fragment you need to call setArguments(Bundle args) on your Fragment and then pass in the Bundle you get from the Intent. Something like this:

myFragment.setArguments(getIntent().getExtras());
CaseyB
  • 24,780
  • 14
  • 77
  • 112
  • I was able to send data from splashscreen to mainActivity, but how do I send from mainActivity to my fragment? Because basically the mainActivty is just setting the viewpager up. – mXX Jun 05 '13 at 14:42
  • Where exactly should I call `setArguments(Bundle args)`? In my MainActivity or MyFragmentPagerAdapter or the fragment itself? – mXX Jun 05 '13 at 19:26
  • Call it in the `Activity` on the `Fragment` – CaseyB Jun 05 '13 at 20:09
  • I've added the line `FragmentOne.setArguments(getIntent().getExtras());`in my `FragmentOne()` But gives me error The method getIntent() is undefined for the type FragmentOne. Maybe possible to get your support in chat? Think will be easier. – mXX Jun 05 '13 at 20:19
  • Call it IN the ACTIVITY ON your FRAGMENT – CaseyB Jun 05 '13 at 20:28
  • Can you give me some more support please? – mXX Jun 06 '13 at 11:22
  • In your Activity get a reference to your Fragment and then call: `FragmentOne.setArguments(getIntent().getExtras());` Then in your Fragment override the `setArguments()` method to accept the `Bundle` and parse it. – CaseyB Jun 06 '13 at 14:29
0

I would consider a solution that doesn't involve you passing around values to all your Activities and Fragments via Intents and Bundles all the time. Here's one such approach:

Make a singleton that encapsulates your location-related code:

public class LocationHelper {
    private static LocationHelper mInstance = new LocationHelper();
    private LatLng mLocation;

    private LocationHelper() {
    super();
        // start getting location
    }

    public static LocationHelper getInstance() {
        return mInstance;
    }

    public LatLng getLocation() {
        return mLocation;
    }

    /* ... */
}

Call LocationHelper.getInstance() when your app starts to initialize it and kick-start getting a location. Anytime you want to use the location, just get the singleton and call getLocation() on it. You can do this from anywhere.

LocationHelper helper = LocationHelper.getInstance();
LatLng location = helper.getLocation();
Karakuri
  • 38,365
  • 12
  • 84
  • 104
  • I think your methode is better. But can LocationHelper extend Activity, because I need that for some services like `locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);`? I'm also getting `LocationSingleton cannot be resolved to a type` – mXX Jun 05 '13 at 15:16
  • Sorry, there was a typo, fixed it. – Karakuri Jun 05 '13 at 15:34
  • The point of not extending Activity is that there will only ever be **one** single instance of LocationHelper throughout your app. You can always change `getInstance` and make it take a `Context` as an argument. If there were more than one, you would be running your location code every time another Activity is created, which is a waste. Also, you should really look into the new Google Play Services SDK and use the location APIs there; they're much improved over the old LocationManager APIs. – Karakuri Jun 05 '13 at 15:36
  • I'm dying to use the Google Play Services SDK, but for a strange reason I can't.. Check out this question I did http://stackoverflow.com/questions/16928956/adding-google-play-services-crashes-aapt-exe As of now still nobody answered on that question and I'm still having problems importing that. Maybe you can also answer that question? In my first post, I've added the class `LocationHelper` So you can check out what I mean. If I don't extend Activity then There are errors. So I think I'm really out of options here? Check out the first post, the last section – mXX Jun 05 '13 at 18:32
  • 1
    No, don't make it extend Activity. If you need to, make the getInstance() method take a Context so you can initialize your LocationManager, but otherwise this is supposed to be a Singleton. – Karakuri Jun 05 '13 at 20:21