I'm trying to reduce the noise in my activity classes (Android) and the first thing I've pulled out is the async tasks I had as inner classes. The only issue I'm having is that I'开发者_JAVA百科m not able to pass the AppDelegate ref from the activity to the async task once it's moved out.
Here is my (failed) attempt at it
//here I pass the ref from the activity
public class HelloAndroidActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
GetSessionsAsyncTask task = new GetSessionsAsyncTask(HelloAndroidActivity.this, getApplicationContext());
task.execute();
}
}
//here I push it to a field to use it later (but it fails during the init of this obj)
public class GetSessionsAsyncTask extends AsyncTask<String, Void, List<Session>> {
private Activity activity;
private AppDelegate delegate;
public GetSessionsAsyncTask(Activity activity, Context context) {
this.activity = activity;
this.delegate = (AppDelegate) context;
}
}
Edit
the app delegate I mention above just extends application (android class)
public class AppDelegate extends Application {
}
You need to declare AppDelegate to be your Application class in the Manifest:
<application android:name=".AppDelegate" ... >
...
</application>
A few things:
- What does 'but it fails during the init of this obj'? Do you get an exception? If yes, what? Post stack trace.
- You can get get the application from the activity (first param), so you don't really need the second parameter to your constructor. If you want to keep it, change it to something more specific than
Context
(keep in mind thatAppDelegate
is anApplication
is aContext
) - You might want to execute your task from
onStart()
instead ofonCreate()
to be sure that your activity is properly initialized before your kick off the task.
精彩评论