0

How can i get the path the end user takes to arrive at any activity.

so if user visited Activities A, B , C .. then in Activity c i would be able to get a info like this "A/B/C". And likewise if user took the path directly to D, F then in activity F i would have the path info of "D/F".

j2emanue
  • 60,549
  • 65
  • 286
  • 456

1 Answers1

0

Whenever you start an Activity you could pass it a string extra that states the path you're talking about. A quick example could be to have this method in an abstract base activity class and use it whenever starting a new Activity:

public <T extends Activity> void startActivityWithPathInfo(Class<T> activityClass) {
    String path = getIntent().getStringExtra("path");
    path = path == null ? "" : path += "/";
    path += this.getClass().getSimpleName();
    Intent i = new Intent(this, activityClass);
    i.putExtra("path", path);
    startActivity(i);
}

Then in each activity you could just get the current path by using:

String path = getIntent().getStringExtra("path");

Edit: Given your requirements, it's probably better to split this up into a "getPath()" method and a "startActivityWithPathInfo(Class)" method. Might be easier for you to retrieve the path in each Activity :)

Edit 2: As per comments, here is the updated code:

public abstract BaseActivity extends Activity {
    private static final String EXTRA_PATH = "path";

    private String path;

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            path = getPath();
        } else {
            path = savedInstanceState.getString(EXTRA_PATH, "");
        }
    }

    @Override protected void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);
         outState.putString(EXTRA_PATH, path);
    }

    public String getPath() {
        if (path == null) {
            path = getIntent().getStringExtra(EXTRA_PATH);
            path = path == null ? "" : path += "/";
            path += this.getClass().getSimpleName();
        }
        return path;
    }

    public <T extends Activity> void startActivityWithPathInfo(Class<T> activityClass) {
        Intent i = new Intent(this, activityClass);
        i.putExtra(EXTRA_PATH, getPath());
        startActivity(i);
    }
}
Bradley Campbell
  • 9,298
  • 6
  • 37
  • 47
  • but in your example what would happen if I hit the back button to reverse then I wouldn't be getting the right path – j2emanue Sep 29 '14 at 05:15
  • It would still be the right path. Each activity keeps a reference to the Intent that started it. However, you did just make me realise that this won't work if the system kills the Activity while it's in the background. I'll post an edit to fix this. – Bradley Campbell Sep 29 '14 at 07:34
  • Excellent. Owe you. This code is brilliant. Your brilliant. – j2emanue Sep 29 '14 at 17:19