Source code snippets (examples)

This is a list of Alvin Alexander's source code snippets (simple source code examples).

Android: How to create a new Fragment and put it in a layout

I’ve been working on an Android app that uses a navigation drawer, and uses fragments for each item in the drawer that you tap on. One of the items in the nav drawer is a “Preferences” item, so when I tap on that item, I run the following code from my nav drawer code:

Fragment prefsFragment = new PreferencesFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(, prefsFragment).commit();

What this does is create a new instance of my PreferencesFragment, and then puts that fragment into what I call the content_frame. This content_frame refers to a FrameLayout that I’ve defined in my activity_main.xml layout file. This fragment basically replaces whatever else was in that FrameLayout before this call. I believe this is the correct approach, at least with the navigation drawer code that I’m using.

My main layout file

For the record, my activity_main.xml file currently looks like this:


        android:layout_height="match_parent" />



I made the FrameLayout tag bold in that file; that’s where all of my fragments are placed when I run the code I showed above.

When is a Fragment destroyed?

This code just made me wonder, “When is this fragment destroyed?” To test this I added an onDestroy() method to my fragment and logged a message when it was destroyed. onDestroy is actually called as soon as I switch to another fragment via my Navigation Drawer interface. That’s good to know.

Here’s a link to the official Android Fragments documentation page. Here’s another link to a useful article that discusses the fragment lifecycle, and shares some source code via Github to demonstrate it all.

MAMP Apache httpd.conf configuration with ProxyPass and ProxyPassReverse

As a quick note to self, I used this Apache httpd.conf configuration in MAMP on my MacBook Pro when developing my “Focus” web application in 2014:

    ServerName focus
    ProxyPass /server http://localhost:8080
    ProxyPassReverse /server http://localhost:8080
    DocumentRoot /Applications/MAMP/htdocs/focus
    <Directory /Applications/MAMP/htdocs/focus>
        DirectoryIndex index.php index.html
        AllowOverride All
        Order allow,deny
        Allow from all

Looking at this in 2015 I stared at that config for a little while, wondering why I used ProxyPass and ProxyPassReverse settings, and then remembered that Focus was written with Sencha, and it used a Play Framework backend, and Sencha (generally speaking) needs to communicate with a server on the same domain as its website. By default, MAMP runs on port 8888, and I had the Play server running on port 8080.

FWIW, I also had this entry in my /etc/hosts file:    focus localhost

So that’s what those settings are about.

Android: Notes on using a PreferenceFragment with the Google Navigation Drawer code (Fragment lifecycle methods)

These are some notes on what happens when I use a PreferenceFragment with the Google Navigation Drawer code.

These are the Fragment lifecycle methods that are run when I go to my PreferenceFragment the first time:

I/VPPreferencesFragment﹕ ENTERED onCreate
I/VPPreferencesFragment﹕ ENTERED onCreateView
I/VPPreferencesFragment﹕ ENTERED onViewCreated
I/VPPreferencesFragment﹕ ENTERED onActivityCreated
I/VPPreferencesFragment﹕ ENTERED registerPreferencesChangeListener
I/VPPreferencesFragment﹕ ENTERED onStart
I/VPPreferencesFragment﹕ ENTERED onResume

Then when I go back to the Navigation Drawer, and tap Preferences, I see these lifecycle methods:

I/VPPreferencesFragment﹕ ENTERED onPause
I/VPPreferencesFragment﹕ ENTERED onStop
I/VPPreferencesFragment﹕ ENTERED onDestroyView
I/VPPreferencesFragment﹕ ENTERED onDestroy
I/VPPreferencesFragment﹕ ENTERED onDetach
I/VPPreferencesFragment﹕ ENTERED onCreate
I/VPPreferencesFragment﹕ ENTERED onCreateView
I/VPPreferencesFragment﹕ ENTERED onViewCreated
I/VPPreferencesFragment﹕ ENTERED onActivityCreated
I/VPPreferencesFragment﹕ ENTERED registerPreferencesChangeListener
I/VPPreferencesFragment﹕ ENTERED onStart
I/VPPreferencesFragment﹕ ENTERED onResume

I used this log output to debug a specific problem today, but if you need to debug a Fragment's lifecycle methods, you can see from this example which lifecycle methods are called when a Fragment is first created, and then when the Fragment is reused.

How to launch an Activity with an Intent, while also passing "extra" data

Here’s a short example of how to use an Intent to launch an Android Activity, while also adding some data (an “extra”) to the activity-launching process:

Intent currentQuoteIntent = new Intent(this, LandingPageActivity.class);
currentQuoteIntent.putExtra(GlobalState.LANDING_PAGE_INTENT_KEY, GlobalState.);
startActivityForResult(currentQuoteIntent, 0);

I show how to get the “extra” from an Activity or Fragment in this article on How to attach an extra to an Intent/PendingIntent in a Notification., but in short, the receiving Activity/Fragment can access the extra data like this:

public static class ShowFullQuoteFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {

        // get the 'extra'
        String quote = getActivity().getIntent().getStringExtra(PollingService.INTENT_KEY);
        Log.i(PF_TAG, "QUOTE: " + quote);

        // other code here ...
        View rootView = inflater.inflate(R.layout.fragment_show_full_quote, container, false);
        TextView quoteLabel = (TextView)rootView.findViewById(;
        return rootView;

If you wanted to see how to add an extra to an Intent, use the Intent to launch an Activity, and then access the Intent in an Activity or Fragment, I hope this code is helpful.

How to get the Android screen orientation (in Java code)

Use this code to get the Android screen orientation:

int orientation = getResources().getConfiguration().orientation;

As shown in the comment, the resulting orientation will either be ORIENTATION_LANDSCAPE or ORIENTATION_PORTRAIT. See the Android docs for more information.


How to get the Android ActionBar Back/Up button to work like the Android back button

As a quick note, I was just in a situation where I wanted to get my ActionBar’s Back/Up button to work just like the Android back button. To get it to work like that, I used this Java code in my Fragment class:

 * react to the user tapping the back/up icon in the action bar
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
            // this takes the user 'back', as if they pressed the left-facing triangle icon on the main android toolbar.
            // if this doesn't work as desired, another possibility is to call `finish()` here.
            return true;
            return super.onOptionsItemSelected(item);

A key to that code is calling this method in the switch statement:


As noted, calling the finish() method may have the same effect -- and may, in fact, be a better approach in some situations -- but I haven’t tested that yet.

In summary, if you wanted to see how to make your ActionBar Back/Up button work just like the Android “back” button -- the triangle that points to the left -- I hope this source code is helpful.

Android: An example onCreateView method in a Fragment class

This Java code shows how to implement a couple of things in an onCreateView method inside a Fragment class:

public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_single_image, parent, false);
    ImageView imageView = (ImageView)rootView.findViewById(;
    return rootView;

What I’m doing here is:

  1. Enabling the Android Back/Up button in the ActionBar
  2. Getting a reference to the “root view” in my layout file
  3. Getting a reference to an ImageView that I know is in that layout file
  4. Setting a bitmap image on that ImageView

If you wanted to see how to do any of these things in a fragment’s onCreateView method, I hope this source code is helpful.

Android: Getting references to Drawable images

As two quick Android “drawable” notes, if you want to convert a drawable resource into a Drawable reference, you can use code like this:

Drawable myImage = getResources().getDrawable(R.drawable.myImage);

Second, if you want to display a drawable image resource on an ImageView, you can use code like this:


(I share little code snippets out here like this because I can never remember how to do some of these things.)

Android: How to load an image from a file and set on an ImageView

If you’re working with an Android application, this source code seems to work to load an image from a file:

Bitmap bitmap = BitmapFactory.decodeFile(pathToPicture);

The Bitmap and BitmapFactory classes are located in the package:


Assuming that your pathToPicture is correct, you can then add this bitmap image to an ImageView like this:

ImageView imageView = (ImageView) getActivity().findViewById(;

As shown, the setImageBitmap method is another key to this solution.

I’m currently using this approach to let users choose an image from their image/photo gallery, which is where I get the file path.

Android setDisplayHomeAsUpEnabled not needed to enable Up/Home/Back ActionBar button

When you want to provide Up/Back/Home navigation in an Android sub-activity, this Java code doesn’t seem to be needed:


The “Add Up Action” docs on this page state that is needed, but as of some (unknown) Android version it is not needed. All you need to do is specify the “Up/Parent” activity in your AndroidManifest.xml file, like this:

    android:parentActivityName=".QuotesListActivity" />

I’m not sure about Android version specifics, but I’m developing my app with a minSdkVersion of 16 and my Up/Back buttons work fine without the Java code.