Monday, November 19, 2012

Irritating things I seem to forget how to do (Android Version)

So one of the most basic things you can do in Android is start a new intent it is super simple (this is not what I forget - I'll get to that in a minute):


Intent i = new Intent(this, AwesomeIntent.class);
startActivity(i);

See? very simple.  Now if you want to pass data back from an activity that you just created you have to start the Inent slightly different:

Intent i = new Intent(this, AwesomeIntent.class);
startActivityForResult(i, REQUEST_CODE_FOR_MY_INTENT);

Even that was pretty easy wasn't it?  

It doesn't take long though before you want to pass information into an intent, and of course you have to return data from the intent (and process it as well).  Here is how you do that:

Intent i = new Intent(this, AwesomeIntent.class);
i.putExtra(Key, Value);

The documentation says that should work however this seems to work better:

Intent i = new Intent(this, AwesomeIntent.class);
Bundle b = new Bundle();
b.putString("KEY", "VALUE");
i.putExtras(b);

startActivity(i);


You can get that extra data you passed in (often in the onCreate method) like this:

Bundle b = getIntent().getExtras();
magicKey = b.getString(key);

Now the whole reason I created the post when you are in an Activity that was created by a "startActivityForResult".  Inside the method where your activity finishes up just do this:

Intent intent = this.getIntent();
intent.putExtra("SOMETHING", "EXTRAS");
this.setResult(RESULT_OK, intent);
finish();

And lastly the class that started it all needs to implement this method:

protected void onActivityResult(int requestCode, int resultCode, Intent intentData) 
{
   if (requestCode == REQUEST_CODE_FOR_MY_INTENT)
   {
     //do some cool stuff here
   }
}


Pretty simple basic stuff - but for whatever reason I always seem to have to look it up.

Happy Coding!

-Aaron

No comments: