i got this code off the internet, i suppose to get a list of all the applications on the phone and judging by the comments on the webpage it works but i just cant seem to get it to work for me at all. it seems to be the getPacketManager() that is giving me the problem. can someone please look at the code and explain to me what i have to do to get it working please?
this is my full class… i cant get it to even run, on the 3 locations where there is a “getPackageManager()” it is giving me an error on the left of the screen saying “The method getPackageManager() is undefined for the type getApps”
package cians.app;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class getApps{
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private Drawable icon;
private void prettyPrint() {
System.out.print(appname + "\\t" + pname + "\\t" + versionName + "\\t" +versionCode + "\\t");
}
}
private void listPackages() {
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++) {
apps.get(i).prettyPrint();
}
}
private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
return res;
}}
getPackageManager()is a method of the ‘Context’ class, so you can call it from any object that extends ‘Context’. The classActivityextends context, and your main class extendsActivity, so you are able to callgetPackageManager()from your main class object. If your class doesn’t extendContext(that’s the case of thegetAppsclass), you can’t callgetPackageManager()from it. You’ll need to get your activity context first.EDIT:
OK, you need to pass your activity to this class:
in getApps class add
and change
getPackageManager()...toparent.getPackageManager()...in your main activity, create an object of getApps and then call it to get the info:
now you still need to implement getInfo(), but it shouldn’t be so hard. and one more thing, classes in Java start with capital letter, so instead
getAppsconsider calling itGetAppsorAppsGetter.