Some initial impressions from Android development

I recently got to do some Android programming, and I'd like to share some of what I learned. A few things strike you the moment you start developing for Android devices.

    1. It is Java

    2. Layouts are done with XML

    3. Android 'pages', or activities are automonous entities.

Well, strictly speaking, these assertions are not 100% correct. Let me elaborate on each one.

Java

Android uses a Java variant; the source code and syntax is definitely Java, but there are some slight differences, there are a number of Java libraries you cannot use, and compiling does not create Java byte code but instead dalvik byte code.

It is worth noting that Java was written with the RISC architecture in mind, and the ARM microprocessor used in the iPad, iPhone, and Android devices is a RISC microprocessor. RIght from the start the java byte code closely matched the ARM op codes, and then they added a Jazelle mode to the ARM microprocessor that handled most Java byte codes on a one-to-one basis.

One interesting thing I noticed working with ARM devices and Java is that when C code was compiled for the ARM 4 registers were commonly directly assigned to the last 4 variables. This is a fairly common practice and C programmers typically declare heavily used variables last because (usually) they will be put in registers instead of the stack. The Java byte code has a special addressing mode for the last 4 items on the stack, this would give the JVM the option to use registers even tho the java language does not support the register keyword.

But bottom line, if you know Java you can write for Android devices.

Layouts

Layouts are done with XML, but also with Java and a WYSIWYG editor. GUI layouts have always been a bother. Early systems had absolute placement. That was okay as long as your programs GUI stayed one size. Then Java (and other systems) had layout managers. A big improvement but what a waste that so much of your program existed just to lay things out, and then remained there taking up memory after it was no longer needed. Then some systems had a WYSIWYG editor but many programmers were frustrated by these. A lot of the 'guts' of the layout was really hidden from you, and often these resulted in code bloat. I remember with one system I had 20 buttons that I set to have the same 5 attributes - same font, size, color and a few other things. This resulted in 100 'set' statements!

So, Android uses XML with nodes that correlate very closely to the layout managers you are used to in Java, with the children of those nodes being the GUI widgets - buttons, text fields, etc. - or other layouts. You can switch between the XML view and the WYSIWYG view quickly. While you can edit in the WYSIWYG view I find it easiest to edit XML and then switch to the WYSIWYG view to verify things.

Everything you do with XML you can also instead do in Java, but this is frowned upon. Typically you only want to change things like visibility and disabling at runtime. However, I've found it is easiest to do some of the more complex things, such as listview, in Java.

The XML layouts support styles. Remember earlier I complained how using a common set of settings resulted in code bloat? You can assign one of more attributes to a setting and then assign that setting to a GUI widget, really reducing the amount of code.

But it gets even better - you can use different layouts and styles for different device screen sizes. In my experience I've found it is possible to write one layout that scales quite well to different screen sizes but the text is often troublesome - text that is a nice single line on a Kindle Fire wraps to 2 lines on a phone. By simply creating 2 different styles the layouts look great.

Now, I'm certain you're asking the question "If the GUI widgets are created in XML, how does java access them?" Each GUI node in the XML can be assigned a unique identifier. Within the code these nodes can be accessed with a

findViewById(NodeID) call.

Activities.

Each Android app takes over the entire screen, and each time you move from one screen to another that new screen completely takes over. Now, it is important to note that a screen does not exist until it is displayed, and when another screen is placed on top of it, it basically goes to sleep.

In java I often created pages well in advance of their use, often setting variables and such long before they were displayed. Now, on the Android, pages have very little direct interaction. One page knows of a new one only when it is being created. But this is a good thing, it enforces the separation of data and GUI we all strive for. Also, ONLY the thread that created a GUI element can alter it. A small point, but how often have you put a long running process in its own thread and have it periodically update a progress bar in the GUI? ( I often do)

But, bottom line, when one page is visible you have to take the view that it exists by itself and none of the other GUI widgets of your application are available. Android provides mechanisms to handle passing data around from one autonomous activity to another, and these include:

1. Increased use of Singletons

2. Preferences

3.StartActivity and startActivityForResult

4. Handlers.

Increased use of singletons

We all know global variables are a bad thing, but face it - you virtually always have one core set of data that the entire program is going to work on. In my case, at any one given time only one practitioner is dealing with only one patient. Well - defined singletons handling groups of related data. Previously in Java I used a 'push' model, when data changed one central object broadcast the changes to all the pages that might use it, whether they were visible or not. In Android I use a 'pull' model where pages get data as they need it. A very simple change - the constructors get reference to the needed singletons and grab values.

 

Preferences

Preferences are an android utility to easily share variable values across an application. It appears originally written to deal with GUI preferences, but can be used in a more general-purpose sense. Preferences let you save and retreive variable name/variable value pairs.

editor.putBoolean(

"trainingMode", bTrainingMode);

 

bTrainingMode = sharedPreferences.getBoolean("trainingMode", true);

StartActivity and

startActivityForResult

There are two ways to launch a new activity or intent. StartActivity launches a new activity when you don't need it to directly return a specific result. The Bundle class allows you to pass in input data in a variable name/variable value sets similar to preferences.

 

For example to start a new page ( a new activity ) called Medical History, and pass it two importatn values, you would use this:

 

Intent medicalHX = new Intent(this, MedicalHxPage.class);

bundle.putInt(

"DocumentType", DocumentDataMgr.DOC_TYPE_MEDICAL_HX);

 

bundle.putInt("PatientID", iPatientID);

medicalHX.putExtras(bundle);

startActivity(medicalHX);

and then in the new activity;

bundle = getIntent().getExtras();

iPatientID = bundle.getInt("PatientID");

That works fine for sending input value TO a new activity, but often we want results FROM that activity. There is a mechanism for us to get that output. Instead of using startActivity() we use startActivityForResult(), passing an additional integer parameter that we'll use to get this results

 

startActivityForResult(signaturePage,

GET_SIGNATURE_REQUEST);

then the new activity calls this prior to exit:

setResult(int, data)

where data is an intent containing another bundle of name/value pairs.

And the original activity retreives this data in the function

 

public void onActivityResult(int requestCode, int resultCode, Intent data)

Handlers

Android only allows the thread that created a GUI widget to 'touch' it. It's worth noting that Java Swing elements are not thread-safe, but in my experience this is rarely an issue. The worst that can happen is a progress bar is slow in updating or an action button that was disabled until a separate thread completes a task is enabled a second or two late. But, Android will throw an exception if you do anything to a GUI element outside of its originating thread.

Handlers and messages provide the mechanism for intra-thread communication like this. The activity that will be receiving results from a separate thread creates a handler object, and gives the new thread a reference to it. This new thread can then create message objects to pass back via this handler.

 

The activity creates something along this line:

 

handler = newHandler() {

 

public voidhandleMessage(Message msg) {

 

if ( bAnimating)

onProgressChanged(

tempSlider, msg.arg1, true);

}

};

and this new, independent thread calls:

msg = Message.obtain(

handler, iProgress, iProgress, iProgress);

msg.sendToTarget();

 

 

 

 

 

 

 

Views: 115

Comment

You need to be a member of Codetown to add comments!

Join Codetown

Happy 10th year, JCertif!

Notes

Welcome to Codetown!

Codetown is a social network. It's got blogs, forums, groups, personal pages and more! You might think of Codetown as a funky camper van with lots of compartments for your stuff and a great multimedia system, too! Best of all, Codetown has room for all of your friends.

When you create a profile for yourself you get a personal page automatically. That's where you can be creative and do your own thing. People who want to get to know you will click on your name or picture and…
Continue

Created by Michael Levin Dec 18, 2008 at 6:56pm. Last updated by Michael Levin May 4, 2018.

Looking for Jobs or Staff?

Check out the Codetown Jobs group.

 

Enjoy the site? Support Codetown with your donation.



InfoQ Reading List

Article: Reactive Real-Time Notifications with SSE, Spring Boot, and Redis Pub/Sub

Explore the power of reactive programming for building scalable real-time notification systems. Using Spring Boot Reactive and Spring WebFlux, leverage non-blocking operations to handle high-volume, asynchronous data flows efficiently. Discover how Redis Pub/Sub enables event-driven messaging and how the SSE protocol provides persistent connections for instant client updates without polling.

By Matteo Rossi

ASP.NET Core 9: Enhancements in Static Asset Handling, Blazor, SignalR, and OpenAPI Support

Microsoft has released .NET 9, which contains features regarding ASP.NET Core 9. This latest release focuses on optimizing static asset handling, refining Blazor's component interaction, enhancing SignalR's observability and performance, and streamlining API documentation through built-in OpenAPI support.

By Robert Krzaczyński

QCon SF: Mandy Gu on Using Generative AI for Productivity at Wealthsimple

Mandy Gu spoke at QCon SF 2024 about how Wealthsimple, a Canadian fintech company, uses Generative AI to improve productivity. Her talk focused on the development and evolution of their GenAI tool suite and how Wealthsimple crossed the "Trough of Disillusionment" to achieve productivity.

By Anthony Alford

Presentation: From Local to Production: A Modern Developer’s Journey Towards Kubernetes

Urvashi Mohnani discusses the full developer experience of writing an application, containerizing it locally, deploying it to a Kubernetes cluster, and debugging Kubernetes applications locally.

By Urvashi Mohnani

Microsoft Introduces Local Emulator for Azure Service Bus Wanted by Developers for Years

Microsoft has unveiled a local Azure Service Bus emulator, transforming the way developers create and test applications. This tool eliminates cloud dependencies and costs, offering a streamlined development cycle and precise debugging in an isolated environment. Compatible with the latest SDKs, it empowers developers to innovate efficiently while ensuring reliable application communication.

By Steef-Jan Wiggers

© 2024   Created by Michael Levin.   Powered by

Badges  |  Report an Issue  |  Terms of Service