Monday, April 28, 2014

Modifying Big Nerd Ranch's Activity/Fragment superclass

The second part of making the MVC model work cleanly with an underlying data model is to create the view and controller levels easily.  

Currently if you create a new project in Eclipse you'll get an Activity connected to what is essentially an empty view (OK, there's a simply layout which is called 'container', but it's empty).  The Activity created by the SDK doesn't do anything except start a Fragment that is placed inside the container and brings along its own xml layout for the actual view that your app will work it.

I think there might be a hint there from the folks at Google regarding their feelings about using Fragments...

The guys at Big Nerd Ranch (BNR) take this one step further.  They recommend creating a class they call "SingleFragmentActivity".  They observe quite correctly that you're basically going to do two very simple things with your activities now that you're "hooked on fragments."

  1. Connect the Activity to a layout that has a container for the fragment
  2. Start (or restart if it exists already) the fragment in the container.

The class is exactly like the one created for you by default with one exception, it comes with a abstract class that will be implemented by later classes which extend this one.

Since the shell activity really doesn't do anything, the only really interesting bit here is the Fragment you're going to start, and that's the only thing that morphs from instance to instance as well.

BNR delegate that bit to the abstract class.  I've implemented this in a couple of ways.  Once with graphic fragments and once with widget/XML based fragments.

Here's the magic (once again I'm noting that a lot of this is from the BNR book with just a few extras of my own... )

First, create a superclass that will have abstract methods in it.  This class will extend FragmentActivity (an android class to create an activity that wants to use support for fragment and API loaders.

public abstract class genericFragmentActivity extends FragmentActivity {
...
   
Normally when you're going to have a shell Activity that will start a Fragment you'll simply do the work in the "OnCreate() Method, and that's the case here as well.  For this class this is all we'll do. We'll let any future implementation set up menus and the like in the child class.   But here's the OnCreate()Method...

@Override // this method is called by Android during creation of activities
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity); // this is the empty xml layout

// define the container that will be used to find or create the fragment
setFragmentContainerID(); // (see below in blog!)
// the supportFragmentManager is provided by the OS... helps us start it. FragmentManager manager = getSupportFragmentManager();
// use the manager to get the fragment reference, if it already exists.. Fragment fragment = manager.findFragmentById(fragmentContainerID);

// if the fragment exists we have it already.. if not? Create it! if (fragment == null){
fragment = createFragment();
// the fragmentContainerID is defined by the child class (below!)
manager.beginTransaction().add(fragmentContainerID, 
                      fragment).commit();
}
} 
  
This is all you see in the abstract class except the method by the BNR guys and my addition.

The BNR guys create an abstract method that will create the fragment. It's simply:
        protected abstract Fragment createFragment();

When the child class implements the abstract method they simply have to instantiate the fragment class and return the reference to the fragment. The rest is taken care of above.

As soon as I started using this I realized that not all of my fragments will go in the same container widget.  As a result I wanted to be able to modify the identifier that points to the container widget.  Initially I simply created a member for this, but then I realized that it's very easy to forget to define the widget (when my code crashed after I forgot!).  So I added an abstract method to force the child class to define it.

protected int fragmentContainerID;  // ID of xml widget that hosts this fragment
// this second abstract class is only really here to force the 
// child class to define the fragmentContainerID - it's easy to forget otherwise.
protected abstract void setFragmentContainerID();

And that's it.  Now there's a simple structure in place to create Activities that immediately and painlessly kick of Fragments.  Using this model you'll be able to use the bundles and result features of Activities, and still use the fragments that are so flexible with respect to the UI...

Here's my Activity class to end with, just to show you how simple these are now.  This one is the activity that will host the fragment to edit the Regional classes.. I'm using the intent feature to send the name of the regional object to the Fragment so it can fetch from the model.

package moticon.nationals;

import android.support.v4.app.Fragment;

public class RegionalEditActivity extends SingleFragmentActivity {

   @Override
   protected Fragment createFragment() {
      String regionName = (String)
          getIntent().getSerializableExtra(NationalConstants.REGION_ID);
      return RegionalEditFragment.newInstance(regionName);
   }

   @Override
   protected void setFragmentContainerID() {
      this.fragmentContainerID = R.id.container;
   }
}

Sunday, April 27, 2014

Accessing the model across Fragments

I'm using the Model-View-Controller (MVC) pattern.

I'm also using multiple fragments, each one will do a different task through the UI.  As the user works with the data the app will need to be able access data in the model layer across fragments.

I initially spent several hours looking for approaches to pass data between fragments.  There are ways I found to do this, but they all seemed clumsy or looked like they would be time consuming in terms of copying data.  I should have been paying more attention to my pattern all along.

-- An aside to plug a good book! -- 
BTW!! - A big nod goes to the Bill Phillips and Brian Hardy and their book "Android Programming - The Big Nerd Ranch Guide".

This solution is cut whole cloth from their book with just a few flavors I've added... This is one of the best Android programming books I've found for someone like me who stumbling through the process of learning this stuff!  They have a project you can work with, but they also explain what's going on in the background.  I'm able to use their book as a reference while I write my own applications... That's a big step up from some of the others I've used, which only give you snippets of capabilities and hints about what might be going on.
-- And now back to this discussion... 

The basic approach to make this work will be:

  1. First, hide the data well in the Model layer.  How will you access this data from different fragments? Their will be classes in the model layer which act as object managers. These object managers will have a get(Activity) method which returns a pointer to themselves (or creates themselves if they have not been instantiated yet).  Then any fragment which gains a pointer to these object manager classes can use the object managers to get the actual data, modify it, and restore it. This is a much better method than trying to pass copies of objects around!
  2. Create a class with an abstract method for the activities in the app.  Each Activity will be forced to create a fragment, and will provide the container ID from the XML layout files.  The activity class will then create the fragment. Each fragment is now created under an activity.  
  3. We can now use the intents, bundles, and ability of activities and fragments to send information back and forth about what should be gathered out of the model layer as well as notify the initiators of fragments that work is finished and they can update their UI displays. 
So, with that brief explanation.. Here are a few snippets of code from Nationals...

Hide the Model Layer
In my app there are two classes which contain most of the data. There is a class "Region" which contains information about the state of different parts of Europe.  There is another class called "Railroad" which contains information about the state of different railroad corporations.  

The user will want to update the Region objects as players modify track and improve value of cities.  

The user will also want to update the current Railroad objects so they have correct information about how many trains and what kind of trains the Railroads have.

The main screen will use these underlying objects to display the current revenue for each railroad.  

To "Hide the Model Layer" I'll use the BigNerdRanch (BNR's) approach of putting an intermediate "Holder class" in place to hold references to regions, and another to hold references to the trains.  

How does an activity get the actual pointer to an object in memory from this "Holder Class"? 

The holder class will have a static member that is the reference to itself.  It will also have a static method to return this static pointer.  Any fragment can call this static method to get the pointer to the holder class. Once it has the holder class it's connected to the rest of the model view! 

Here's the get method for "Europe", which is the holder class for all the Regions.
   public static Europe get(Context c){
      // europe is the static member holding
      //  the reference to this holder object.
      if (europe == null){
 europe = new Europe(c.getApplicationContext());
      } 
      return europe;
   }

I'll try to take time to document the abstract class for creating fragments tomorrow or the next day, but this is enough for one entry.

Making Fragments work

I'm writing a small app that will do some simple calculations for a game I play called 18OE.

I already have a spreadsheet that I can use on my android to do these calculations, but the way these calculations work it's a natural for a small app.  One of the guys I play this game with, Corbin, actually already started writing an app for it.  

The goal of the app is to calculate the money made by any railroad in its region.  There will be two simple classes - Railroads and Regions.  Each will have its own screen to configure and control them, and a main screen will display latest revenue generation values for players to reference.

I could write the entire app to take place within a single Activity, but I want to get more experience with Fragments and this app is a simple enough concept that I can focus on the Fragment stuff without getting bogged down in the app itself.

Fragment are (in my limited understanding) like a kind of thread with its own UI elements and OS support. You can start a fragment to do a task that requires a user element, connect it with a container (like a square or layout) on the screen, and when the fragment is done control can return to the original creator.

As simple as that sounds, I have tons of questions like:

  • How do you pass objects to fragments you create?
  • How do you get those modified objects back?
  • Can a fragment access objects in other parts of the overall app (Activity) directly? Would you want this to take place? 
The answers to these simple questions illustrate clearly just how many gaps there are in my understanding!  

I'll be writing more about these as I figure them out... 

Thursday, April 24, 2014

Updating Eclipse (again)

One of the first things I have to do every summer is update Eclipse.  I'm looking forward to getting Android Studio up and running, but until it's a bit more stable I'm going to stick with what I'm most productive at -- Eclipse.

In the past I know I've just pulled out a shotgun, blown away the old Eclipse and reinstalled the new one, complete with the latest Android updates as well.

This summer I preferred not to do that and went for the upgrade to keep all my Java, Android, and other goodies in place (I can't even remember all the little goodies I've installed).

So I open Eclipse, click Help->Check for Updates and there's nothing.

I then go to the Eclipse.org web page and see that I'm a revision behind -- I'm running Juno (4.2) and now things are up to Kepler (4.3).

How do I upgrade? I dig around a bit and nothing seems to work... I consider briefly pulling out old Trusty.. but pause... A quick search finds me someone who wrote about this... His entry is here:

http://codebin.co.uk/blog/upgrading-eclipse-from-juno-to-kepler/

Key Learnings?
In the future I'll try to remember that you can modify the list of places Eclipse will look for updates by going to Window->Preferences, and then modifying Install/Update->Modify Available Software Sites.

Oh, and be aware that after you restart Eclipse, it will now invite you to update the affected plugins and other packages that need to change after updating Eclipse.

For me this included Jigloo and a few other packages.

Stumbling through Android programming

This is a blog about trying to fill in the gaps in Android Application Programming.  

I'm a good programmer, but the only real experience I get is every summer when I'm done teaching and I take time to try and write a few Android Apps... 

Every summer when school is finished, I set some goals to get some apps finished, and break out my books and go after it again.  It's fun, but it's also frustrating. I forget a lot. I have to relearn it. And so along the way I have learned to try and take a few notes about how I connected (or reconnected) the dots...

For example, last summer when I finally had to take a break from programming I had written a number of general purpose fragment classes that were supposed to allow me to quickly code applications using fragments going forward.  I had used them in a small application I'd written as a tool for use during playing the game 1830.   Besides these I had also written some basic graphics based applications and was well on my way to having a decent little game engine written..

So... Here it is the start of May (almost), and I'm looking over my code thinking.. "Did I actually write all that? I can't remember very  much of it..."  And even with the comments and overly long variable names I find it's going to be a slog to try and dredge up from the depths of my murky memory the details of what I'd finished last summer...

And this reminded me of how often I find myself trying to connect the dots on basic Android, Java, and other programming items.  I learned them a year ago, implemented them, and now I can't remember what I did because it's just been too long..

So this Summer, I'm going to keep a blog and attempt to document some of the things I learn in a place where others (who are new or new again every year!) can get something out of it, and hopefully I can look back and read what I did and get back in the saddle more quickly... 

So, if you're a stumbling android programmer like me, with lots of gaps in your knowledge, and a desire to get better (one bit of knowledge at a time), perhaps this will be a place for you to visit.... 

Giddy-up!