Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason why not use a "newInstance" pattern with an activity?

It seems like a nice way to simplify how arguments are set for fragments so I'm curious why it's not commonly depicted for creating explicit intents for starting activities?

like image 995
kkemper Avatar asked May 16 '17 21:05

kkemper


People also ask

What is newInstance in Android?

The newInstance() method of Class class and Constructor class is used to create a new instance of the class. The newInstance() method of Class class can invoke zero-argument constructor, whereas newInstance() method of Constructor class can invoke any number of arguments.

How do I find the instance of a fragment?

To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.


1 Answers

There's nothing wrong with creating a static method to build the Intent to start an activity, or even having a static method that starts the activity. You can also go with an IntentBuilder pattern, where you expose a builder-style API that generates the Intent, for scenarios where a simple method would be unworkable. I take that approach in my CWAC-Cam2 library, for example.

Google hasn't been promoting the pattern, though you will see this sort of code if you generate a service from the Android Studio wizard, IIRC. However, Google isn't really in the business of trying to show every possible programming pattern.

The biggest limitation that I know of is that there is no enforcement mechanism. While you can offer these sorts of facilities, there is nothing stopping developers from bypassing or ignoring them. IOW, the classic create-an-Intent-and-go API is "public", and you cannot somehow make it private. So, your activity needs to assume the worst, and have whatever defensive programming you feel is appropriate.

like image 184
CommonsWare Avatar answered Oct 23 '22 05:10

CommonsWare