Android: Base Activity class Example


It’s always been a good idea to make a baseActivity in android project.

Usually one screen is represented by an activity. Suppose, you have 3 custom activity classes (i.e, you writes them) in your android project. And you extended these 3 custom activity from android.app.Activity class.

What I am suggesting is to create an activity from android.app.Activity called baseActivity and make the 3 custom activity to extend from baseActivity.

For example,

public abstract class MyAppBaseActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

And your custom activity

public class MyCustomActivity extends MyAppBaseActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Notice that, MyAppBaseActivity is an abstract class. The reason is, we are not going to instantiate it. That’s why you don’t need to add the MyAppBaseActivity class in AndroidManifest.xml file. Now the question is, why would you do that? Means, why you need to make an baseActivity class and then make your other activities as a subclass of it?
Well, here are few very generic reasons
1. You can avoid code duplication of you application wise common ui tasks. Suppose you want to show progressDialog in different activities. Just write code to show a progressDialog in your baseActivity and call that method from other activity.

 

2. Your application menu should be consistent across different application. For example, you have a settings screen. Option menu is containing the navigation to settings screen. You should display the settings throughout the application, means regardless of activity. User want to access the settings screen from anywhere in application. This feature can be easily achieved, but you have to override onCreateOptionsMenu in each of your activity or, you can override it once in your baseActivity.
Here is a generic baseAcitvity class example

package com.example.TestAndroid;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.Toast;

public abstract class MyAppBaseActivity extends Activity {

    private ProgressDialog mProgressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_common, menu);

        // Get the SearchView and set the searchable configuration
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
            searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            searchView.setIconifiedByDefault(true);
        }

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();

        if (itemId == android.R.id.home) {
            finish();

        } else if (itemId == R.id.menu_settings) {
            startActivity(new Intent(this, SettingsActivity.class));

        } else if (itemId == R.id.menu_search) {
            onSearchRequested();

        }

        return super.onOptionsItemSelected(item);
    }

    protected void showProgress(String msg) {
        if (mProgressDialog != null && mProgressDialog.isShowing())
            dismissProgress();

        mProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.app_name), msg);
    }

    protected void dismissProgress() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    protected void showAlert(String msg) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getResources().getString(R.string.app_name))
                .setMessage(msg)
                .setCancelable(false)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).create().show();
    }
}

menu_common.xml

</pre>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item
     android:id="@+id/menu_settings"
     android:icon="@android:drawable/ic_menu_preferences"
     android:showAsAction="always"/>

<item
     android:id="@+id/menu_search"
     android:title="Search"
     android:showAsAction="always"
     android:icon="@android:drawable/ic_menu_search"
     android:actionViewClass="android.widget.SearchView"/>

</menu>
<pre>
About these ads

One thought on “Android: Base Activity class Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s