0

I'm very new to Android programming (and Java for that matter) coming from an iOS background. What I am trying to do, is pass a pointer to a Fragment from one Activity to another.

Basically, I have a starting activity called BeginActivity that handles a couple of Fragments for login and register screens. Once logged in, I load up the main activity of the app called TabsFragmentActivity using this code:

public void loggedIn() {
    Intent intent = new Intent(this, TabsFragmentActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    this.startActivity(intent);

    finish();
}

I'm using FLAG_ACTIVITY_CLEAR_TOP as I dont want the user to go back without actually logging out first.

Now the problem:

In BeginActivity I have a pointer to a fragment that holds the users data. I am using it like a singleton, that the first few view fragments can access from BeginActivity.

I need to pass this same object to the new TabsFragmentActivity before I call finish() on it.

How do I do this? I know I can use putExtra() but I believe that is just for strings etc.. and not other Fragments.

Is there a way in the newly created TabsFragmentActivity that I can reference the BeginActivity to 'grab' the pointer?

Thanks

Darren
  • 10,182
  • 20
  • 95
  • 162
  • YOU CANNOT USE one Activity reference in other Activity ... Activity canot be use as singleton ... you can use Application class ... but still there are better ways for doing it (not using singletons at all - Content providers, Shared preferences, Intent extras, ...) – Selvin Apr 11 '13 at 11:36

2 Answers2

1

Basically you need to be able to pass your class via the intent, look at Serializable / Parcelable interfaces

This question has the answer you require

How to pass an object from one activity to another on Android

Community
  • 1
  • 1
gheese
  • 1,170
  • 1
  • 11
  • 17
1

First of all, you should be sure about Fragments and Activity life cycle.

Fragments are designed to be reusable UI complex components. They look like activity, but you can reuse. So,you can have as many activities you need containing the same fragments, but not the same instances of these fragments.

If you just want to pass you user data for another activity you must use Bundle and putExtra(). Depending of the user data type can be necessary implements Serializable or Parcelable Interfaces, as @gheese said.

If you want to use the same UI appearence of your fragment on two or more activities, besides use Bundle and putExtra. Each activity that you want this behavior must contains a field whose is a Fragment and in the moment of starting this fragment you can use getActivity().getIntent().getExtra to get the user information and populate your fragment.

Bruno Mateus
  • 1,727
  • 18
  • 25