Question

This is a newbie type question. I want to create a public method that can be accessed by any activity in the application. The method I am trying to create is a simple method to show the versionName or VersionCode. here is the code I use in a private method, I just feel like there has got to be a simple way of making this method accessible to all my activities without having to add the private method code to each activity individually, and simply adding a public descriptor doesn't seem to work... Thank you!

method:

private PackageInfo getPackageInfo() {
        PackageInfo pi = null;
        try {
             pi = this.getPackageManager().getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return pi;
    }

example usage:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        PackageInfo versionInfo = getPackageInfo(); 
        String about = new String(
                    versionInfo.versionName +"\n" + getString(R.string.about));
Was it helpful?

Solution

Define a new class with a static method:

public class PackageInfoHandler{
   public static PackageInfo getPackageInfo(Context ctx){
    try{
     return ctx.getPackageManager().getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES);
    } catch (PackageManager.NameNotFoundException e)
      e.printStackTrace();
   }
}

use it in your Activity like this

PackageInfo versionInfo = PackageInfoHandler.getPackageInfo(this);

As a addition you could return the string from the PackageInfoHandler and try to give it a better name than i did ;-)

Or you could make a superclass of where your method is implemented and extend all your activities from it.

OTHER TIPS

2 simple options :

  1. make this method public in an abstract Activity and make every one of your activities inherit this class.
  2. make it public static and add a context parameter, put it in an utility class.

If methods that are accessing it are in the same class, then you dont need to change anything. But if methods of other classes may access this method. Just change the private to public

public PackageInfo getPackageInfo() {
    PackageInfo pi = null;
    try {
         pi = this.getPackageManager().getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return pi;
}

add "public" to method

public PackageInfo getPackageInfo() {
    PackageInfo pi = null;
    try {
         pi = this.getPackageManager().getPackageInfo(this.getPackageName(),  
     PackageManager.GET_ACTIVITIES);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return pi;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top