The android code is simple:
public void createNewTask(View v) {
try {
MyTask task = MyTask.class.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
return null;
}
}
But when invoking createNewTask method, it will throw an exception:
Caused by: java.lang.RuntimeException:
java.lang.InstantiationException: com.example.MyActivity$MyTask
at com.example.MyActivity.createNewTask(MyActivity.java:214)
... 14 more
Caused by: java.lang.InstantiationException: com.example.MyActivity$MyTask
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1440)
at com.example.MyActivity.createNewTask(MyActivity.java:211)
But if I choose another class, e.g.
MyActivity task = MyActivity.class.newInstance();
Everything will be fine.
Where is wrong in my code? I tested it in an android phone with android 2.3.6.
Found two ways to solve this problem:
or
According to documentation:
Try adding nullary constructor to your class:
EDIT
According to this documentation: