2

I am creating an extendable android application and I need to be able to load class which extends Fragment from different application (apk).

String packageName = "com.something.project";
String className = "com.something.project.TestFragment";
String apkName = getPackageManager().getApplicationInfo(packageName, 0).sourceDir;
PathClassLoader classLoader = new PathClassLoader(apkName,ClassLoader.getSystemClassLoader());
Class<?> clazz = classLoader.loadClass(className);
Fragment f = (Fragment)obj;

This was working fine, but when I tried to use Fragment from Android support library(android.support.v4.app.Fragment) to make my application compatible with older Android devices the problem occurred. To be specific I have been getting exception when I try to cast to Fragment (ClassCastException). I know that this is happenning because both Fragment classes are loaded with different ClassLoader, but I was not able to make it work.

BJMg
  • 61
  • 2
  • 5

1 Answers1

1

So I have finally figured it out. I needed to remove android support library from my plugin application so with help from this article http://android-developers.blogspot.cz/2011/07/custom-class-loading-in-dalvik.html I was able to use ant to compile my plugin application without android support library classes. Then it worked like a charm.

BJMg
  • 61
  • 2
  • 5
  • have you been able to migrate this technique to the gradle build system? – Greg Bogumil Dec 28 '13 at 20:57
  • I've got no need to migrate to gradle. Android studio is still early access preview. I don't think that it would be wise to start using it. – BJMg Dec 29 '13 at 00:46
  • thank you for the feedback. I'm just starting with android development and figured I would go with the latest. Unfortunately this item seems to be an issue with the android gradle plugin. compileClasspath is not defined on SourceSet as it is in the standard Gradle build system. – Greg Bogumil Dec 29 '13 at 14:59
  • So your method was to simply not use support libraries? This seems like a workaround, not an actual solution. – Kenny Worden Jul 24 '17 at 14:20