How do I share common functions and data across many activities in a single android application

Why you don't just make a Class with only static functions, passing needed Parameters? An example if you want to show an ErrorDialog

public class SharedHelper{

    public static Dialog showErrorDialog(Context ctx, String message, String title, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener){
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setMessage(message).setTitle(tilte);
        if (okListener != null){
            builder.setPositiveButton(R.string.button_positive, okListener);
        }
        if (cancelListener != null){
           builder.setNegativeButton(R.string.button_negative, cancelListener);
        }
        return builder.show();
    }
}

Singletons are (from my point of view) one of the uglyest design pattern and will bite you sooner or later. Putting anything in Application requires you to cast it everytime to the Special Application class you designed. A class with only statics however is very flexible in its usage and doesn't need an instance to work.


For the storage-issue:

lookup "SharedPreferences" & "SQLite" and decide afterwards which storage-type suits your needs more.

For the methods-issue:

This question is a bit more complex and there are different ways to do it. For example you could write a parent-class that implements all your globally needed questions and you let all your activity-classes inherit from it.

public class MyParentActivity extends Activity {
    public void myMethod() {
    }
}

and:

public class Activity1of34 extends MyParentActivity {
    myMethod();
}

Tags:

Android