Android - Organizing levels in a game - java

I'm new in the development with Android. For a school project, I'm currently working on an application for children to help them learn writing.
The app will contain many levels that use the same concept, only the background changes. I have made a level that works fine and now to finish the work, I want to add levels using the code of the first one.
So what is a good/usual way to do that ?
I thought that I could create as many activities as levels. In each new activity, I could start the first one and give it the new background as parameter. But with 50+ levels, it seems a bit strange to me to have so many activities.
Thank you for your help :)

If changing to a new background is all a change of levels will trigger, I would just add a level member variable to the activity and (for instance) listen for the next level in order to change the background. If it turns out that you will have to change more than the background, #Vucko s answer seems viable.
Definitely do not repeat the same code fifty times in fifty different activities!

You can use fragments, particularly 1 type of Fragment called 'LevelFragment' which will have a few arguments that you can pass to it so that each level is different, those arguments should refer to the content of the level (background or whatever). This way you're reusing the same layout and the same logic, just changing some of it's behavior based on the arguments you have.
Now all you need to do is to swap out fragments in your container, while still staying in one Activity only. Since your question was kinda vague, I cannot offer any implementation tips at this point, but rather a basic guideline and a direction to consider.

You can use a BaseActivity that will be extended from all other activities for code centralization. Otherwise you can use always the same activity and start it with a parameter in the intent (for example, level number) and make your own logics according parameter value. Finally, you can give a look to fragments too, keeping central logic in the same activity.

Fragment is your solution, you can simply pass the background assets name (throw intent).

Related

Use Enum for checking condition

I am working on an application in which there are some fragment classes, which can be open by two ways in the application. The first way is Main Flow , the second way is through the Navigation Drawer.
So when the fragment is called from the Navigation Drawer than it will perform some task, and if it's call from the Main Flow than it will perform another task.
How can I check the context? Is there possibility through the use of Enum class.
Note:
I don't want to send the hardcoded value through the Intent.
Firstly, you should avoid using enums in Android environment. Prefer to use #IntDef, #StringDef. The main reasoning behind this is the waste of resources. Enums take much more memory.
As Colt McAnlis shows in this perfmatters episode enums take 13x more space on rather trivial example.
Secondly, what you want to achieve may be done via Intents or Bundles, passing a boolean value from one component to another.

Is there a model change listener mechanism in android

I am designing a android user interface for a sports app.
One of the features of the app is that the text of buttons and menu items changes as
the game state progresses. So you go from setup game -> start first half -> half time -> second half -> game over etc. The buttons and the menu item text change to indicate the next valid actions in the app.
Now so far I am doing that by watching a global var of the state and basically checking this in the various onCreate, onResume methods. at least for the buttons anyway. Not sure about menu items and how to make them dynamic.
Now I figure there must be a better way to do this in android ? In swing you might have a modelchangelistener and you could register as a listener of that in your view. Does something similar exist in android ? Also I know in Java you can do the Observer pattern but I was looking for something built into android. I imagine this scenario is fairly common.
But if there is not then NO YOU HAVE TO DO IT YOURSELF is an acceptable response to my question too.
Thanks in advance.
Frank.
Android does not have anything in particular like an Observer/Observable - even though you are free to use those in Android as well.
The question is: should you use Observer/Observable-classes, or not? Some say no, because it requires you to override an update-method which takes an Object parameter. This is not OO-friendly. Others, love it.
Those against it, suggest you write your own Observer classes, and register those Observers manually. Each Observable should then iterate through a list of Observer instances to say:
"Hey! Here's an update."
Good question.
You have to implement your own Listener and then you can use a selector in the XML file you create later on. Just like when you use it with Buttons : android:state_pressed="true"
Edit: However, I really suggest you don't spend time at all on this task as that can be accomplished in any other simpler way.

Keeping data view/layout in Android after screen rotate/activity destroyed

I'm a little confused about the Activity being destroyed and recreated when the user's device is rotated.
I've been reading around, and I understand the rationale for doing so (it basically 'forces' the developer to make sure they haven't 'missed' anything upon rotation/language/other changes)
I'm happy to respect best practice if it is seen as such, however it begs the question:
How do I 'remember' the state of the game/app, so that when the screen is rotated I have something from which to re-generate what the user was looking at?
From what I can see, absolutely everything is destroyed, the base class constructor runs and all variables in the Activity are 'null'.
I suspect the 'savedInstanceState' (Bundle class) is where I would collect that data, but reading around it only seems to be used for when the app is closed from lack of resources (and a few other extremely fringe cases)
Am I misinformed or misunderstanding the purpose of savedInstanceState? Is it wise to abandon best practice (letting the Activity be destroyed) if I'm mindful enough to not miss anything upon rotation? Thanks in advance for any advice.
I should note this question applies to game programming (I'm not using a layout XML)
Do you need your activity to be recreated? Is there work you want to do on rotation? savedInstanceState is where you would store data to be passed to the recreation of the Activity, but since you aren't using XML layouts you may consider just adding android:configChanges="orientation" to your activity in the manifest. This will give you manual control over what happens during rotation change.
In additional to my original comment, I would override config changes for keyboard being show as well:
android:configChanges="orientation|keyboardHidden"
If there is work you want to do on rotation change you can override onConfigChange and do anything you need there.
It's hard to say that there is a time when you should always override config changes, but I often do it when I have no dependency on resource folders that are size or orientation specific and I'm doing a lot of work that would take too much time to recreate.
There are other best practices to store data while activitiy config changes.1. Developer Doc Handling Runtime Changes2. Alex Lockwood : Handling Configuration Changes with Fragments, This will answer all your questions reagarding config change and storing data.
Impt:
Fragment file to store data. You must set setRetainInstace(true) in order to store data and retrieve while your activity config changes.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}

Keeping things decentralized Android

This might not make much sense in terms of Android SDK, but, in C++ I am used to keeping my main.cpp (and specifically main() function) as a place where I declare and initialize other classes/objects, and afterwards all the things that my application does take place in those classes. I never come back and check for anything in main.cpp afterwards.
But in Java, Android SDK, you have to override dozens of methods in main activity and all of that takes place in one single file. Example:
I have a MainActivity.java and SomeTest.java files in my project, where first is default MainActivity class which extends Activity, and SomeTest.java contains class that declares and runs new Thread. I initialize SomeTest class from MainActivity.java and pass a handle of the activity to it as a parameter:
SomeTest test = new SomeTest(MainActivity.this);
And having the handle to MainActivity, I proceed doing everything from this newly created thread. When I need to update the UI I use runOnUiThread() to create and show a new ListView (for example) on my main layout. I want to get the width and height of the newly created Listview, for what I have to override onWindowFocusChanged() in my MainActivity.java and notify the thread from there, as getWidth() and getHeight() will only have values when ListView is actually displayed on the screen. For me it's not a good practice to make such connections ('callbacks', if you will) from MainActivity to that thread.
Is there a way I can keep methods like onWindowFocusChanged() within the thread and don't touch the MainActivity.java at all?
As I said, might not make much sense.
Is there a way I can keep methods like onWindowFocusChanged() within the thread and don't touch the MainActivity.java at all?
onWindowFocusChanged() is a callback method. It is called on the activity. You cannot change this.
And having the handle to MainActivity, I proceed doing everything from this newly created thread.
That's generally not a good idea. Using a background thread to, say, load some data from a file or database is perfectly reasonable (though using Loader or AsyncTask may be better). However, usually, the background thread should neither know nor care about things like "the width and height of the newly created ListView".
You are certainly welcome to migrate some logic out of the activity and into other classes. You might use particular frameworks for that, such as fragments or custom views. However, the class structure should not be driven by your threading model. For example, let's go back to your opening statement:
in C++ I am used to keeping my main.cpp (and specifically main() function) as a place where I declare and initialize other classes/objects, and afterwards all the things that my application does take place in those classes
However, in C++, you would not say that you are locked into only ever having two classes, one of which is operating on some background thread. While you may have a class or classes that happen to use a background thread (or threads), the driving force behind the class structure isn't "I have a background thread" but "I want to reuse XYZ logic" or "I wish to use a class hierarchy in support of the strategy pattern" or some such.
Personally speaking Context idea taken from Android SDK seems to be messy. What you are describing comes from too much responsibility intended for Activity. That's why you need to track a LOT of things inside single file (Activity's life cycle, getting Context instance in order to show Dialog etc.). I don't think there's perfect solution but I would recommend using:
Fragment subclasses which are helping to divide your screen (and so on logic) into seperate parts
3rd party frameworks/libraries like AndroidAnnotations, RoboGuice, Otto which are perfect tools to avoid spaghetti code
if you would like to perform some UI updates from another class, consider using an AsyncTask passing it the Views you need to update. Let me know if you need an example
I read everything and understand your statements, I can see you've been doing programming for sometime but apparently is just starting with Android, I've done a lot of embed systems before so I totally get the concept of having a software that looks like:
void run(){
object.setup();
while(true){
otherObject.run();
}
}
But there's one fundamental flaw on the you logic of your question:
Android programming is a different programming paradigm from C++ and from computer programming and you should understand its specific paradigm instead of assume what is good practice from other paradigms.
Quote from you: create and show a new ListView (for example) on my main layout. I want to get the width and height of the newly created Listview, for what I have to override onWindowFocusChanged().
From that I can see that you've really trying to do Android stuff on a way that is not recommended on an Android context. A ListView you can easily implement from the XML layout setContentView(int) and use the Activity onCreate to instantiate any threading (AsyncTaskLoader) framework to load the data in background and deliver it back to the UI.
That doesn't mean that all your code will be dumped in one file making it a mess. This little example I put you can do with Activity that implements the loader callbacks, a separate class with the loader, a separate class with the data loading work, a separate class with the data adapter, the activity is just a central piece that organise and manage those classes on the correct moment of its life-cycle and at no point you need to call onWindowFocusChanged() and still have a nicely organised code.
Apart from that please refer to CommonsWare answer as it's usually cleverly written and correct.

Android Programming and Java syntax

This is a question regarding the syntax used in Eclipse SDK while programming some JAVA code for an Android App.
I am an embedded microcontroller engineer that's mainly used to programming in Assembler (a long time ago) and C. I am a newbie when it comes C++ and JAVA and to help me write my code I have been using a mix of the developer.android.com for background info and stackoverflow.com for real world examples and have found them very useful.
So, I have no problem writing code to do what I want to do because I've always done it, but I am finding it very difficult getting my head around the syntax used in writing Android Apps.
For example to access the GPS one of my lines of code read thus:
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
but can be shortened to this:
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
I prefer the second version, but why were some examples written like the first example? Both seem to work fine. I've seen other examples that look even more complicated using "Class".
Secondly, is this not a complicated way to do a really simple thing:
Toast.makeText(getBaseContext(),"Hello World",Toast.LENGTH_SHORT).show();
Why not:
Toast("Hello world");
It now takes me four times as long as it use to write code.
The line break after the cast there is just to keep the lines from getting too long.
On this:
Toast.makeText(getBaseContext(),"Hello World",Toast.LENGTH_SHORT).show();
... it would be simple to write it as you say, aexcept that doesn't do the same things. Basically, that line is
Finding the outermost enclosing place to put graphics
Setting the text you want to show, and setting some formatting or some such
and then showing it.
You want to split those up because you don't always write to the outermost world, and you may want to, for example, make several different chunks of text and show90 or hide() them later. (Think an error message and a success message, for example. You like to build them once and then show/hide the ones you don't need.)
Now, if you can define what context you want and never want to mess with the visibillty, you can make a function that does just that.
It is kind of beginner OOP-ish style to put this everywhere. It is implied in your second example, and the second example is the more common style.
Now this one has to do with a bit of engineering. Yes, your second short example could have been implemented (except that Toast is a class, not a function, but a similar thing would work), but it would preclude a lot of important things you may want to do. A Toast may not be all that lightweight of an object; you may want to cache it. That's why you first get an instance with makeText and only then call show on it. The Toast instance will also have a complete lifecycle that you need to control, but won't be able to with your simple example. The instance can probably undergo further configuration, etc. etc. In short, there's a reason for it which is not obvious from a Hello, world piece of code.
Welcome to the world of Android and Java programming. Since you come from an assembly language background, my advice is: Get used to more typing. :)
Regarding the first code fragment: First, the qualifier this. on the call to getSystemService() is redundant; you can just drop it. Secondly, you can eliminate the qualifier on LOCATION_SERVICE by statically importing the name. Add something like this to the imports for the compilation unit:
import static android.content.Context.LOCATION_SERVICE;
or, if you don't mind the namespace pollution:
import static android.content.Context.*;
Regarding the second fragment: for architectural reasons, Toast eventually needs to associate the popup window to some application context. The first argument to the factory method makeToast is what makes this possible. (By the way, you just need getContext(), not getBaseContext(). You could also stash the context in a field.) As far as the third argument to makeText—arguably, a version of the factory method could have been provided that has a default display time, but Android doesn't provide that, so you're stuck with the third argument as well. You can again avoid the qualifier by statically importing LENGTH_SHORT. Finally, the factory method just returns a Toast object. You aren't required to show() it just yet; it could be stashed and shown at a future time. It's good design to separate creating the Toast object from the action of putting it on the screen.
I will try to explain the things in the easiest way and to the best of my ability.
1. ".this" refers to the current object in Java. ".this" specifically points to the current object accessing its own instance variable members of that class.
2. Using "this" is just being more specific.
3. Now in the case of Toast, It requires the "context" parameter to point to the Activity
where it will display the Toast.(ie on which activity)
4. You can use "this" if you are not inside an Anonymous class, or if you are in an Anonymouse class then use "Your_Activity_Name.this" in place of context.
5. getBaseContext, getApplicationContext are like global access to the parts of the Application.
6. I always prefer Your_Activity_Name.this in context place. Context means the Activity, on which the Toast is going to be displayed. And yes there is No Toast(String s) method in activity.

Categories

Resources