0

I got a complicated problem involving a ListView and some Intents on Android:

I have a ListActivity which contains many items. From another Activity, lets call it CallingActivity, I want to launch this ListActivity and scroll to a specific item. In the ListActivity some other Activites can be launched, lets call them AnotherActivity.

My current implementation is to store the item to which the ListActivity should scoll in the intent and then use the following code in the onStart() method.

if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_EVENTNR)) {
        int p = getIntent().getExtras().getInt(EXTRA_EVENTNR);
        getListView().clearFocus();
        getListView().post(new Runnable() {
            @Override
            public void run() {
                getListView().setSelection(p);
            }
        });
    }

This solution has a huge drawback:

Suppose the following call-sequence:

  1. CallingActivity launches ListActivity with Intent [EVENTNR=123]
  2. ListActivity recieves the intent and scrolls to the right position.
  3. User continues to read and scrolls further down.
  4. AnotherActivity is launched from ListActivity
  5. The User presses the Back-Button
  6. The old intent (from 1.) is still present and gets passed again in onStart of the ListActivity.
  7. ListActivity scrolls to the same position again (same as in 2.)
  8. Scrolling of the User from 3. is lost

I think a Intent is the wrong solution for carrying the scroll-information. Intents are more for the contents of a activity and not for its display.

Is there another solution for passing the scrolling information which only gets applied once? Did I miss something?

theomega
  • 31,591
  • 21
  • 89
  • 127
  • It could be possible using BroadcastReceivers: http://stackoverflow.com/questions/2282435/inform-activity-from-a-broadcastreceiver-only-if-it-is-in-the-foreground – Moss Mar 21 '12 at 12:07

1 Answers1

1

What if you do getIntent().removeExtra() to remove your extra data?

On the other hand it might be that putting the info into the Intent is an unnesessary complication as you don't really need an Intent for that. Can it be a plain java object to store that info with API to set and reset it?

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
  • Thanks for the `removeExtra` hint. Anyway, could you explain what do you mean by `API to set and reset`? How can I send the value where to scroll from `CallingActivity` to `ListActivity? – theomega Mar 21 '12 at 11:01
  • Oh, I just thought what is causing troubles is the Intent because it's always there. So I just meant maybe create a plain Java class like ScrollInfo with methods set(int pos) and clear() and pass that instead of Intent. Same as removeExtra() though... – Alexander Kulyakhtin Mar 21 '12 at 11:30