Monday, November 14, 2016

Activity's and Fragments

Last summer during my internship I used Fragments quite often and as such for a while I understood at least the basics about Fragments, their use cases, and what strengths and weaknesses come with Fragments. Unfortunately, quite recently I had my knowledge tested on this and I learned quite quickly that I don't understand Fragments as good as I once did. So after going back and using Fragments over the weekend and reading the docs and as many tutorials as possible, I finally at least got a slight refresher on Fragments.


When is it better to use a Fragment over an Activity?


Well, actually they really just work hand in hand. An Activity will hold the context and everything you need for the Fragment, the Fragment however will store information and thus you can pass information easily through from Fragment to Fragment.

When is this useful?


Let's say for a minute that you are a general contractor and have 7 houses you're currently building. For each house you have information you need to know, but shouldn't be included in the list.

Now you could do a list like below where each item in the list is associated with an ID which you send through an intent to another activity. This might look great on phone with a relatively small screen, but on a larger device like a tablet, as you can see below, it could definitely look better.



This is where fragments come to the rescue. Let's go back to that list. Now lets say that each item in that list actually has a reference to a JobSite object that has all of the information about the job site. The fragment can pass objects through the activity to another fragment within the same Activity. Doing that you can fairly easily do something like this.


On a mobile phone you can easily use an animation to slide, expand, fade or whatever animation works best for you. On a tablet however this makes your app more user friendly across a wider range of devices.

How do I pass information to the Activity?


Passing data from the Fragment to the parent Activity is fairly simple. Within the fragment make a call to getActivity() and you can use all of the accessor methods available in the parent Activity.

Thursday, November 10, 2016

Android - Handlers and Data Leaks

This post is mostly for my reference as I use Handlers a lot, but I'm still trying to get use to the idea of a WeakReference. Obviously this isn't rocket science, but up until about 9 months ago I used Handlers in a very improper way (my first example) and undoubtedly ended up with a lot of data leaks in any multi-threaded application I developed.

I am writing this because I recently I was being tested on my Android knowledge, and although I knew about data leaks and how to solve the data leaks, courtesy of Android Studio, I didn't know what was actually causing the data leaks.

If not properly used a Handler will hold a reference to the context of the activity from which it was created which therefore prevents the garbage collector from performing garbage collection on the Activity from which you instantiated the handler. Here's a good example of what NOT to do.
class FooActivity extends Activity {
    private Handler mHandler;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foo);
        mHandler = createMyHandler();
        createBackgroundThreadWithHandler(mHandler);
    }
    private Handler createMyHandler() {
        return new Handler() {
            @Override handleMessage(Message msg) {
               super.handleMessage(msg);
               Toast.makeText(FooActivity.this, "Hi", Toast.LENGTH_SHORT).show();
            }
        };
    }
}

The above code is not good because we have no idea how long the BackgroundThreadWithHandler will be alive, however as long as it is, it will have a reference to the handler which will have a reference to the context of FooActivity.

So now lets look at the proper way to handle dealing with Handlers. We need to be able to create the handler, however we can't let the handler hold a strong reference to the Context/Activity.

class FooActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foo);
        createBackgroundThreadWithHandler(new MyHandler(FooActivity.this));
    }    

    void sayHi() {
        Toast.makeText(FooActivity.this, "Hi", Toast.LENGTH_SHORT).show();
    }

    static class MyHandler extends Handler {
        MyHandler(FooActivity fooActivity) {
            weakFooActivity = new WeakReference(fooActivity);
        }   
        @Override handleMessage(Message msg) {
            super.handleMessage(msg);
            FooActivity fooActivity = weakFooActivity.get();
            if (fooActivity != null) {
                fooActivity.sayHi();
            }
        }
    }
}

This example keeps a weak reference to FooActivity which allows the garbage collector to still perform garbage collection on FooActivity.