This is more of a question where I'm trying to see if my thinking is correct before I start coding something that winds up not working. Let me see if I can explain what I'm trying to do first. My main issue is wanting to know if I'm on the right track or not.
I'm creating a game using the page viewer and fragments so I can have a tabbed layout. That's not a problem. Where I'm getting confused and turned around is that I have multiple activities, each handling a different part of the game so that I avoid having too much on the screen at any one time. I had wanted to have all of the game methods in a single class and have each activity pull from it. Can I do so if the class is private? I assume if I had a GAME class for example that I would have to instantiate a particular version of it somewhere but if I did, how can I be sure that everything is pulling from that same instance?
Another approach I had thought of was basically just making one game class that did everything and then just spit out the variable values to the various activities as needed which would then update the UI. Would that be a better approach? I think if I do it this way I can avoid having to pass data directly from one activity to the next. I can just have them all pull whatever values they need directly from the class.
Does any of this make any sense or am I way out in left field somewhere? Any direction to go in to start would be helpful as I've been going around for days trying to chart some kind of course.
It sounds like you want to put all your game logic into a Game class and have all of your Activities access that single Game instance. The answer is yes, that's probably the right approach and a simpler approach then trying to get your Activities to pass data around via Intents.
You can use a singleton pattern to get access to the same instance everywhere. (Something like this)
public class Game {
private static final Game INSTANCE = new Game();
private Game() {}
public static Game getInstance() {
return INSTANCE;
}
}
Or if you're using a dependency injection framework like Dagger, you can just mark the Game provider as providing a singleton. (If you don't know what this is, just use the singleton pattern above for now)
Related
For example, let's say my Rest adapter created with Retrofit lives inside Application class.
I would love to get it inside the Activity, so I write the following code:
public class MainActivity extends Activity {
#Inject MyRestAdapter mRestAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((GlobalApplication) getApplication()).getComponent().inject(this);
}
}
Granted, it will make the job done. But...
How is this different from calling getApplication(), and then explicitly yank the MyRestAdapter to MainActivity? Yes, Dagger 2 will simplify the setup by automatically getting everything to the Activity, but you still need to explicitly tell from where you need these dependencies, and that, if I understand correctly, defeats the whole purpose of DI. Am I right to say that Dagger 2 is "semi-automated service locator", or it's just the tutorials that misled me, and there is correct way to inject dependencies with Dagger 2 into the View or Activity from Application?
I've been experimenting with Dagger and it definitely seems to blur the lines between service locator and dependency injection. This is at least true when used with Android activities. With the current version of Dagger, it is possible to write AndroidInjection.inject(this) in an activity's onCreate method. That's basically like saying "find all the services I need and inject them into me." So Dagger is a combination of a some central/global service locator that knows where to get the services and an injector that knows where (i.e. which instance variables) to put those services in the activity. It seems that Android activities force reliance on some kind of singleton/global object.
There is no 1 "purpose of DI" but definitely one of them is to separate the configuration from what actually requests the configured objects. The idea is that your higher-level objects, such as Activitys in Android, can request all of the objects it needs without worrying about where they come from, how they are constructed, and any semantics about their relationships. Similar to how an Activity doesn't deal with drawing text to the screen (and instead delegates that to a TextView[0]), DI helps keep your objects from knowing too much that is not relevant to the actual logic they need to perform.
Inherent in the "semi-automated service locator" you describe is static analysis and error handling. As applications become larger, it becomes even harder to get manual-DI correct. Dagger helps make your code less error-prone (and less tedious to maintain).
Consider the case where you have an internal version of your app for employees, where you log lots of information about how they use the app to make sure you can identify any issues. In your actual product, however, you don't want to track personally identifiable information like that when it's not necessary. Now, your MainActivity needs an AnalyticsLogger - which one should it get? The more cases you have, the easier it is for Dagger to help piece things together than for you to do it yourself.
[0] which delegates to a Paint object
Hope you guys can clarify something for me.
I've been using Android for about 6 months now and I'm still confused about the best way to communicate between Activity and Fragments. I've already read the the info on the android developer site.
Fragment to Activity
Right now I know with 100% absolute certainty that an interface is the best way to communicate from Fragment to Activity. I.e. creating an interface in your Fragment and letting your Activity implement it. This way you can call the method from your interface inside your Fragment and have it handled by the Activity (which implements the interface).
Activity to Fragment
Here's were I'm not sure. The android developer site says that in order to communicate with a Fragment you have to put your objects in a Bundle.
Bundle bundle = new Bundle();
bundle.putInt(SOME_IDENTIFIER, myInt);
Now I've been know to use a Singleton class every now and then when I have quite some functionality that I can separate. Say I have a Singleton called PersistenceService where I handle all of the persistence related stuff, e.g. saving something in the SharedPreferences. The PersistenceService will then hold methods like putMyString(String key, String myString) or putSomeObject(String key, SomeObject someObj). This way a class doesn't have to handle persistence itself but can just call the PersistenceService to do it.
Now say I have to update something in my Fragment, a TextView or something.
This is what I do:
String myString = PersistenceService.getInstance(getActivity()).getMyString(someKey);
textView.setText(myString);
I pass in a context (getActivity()) because I need it to get the SharedPreferences.
Now my actual question is:
Do I retrieve my data in the Activity and pass it to the desired Fragment through its Bundle? Or do I simply reference my Singleton right in my Fragment and access the data there directly.
I'm not stuck or anything, but I'd like to know what you guys would recommend.
Any advice, remarks, info etc. is greatly appreciated.
This is a very broad question, and as the pragmatic thinking and learning book says, the answer to most questions in software is "It all depends!".
And it really does, it really all depends, there's no hard rule in software, "always" and "never" are very powerful words that shouldn't be used in software, so, saying always go for "Bundle" info or Never go for a Singleton is a little bit stupid specifically in software, so, instead of telling you exactly what to use, ask your self what would fit better in your needs taking on count things like, scalability, extensibility manageability, etc. For example:
If you go for Bundle, you give some flexibility to your fragment, you are creating some kind of independent component ready to work with whatever information you provide, on the other hand, if you know that you need that fragment only in that place, and the information you will pass is somehow complex(can't be passed using a bundle), why complicating so much? Just go for the Singleton if it does the job simple and clean.
I hope my point is well explained here, there's no hard rules for one way or another, just be as diligent as possible and don't go one way or another just because of laziness or negligence, instead be analyst if it's worth going one way or another based on your needs, and always take on count that not because you went that way this time it will be true for ALL your scenarios.
Hope it Helps!
Regards!
I use bundle when I want send data from fragment to fragment (from fragment to activity by interface, from activity to fragment by bundle).
If data is used in all fragments singleton is the best way, sometime I use also a istance of data objcet in activity that I manipulate in fragment by public methods of activity but I don't think that this is a best pratic.
Please understand that 2 fragments can’t directly communicate with each other, They will need help of the activity under the context of which they are created. Using an interface :).
Implement the interface in a fragment
interface StartCommunication
Define the interface in the activity whose context fragment is using
public class MainActivity extends Activity implements
SendFragment.StartCommunication
My problem seemed simple to me, but apparently it isn't.
I got a core class that is able to calculate a complex result depending on parameters entered by a user. Up to now I showed the result as a ListView and for the detail view, I used a sliding panel - so everything is neat within one activity A.
But now, I wanted to get rid of the sliding design and "simply" use a master/detail flow so I could show two fragments next to each other on tablets and separately on a mobile phone.
Well, I did not want to redesign the whole app for that, but basically: how do I get the detail information to my different activity B???
I know that through an Intent I can only send Parcelable (or serializable) data, but that is far to complex for essentially int-array-type of data! All the converting to and re-constructing from the Intent - that is just a pain!
Of course, I also do not need a database or similar complicated stuff - no SharedPrefs, please, that is all at least as complex as implementing the Parcelable!
Basically, I thought of two approaches, but they all ... stink ... kind of:
a) store the calculated data within the application class - problem: the app might get destroyed and restarted just for re-displaying activity B. Then there wouldn't be anything left in the app object!
b) implement a content provider that does the calculation and caching the result there. Hmm. The cursor again is way to complex to transfer the simple result. And: for how long should I cache the result in the ContentProvider?
I feel this is all a mess. :-(
Any ideas?
The Intent approach is by far the simplest one.
Talking about a Master/Detail flow, usually that means passing one id, this is few information and easily reconstructed from A to B (activity).
Don't use A for exactly the reason you mentioned, and B wow! too much work =)
I really think either use an Intent or use shared Prefs they are by far the least code demanding options.
Have you been able to create the behavior of the app getting destroyed and everything being deleted? I've been developing an app doing some things along the same lines and I have just been using public static variables to store things in the activity that they are created in. That way they are accessible from other activities. Not necessarily the most elegant way of doing things but it's working for me just fine.
oh man its not mess:)
did you aware of Design patterns if yes then you can use singleton pattern where you can store data for your next activity
public class mySingleton
{
mySingleton instance;
yourvariable1;
yourvariable2;
yourvariable3;
yourobject1;
yourobject2;
public static mySingleton getSingletonInstance()
{
if(instance==null)
{
instance=new mySingleton();
}
return instance;
}
}
by this you can save your data till your any activity is running or you may say untill your application is in system memory
but if you want to close application and persist data then make a background service there you can save data your applications activities will destroy but the service will contain the variables and data
hope it will solve your problem
I have a simple app, it logs a bunch of sensor/gps data. The first activity is a mess, and way too long, so i wanted to modularize it. I want to have 3 modules now:
Main Activity
Sensor Data (Gyroscope, accelerometer, etc)
GPS Data (Position, elevation, etc)
What is the best way for me to go about modularizing this? I was trying to move some of the Sensor Data out of the original class, and then I noticed that my class needed to extend some android.content.context (such as an Activity) in order to access the sensor data properly?
Thanks for a nudge in the right direction.
From my comments on the original question...
You don't need to extend Context - you can create helper classes and simply pass the Activity Context into the class constructor or into the various methods using this from the Activity.
As long as you design your helper classes correctly then it is fine and it is something that many people do and, indeed, there are various Android classes which require a Context parameter. Avoid memory leaks and use the right Context.
Sometimes using the application Context might be better as it is persistent for the life-time of all application components. It is, however, only a partial context in that certain things won't work with it (some UI-related tasks, for example). Otherwise using the Activity Context is fine as long as nothing holds a permanent reference to it (which can cause memory leaks if the Activity is destroyed.
Suppose I have an activity MyMainActivity, let's say complex enough with a bunch of code.
From another activity, to access a public variable or a method I instanciate :
MyMainActivity ma = new MyMainActivity();
ma.editVariableMethod();
String example_variable = ma.public_examplevariable;
When I instanciate MyMainActivity ma, is it like creating the hole activity again and storing everything from MyMainActivity to memory, and that way it takes the same amount of memory it would take if I was starting MyMainActivity, or is it just a link which permits to edit variables from MyMainActivity?
You can't instantiate an Activity. The framework has to take care of it. If you want to use public methods either make them static OR get a reference to a valid instance of the activity object.
Edit:
As Squonk pointed out, depending on your use case, it might be a better idea to just extract the shared logic to another new class, at least until you know what you're doing. Giving "full access" to internal variables or even methods in an Activity might seem to work, but it's very likely NOT the right approach.
It is a bad practice to share memory-resident objects between objects in Android, no matter what the objects are. Android won't ensure that it will work. There are alternatives available for most use cases. In the particular case of "accessing a public variable" in another Activity, you can call startActivityForResult(), or ensure that your Activities store data they want to "share" in SharedPreferences, etc.
If you have two or more Activities that use the same method, you should first consider if the class needs to be abstracted into a separate object. Ideally, Activities should be frameworks that delegate to POJOs.