Android Programming and Java syntax - java

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.

Related

Android - Why people refer to a static context inline repeatedly, instead of pass it in the Method() once?

I'm approaching completion of my first true App..
Along my road (in the past couple years) I've seen many examples of code.
One thing is consistent: I always see the use of static context references such as:
getApplicationContext(), this.getActivity(), and many other such references..
But earlier today, after asking how to retrieve Context from a Method within a Receiver,I was told simply "pass it the Context", ex: public void receiverMethodCall(Context context).
My Question is: If it's that simple, why do people frequently make repeated static context references inline within their code, over and over again, instead of simply passing the containing Method a Context to begin with, and referring to it using "context" when needed?
I Hope that I got your question meaning - you got your answer and told to pass on the context as a context typed variable - but do not forget that when you want to call your method and pass it a context, you will have to know what this context is and initialize it.For example, if you want to make a Toast one of the method parameters is context and if you are using a lot of Toasts it would be better to have context reference and use it for every time you want to show a Toast(or use any other method that requires context.)rather than using this.getActivity() orgetApplicationContext().By doing this you can prevent a duplicated code and you won't need to refer to the context in your code a lot of times, now for the question about "why do people frequently make repeated static context references inline within their code".
I can think of one case when it won't be a bad thing to make 2 context reference: let's say that you have 2 methods in the same activity that are using context - if those methods are used once then you can create context reference inside the method and let the garbage collector handle that reference.I do have to say that I agree with you, I think that if its optional just pass context to your method and let it use it, its really simple solution.

Android - Organizing levels in a game

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).

View all methods called during Runtime - Eclipse Java

I have a Java application and basically I want to know all the methods that are called in the background when I do something in the GUI. I know you can view the Call Hierarchy by selecting a method but that's while the code isn't running. I want to view every single method called in every class when I select something for example so I can figure out which methods/classes/packages are responsible for this functionality. I also don't want to have to set a breakpoint at the start of every method as there are far too many methods/classes/packages for that to be feasible. Bear in mind that I don't even know the first method called for some of the operations, if I knew that, it'd be easy to figure out what's going on.
Is there a way to do this or am I ahead of my time?
I think you could use the debug mode to see all methods called
Run DEBUG in your IDE, your each step in application will move you to the right place in the code, during your program you can see each variable value.
Also you can follow each code line which your code is doing.
http://www.vogella.com/tutorials/EclipseDebugging/article.html
Regards!

How can I generate and compile Java files in Android at Runtime

I know with javax.tools.* it is possible, but since this is not included in the Android API, I'm desperately wondering, is this possible?
Right now, my goal is to create a drag-and-drop tool to allow users to create their own layouts (as not everyone wants to learn Mobile Development, as it requires a lot of time, dedication and practice) similar to how Android Studio does it's own. However, of course the most important thing is to implement functionality via onClickListener and onTouchListeners. I've begun remedying this by creating my own DSL (Domain-Specific-Language) with a GUI front-end allowing users to choose what they want via PopupMenu and SubMenus. For example...
Statements
{ if, for, while }
Statements must be followed immediately by a reference and then a conditional (obtained from that reference), like a "if(Object.conditional())" statement.
References
{ Object1, Object2, Object3 }
The objects are references to other Views (I.E, Buttons, Layouts, WebView, etc.).
Conditionals|Actions|Getters|Setters
{ isSomething(), doSomething(), getSomething(), setSomething() }
Each Reference's methods, wrapped so that each wrapper keeps track of it's method's attributes and description (hence documentation).
It would go something like such...
IF ImageView1.isVisible()
ImageView1.setVisible(false)
ELSE
ImageView1.setVisible(true)
Of course, the method setVisible(boolean) is a wrapped version of setVisiblity(int).None of this is typed, it is obtained from a simple PopupMenu which shows them the applicable selections based on current context.
How I plan on transcribing this to compiling code was to convert the statement into Java code, inserting references on the fly as they are needed (I.E, ImageView1 would be defined in java as private ImageView ImageView1;), generate methods somewhat similar to how ButterKnife generates it's extra classes for it's onClick and onTouch annotations, etc.
Then, after planning all of this (been working on it for 2 weeks now), I find out that Android does not have support for compiling code like this. Please tell me something like this is possible. It's something I 100% wanted to do. Is this possible with any third party libraries?
If not, is there some possible way to mimic doing so? I could do it the long and slow way, of preparing every such possible way, keeping track of the references myself through a map, and when it is about to be called, directly call the implemented method for the View associated with that key, which theoretically COULD work. In fact, that'd be my second go-to if I can't. It'd be messy though.
Sorry if this is too long, I just want to get this to work.
TL;DR: Is there a way to compile a generated Java file created at Runtime in Android (since javax.tools.* does not exist), and if not what would be the best way to do so?

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.

Categories

Resources