• 0

[JAVA/Android] how to get package info from within static context?


Question

I'm trying to create an "About" window that pops up from my app when a user clicks "About app_name" in my preferences screen. It all works, but I'd like to have the version number get pulled from the packagemanager, but can't seem to be able to do it inside a static routine:

public class AboutDialogBuilder {


	public static AlertDialog create( Context context ) throws NameNotFoundException {

                //get info about package so we can get version number out of it.
		PackageManager manager = context.getPackageManager();
        	PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);


		String aboutTitle = String.format("About %s", context.getString(R.string.app_name));


		// Set up the TextView
		final TextView message = new TextView(context);
		// We'll use a spannablestring to be able to make links clickable
//		final SpannableString s = new SpannableString(aboutText);
		message.setText("Version: 1.0" + "\n\n" + "icon sets by http://www.iconshock.com");
		//message.setText(string.iconshock);
		// Set some padding
		message.setPadding(5, 5, 5, 5);
		message.setBackgroundColor(0xFFE3E3E3);
		message.setTextColor(0xFF000000);
		// Set up the final string


		// Now linkify the text
		Linkify.addLinks(message, Linkify.WEB_URLS);

		return new AlertDialog.Builder(context).setTitle(aboutTitle).setCancelable(true).setIcon(R.drawable.app_icon).setPositiveButton(
			 context.getString(android.R.string.ok), null).setView(message).create();
	}
}

The two lines related to packagemanager at the top are what I'm having issues with. I get a message in Eclipse stating "Cannot use this in a static context", with "this" being underlined in my code. I currently have the line "message.setText(.....)" to display the Version number, but I'd like to get it pulled from the package instead so that I don't have to continually update the code if I update the app.

Thanks.

2 answers to this question

Recommended Posts

  • 0

I had to refresh real quick on the 'this' reference you're using first:

  Quote

Whenever a method is called in C++/Java/C#, an implicit argument (the ?this? reference) is passed along with/without the other parameters. In case of a static method call, the ?this? reference is not passed as static methods belong to a class and hence do not have the ?this? reference.

I found this snippet that seems to get a Package object p and extracts the version without the need for a 'this' ref.

public class GetPackageInfo {
    public static void main(String[] args) {
	packageInfoDemo("java.util.zip");
    }

    public static void packageInfoDemo(String pkgName) {
	Package p = Package.getPackage(pkgName);
	System.out.println("Specificationion: " + p.getSpecificationVersion());
	System.out.println("Specificatione: " + p.getSpecificationTitle());
	System.out.println("Specificationor: " + p.getSpecificationVendor());
    }
}

Then I found this other snippet that lacks your 'context' reference but still seems to get at the PackageInfo object like you want. Might help but I haven't used this class before (can you tell? :p ) The code snippet below comes from here and has a more detailed example with class code.

public void getVersion(View view) {
	CharSequence name = nameField.getText();
	try {
	    PackageInfo pkgInfo = getPackageManager().getPackageInfo(name.toString(), 0);
	    versionInfoField.setText(String.format(
		getString(R.string.packageInfo),
		pkgInfo.versionCode, 
		pkgInfo.versionName
	    ));
	}
	catch (PackageManager.NameNotFoundException e) {
	    versionInfoField.setText(getString(R.string.packageNotFound));
	}
    }

  • 0

You cannot use 'this' in a static method because there is no instance of the class to refer to there.

It just requires the package Name, so you could manually enter that. Or do something like AboutDialogBuilder.class.getPackage().getName()

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Burrrrn. Bought COD WWII last month when it was on sale for PC. Oh well. Excellent game tho, and the PC version plays/looks amazing (and has it's own PC achievements). ...wondering if this is a lesson on waiting on sales. ...also hoping Rise of the Tomb Raider has it's own PC Achievements
    • Google Chrome 137.0.7151.120 (offline installer) by Razvan Serea The web browser is arguably the most important piece of software on your computer. You spend much of your time online inside a browser: when you search, chat, email, shop, bank, read the news, and watch videos online, you often do all this using a browser. Google Chrome is a browser that combines a minimal design with sophisticated technology to make the web faster, safer, and easier. Use one box for everything--type in the address bar and get suggestions for both search and Web pages. Thumbnails of your top sites let you access your favorite pages instantly with lightning speed from any new tab. Desktop shortcuts allow you to launch your favorite Web apps straight from your desktop. Chrome has many useful features built in, including automatic full-page translation and access to thousands of apps, extensions, and themes from the Chrome Web Store. Google Chrome is one of the best solutions for Internet browsing giving you high level of security, speed and great features. Important to know! The offline installer links do not include the automatic update feature. Google Chrome 137.0.7151.120 changelog: [$7000][420697404] High CVE-2025-6191: Integer overflow in V8. Reported by Shaheen Fazim on 2025-05-27 [$4000][421471016] High CVE-2025-6192: Use after free in Profiler. Reported by Chaoyuan Peng (@ret2happy) on 2025-05-31 [425443272] Various fixes from internal audits, fuzzing and other initiatives Download web installer: Google Chrome Web 32-bit | Google Chrome 64-bit | Freeware Download: Google Chrome Offline Installer 64-bit | 128.0 MB Download: Google Chrome Offline Installer 32-bit | 115.0 MB Download page: Google Chrome Portable Download: Google Chrome MSI Installers for Windows (automatic update) View: Chrome Website | Release Notes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • -Drop the art style, it's cool but doesn't fit the franchise at all. -Make it a gritty single player game, like Halo -Include deathmatch and all that stuff, extraction can be a separate mode If they don't do that, it's dead on arrival IMO.
    • It's a shame because it's one of the best immersive sims ever made, even though it could have used a bit more monster variety IMO.
  • Recent Achievements

    • One Month Later
      Custom Greek Shirts earned a badge
      One Month Later
    • Week One Done
      Custom Greek Shirts earned a badge
      Week One Done
    • One Year In
      Custom Greek Shirts earned a badge
      One Year In
    • Week One Done
      topantidetectbrowser earned a badge
      Week One Done
    • Explorer
      Jdoe25 went up a rank
      Explorer
  • Popular Contributors

    1. 1
      +primortal
      672
    2. 2
      ATLien_0
      281
    3. 3
      Michael Scrip
      223
    4. 4
      +FloatingFatMan
      190
    5. 5
      Steven P.
      146
  • Tell a friend

    Love Neowin? Tell a friend!