• 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

    • What? Every single app I've installed from the Microsoft Store comes from its intended developer and works perfectly fine. What apps do you install?
    • Microsoft Store is such a weird place filled with so much absolute garbage and with reputable apps that somehow come from questionable sources. Like, the app name is known, the images back it up but the publisher is just some weird name that's not mentioned for the apps we know.
    • NTLite 2025.06.10459 is out.
    • Wireshark 4.4.7 by Razvan Serea  Wireshark is a network packet analyzer. A network packet analyzer will try to capture network packets and tries to display that packet data as detailed as possible. You could think of a network packet analyzer as a measuring device used to examine what's going on inside a network cable, just like a voltmeter is used by an electrician to examine what's going on inside an electric cable (but at a higher level, of course). In the past, such tools were either very expensive, proprietary, or both. However, with the advent of Wireshark, all that has changed. Wireshark is perhaps one of the best open source packet analyzers available today. Deep inspection of hundreds of protocols, with more being added all the time Live capture and offline analysis Standard three-pane packet browser Multi-platform: Runs on Windows, Linux, OS X, Solaris, FreeBSD, NetBSD, and many others Captured network data can be browsed via a GUI, or via the TTY-mode TShark utility The most powerful display filters in the industry Rich VoIP analysis Read/write many different capture file formats Capture files compressed with gzip can be decompressed on the fly Live data can be read from Ethernet, IEEE 802.11, PPP/HDLC, ATM, Bluetooth, USB, Token Ring, Frame Relay, FDDI, and others (depending on your platfrom) Decryption support for many protocols, including IPsec, ISAKMP, Kerberos, SNMPv3, SSL/TLS, WEP, and WPA/WPA2 Coloring rules can be applied to the packet list for quick, intuitive analysis Output can be exported to XML, PostScript®, CSV, or plain text Wireshark 4.4.7 changelog: The following vulnerabilities have been fixed wnpa-sec-2025-02 Dissection engine crash. Issue 20509. CVE-2025-5601. The following bugs have been fixed Wireshark does not correctly decode LIN "go to sleep" in TECMP and CMP. Issue 20463. Dissector bug, Protocol CIGI. Issue 20496. Green power packets are not dissected when proto_version == ZBEE_VERSION_GREEN_POWER. Issue 20497. Packet diagrams misalign or drop bitfields. Issue 20507. Corruption when setting heuristic dissector table UI name from Lua. Issue 20523. LDAP dissector incorrectly displays filters with singleton "&" Issue 20527. WebSocket per-message compression extentions: fail to decompress server messages (from the 2nd) due to parameter handling. Issue 20531. The LL_PERIODIC_SYNC_WR_IND packet is not properly dissected (packet-btle.c) Issue 20554. Updated Protocol Support AT, BT LE LL, CIGI, genl, LDAP, LIN, Logcat Text, net_dm, netfilter, nvme, SSH, TCPCL, TLS, WebSocket, ZigBee, and ZigBee ZCL Download: Wireshark 4.4.7 | 83.2 MB (Open Source) Download: Portable Wireshark 4.4.7 | ARM64 Installer View: Wireshark Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Snapchat finally has a watchOS app, a decade after the Apple Watch launched by David Uzondu Snap has announced that Snapchat is finally hopping onto Apple Watch, something many users have probably been waiting for. This new app lets you easily preview an incoming message right on your wrist and then fire back a reply without ever needing to grab your iPhone. For those quick responses, you have options: you can tap out a message on the keyboard, use Scribble to draw letters, dictate your reply, or just send a fitting emoji. Snap says it's trying to make Snapchat easier to use on all the different devices people have in their lives. It's already seen people using Snapchat on tablets and the web, so bringing it to wearables like the Apple Watch feels like the next natural move. That marks a big change from back in 2015 when the Apple Watch first launched. At the time, Snap took a more cautious "wait and see" approach, wanting to see if people actually used smartwatches before building an app. New app launches are not always perfect. It is still early days for the watchOS app, as some users on Reddit have reported the app being stuck on the loading screen. Hopefully, Snap will address these initial teething problems quickly. This expansion to Apple Watch comes after the company abandoned its widely criticized three-tab app redesign following a notable drop in its North American daily active users and significant negative feedback. That redesign, introduced back in September 2024, was meant to simplify things but ended up frustrating many, leading Snap to reverse course after about seven months and work on a refined five-tab layout. Meanwhile, Android smartwatch users with Wear OS are still in a different boat, as there is no official, dedicated Snapchat app for that platform yet. They can typically only receive notifications, and attempts to sideload the full Android app often result in a clunky experience.
  • Recent Achievements

    • Week One Done
      CHUNWEI earned a badge
      Week One Done
    • One Year In
      survivor303 earned a badge
      One Year In
    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
  • Popular Contributors

    1. 1
      +primortal
      419
    2. 2
      +FloatingFatMan
      182
    3. 3
      snowy owl
      181
    4. 4
      ATLien_0
      174
    5. 5
      Xenon
      138
  • Tell a friend

    Love Neowin? Tell a friend!