r/androiddev • • Nov 26 '16

Effective Java for Android (cheatsheet)

https://medium.com/rocknnull/effective-java-for-android-cheatsheet-bf4e3433889a
223 Upvotes

49 comments sorted by

View all comments

32

u/Plastix Nov 26 '16 edited Nov 26 '16

Static factory methods are really good for creating intents as well:

public class MyActivity {

	private static final String EXTRA_ARG = "SomeArg";
	
	public static Intent newIntent(Context context, String someArg){
		Intent intent = new Intent(context, MyActivity.class);
		intent.putString(EXTRA_ARG, someArg);

		return intent;
	}
}

Great writeup! Thanks for sharing.

10

u/ditn Google Developer Expert Nov 26 '16

There's a shortcut/postfix completion thing in Android Studio to do this for you. Type 'start' on a new line.

2

u/Plastix Nov 26 '16

Woah I didn't know this live template existed. Thanks!

4

u/ditn Google Developer Expert Nov 27 '16

Nor did I until a week ago! Turns out hitting CMD+J (iirc) lets you browse the templates in context, it's worth having a dig around for half an hour and seeing what's useful to you.

1

u/aselims Jan 26 '17

'starter' is the right one at AS2.2.3

16

u/Zhuinden Nov 26 '16

It's great when the static factory method is actually static

3

u/Plastix Nov 26 '16

Haha nice catch. I was typing a little too fast.

4

u/[deleted] Nov 26 '16

There is a lib called Henson that generates intent builders for activities from fields you have annotated. These fields can be automatically injected on the activity instance as well (works similarly to ButterKnife). You can make fields optional or required. It's pretty nice.

1

u/eMperror_ Nov 28 '16

Henson/Dart is very good! We use it on a fairly big project and it's been very good to us so far.

1

u/[deleted] Nov 26 '16

[removed] — view removed comment

4

u/chickennoodlegoop Nov 26 '16

This works fine when you can make assumptions about the arguments/extras that you need the intent to have, but gets a little tricky to abstract away otherwise.