将数据从Splashscreen传递到ViewPagerActivity到Fragment

时间:2013-06-05 14:29:43

标签: android android-intent android-fragments android-viewpager

当我启动我的应用程序时,我会显示一个闪屏,我会在其中显示我的徽标,并在后台我正在获得GPS协调(经度和纬度)。然后它进入我的MainFragmentActivity,我设置了我的viewpager,FragmentManager和MyFragmentPagerAdapter。我在MyFragmentPagerAdapter中设置了片段。这是我的问题,我似乎无法与我的片段进行GPS协调。

简要总结: 在完成启动画面后,会在启动画面中计算GPS协调,MainFragmentActivity会打开并且所有内容都已设置好,因此我的viewpager工作正常。然后我希望能够访问我的碎片中我的闪屏中计算的那些GPS协调。我试过额外传递它们,但我的片段没有被intent startActivty打开。所以我被困在这里。

闪屏

//Calculating GPS coordinations ...

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

倒计时

//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;
    }    
}

**片段的例子,在这个例子中我刚刚使用了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;
        }

    }

2 个答案:

答案 0 :(得分:1)

问题在于,您没有将lat和lon放在您用来开始活动的Intent中。你需要这样的东西:

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

要将Activity中的数据传递到Fragment,您需要在setArguments(Bundle args)上致电Fragment,然后传入您获得的Bundle Intent。像这样:

myFragment.setArguments(getIntent().getExtras());

答案 1 :(得分:0)

我会考虑一个解决方案,它不会让您一直通过Intents和Bundles将值传递给所有的Activity和Fragments。这是一种这样的方法:

创建一个封装与位置相关的代码的单例:

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;
    }

    /* ... */
}

当您的应用开始初始化并启动获取位置时,请致电LocationHelper.getInstance()。无论何时您想使用该位置,只需获取单身并在其上调用getLocation()即可。你可以从任何地方做到这一点。

LocationHelper helper = LocationHelper.getInstance();
LatLng location = helper.getLocation();