0

<summary>

Is there an elegant way of getting the result of an activity from a non-activity class, or is it always going to be a hack? Would I be better avoiding that situation if possible?

</summary>

I have an activity, that has an instance of a session for a web service, which will generally be pre-authenticated (the session key will be saved in SharedPreferences). However, the first time it runs, I will need to pop up a log in activity, which will return the username and password to the session, which will then talk to the server and get a session key.

Ideally, I would like to have the non-activity session class call startActivityForResult, but I'm not sure it's possible. I've seen various questions about how it can be done:

How to get the result from OnActivityResult inside another class?(outside of the activity

use startActivityForResult from non-activity

But they all seem a little hacky. I've also seen this, which suggests that passing round contexts is not the best idea anyway:

http://android-developers.blogspot.co.uk/2009/01/avoiding-memory-leaks.html

Another option is to save the username and password to sharedpreferences and retrieve it in the other class, but then I'd have to have some way of figuring out when it had been saved, and it all seems to be getting rather messy.

Another option is to make the session a non-displaying activity. Seems like a large overhead though.

My project is still in planning stages, so I'm after best practice. What is the most elegant way to do this?

Community
  • 1
  • 1
spookypeanut
  • 503
  • 1
  • 6
  • 24
  • Please write to the point. It seems very descriptive, no one will read this whole crap!!!! – Bhavik Ambani Dec 21 '14 at 14:45
  • A vote down for too much information seems rather harsh: you've ensured nobody will ever read it now, by giving it negative marks. – spookypeanut Dec 21 '14 at 15:00
  • My dear friend, I have not downvoted your question, I generally never downvote the question what so ever the question is, if I dont like then I put on one comment as I placed here. So my dear friend, i have not downvoted your question. – Bhavik Ambani Dec 21 '14 at 15:02
  • Apologies, I jumped to conclusions. I'll try to edit a summary to the top of the post later, so that people who are interested can still see all of the info, but it's not too daunting for those without much time. – spookypeanut Dec 21 '14 at 15:06

1 Answers1

0

I would use an event bus (e.g. Otto, GreenRobot) to communicate the result from the activity to the non-activity.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • Thanks for the suggestion, I'll investigate those. My initial thought is that they're an even larger overhead than making my session an activity though! I can't foresee another point in my app when I might need an event bus. – spookypeanut Dec 21 '14 at 15:04