I'm new to Android, so I might be missing something. I'm writing a "login" Activity. The Activity returns security tokens for the app to use later on.
Everything works fine. What I don't quite like is the protocol used to return the results:
In essence, my Login Activity is used like this:
...
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent authActivity = new Intent(context,
AuthenticationActivity.class);
authActivity.putExtra("clientId","MY CLIENT ID");
startActivityForResult(authActivity, AuthenticationActivity.AUTH_REQUEST_COMPLETE);
}
});
Then, I retrieve the results through the onActivityResult
method:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent authActivityResult) {
super.onActivityResult(requestCode, resultCode, authActivityResult);
switch(requestCode)
{
case AuthenticationActivity.AUTH_REQUEST_COMPLETE:
if(resultCode==RESULT_OK)
{
access_token =authActivityResult.getStringExtra(AuthenticationActivity.ACCESS_TOKEN)); ...
Is this the way it is supposed to be done? Or is there a better way? For example, I would like to return a Type instead of using a property bag. That has many advantages (e.g. easier refactoring, compile time checks, etc)
Roughly, I would like to see something like (pseudocode):
startActivityForResult<MyResult>(authActivity, new OnResultHandler() {
@Override
void HandleResult( MyResult r )
{
....
}
});
Would love to hear what Android experts think!
I'm sure we all have things in Android that we would have done in a different way. This is the same with all operating systems, programming languages, political systems, economic systems, religions, etc.
However, if you want to program for Android you are pretty much stuck with using what is there.
To answer your question, you don't have a to use a "property bag" to return stuff to the calling activity. You can put any object you want into the returned Intent
as an extra, as long as it implements either Parcelable
or Serializable
.
For example, assuming that MyResult
implements Parcelable
, your AuthenticationActivity
could return the result like this:
Intent resultIntent= new Intent();
resultIntent.putExtra(RESULT, myResult);
setResult(RESULT_OK, resultIntent);
finish();
and the calling activity could extract MyResult
like this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent authActivityResult) {
super.onActivityResult(requestCode, resultCode, authActivityResult);
switch(requestCode)
{
case AuthenticationActivity.AUTH_REQUEST_COMPLETE:
if(resultCode==RESULT_OK)
{
MyResult result = authActivityResult.getParcelableExtra(AuthenticationActivity.RESULT));
Now you have a MyResult
object that you can do whatever you want with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With