I am loading a jar file at runtime from SD card using DexClassLoader class
final String libPath = Environment.getExternalStorageDirectory() + "/test.jar";
final File tmpDir = getDir("dex", 0);
final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader());
final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("org.shlublu.android.sandbox.MyClass");
final Object myInstance = classToLoad.newInstance();
final Method doSomething = classToLoad.getMethod("doSomething");
doSomething.invoke(myInstance);
In my jar file i am printing few logs which is working fine.Now what i am trying to do is print a Toast from jar file. While doing this the exception i am getting is java.lang.reflect.InvocationTargetException. I know why we get this exception and reason behind it is nullpointer exception at context using it while printing toast. So its not a duplicate of
What could cause java.lang.reflect.InvocationTargetException?
cause behind it is
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
code in jar file is
public class MyClass extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public void doSomething() {
Toast.makeText(getApplicationContext(), "MyClass: doSomething() called.", Toast.LENGTH_LONG).show();
Log.e(MyClass.class.getName(), "MyClass: doSomething() called.");
}}
Can anyone help me to achieve this.Any help will be appreciated.
Edit: what i am trying to do is I have a library of my own which many of my clients are using...what i want is that to load my library from user's SD card..and i want to update the library when ever i want without user's knowledge and without any version updates.Library includes few interfaces,Fragments and Activities. so now i am able to load my library from sd card and can invoke basic functions.Now the main challenge is to implement interfaces from library and invoking functions having usage of context in them.
Any samples or hint involving such operations will be much helpful.
doSomething
you callgetApplicationContext()
... – OliveroContenxt.startIntent
... but such activity had to be declared in manifest ... solution is to use Fragments instead – Olivero@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setText("This is fragment loaded dynamically"); return textView; }
– Olivero