I have android app with asynchrounous data sync from server via pressing button. However I need the button to be in all activities of app so I decided to have updateTask as standalone class.
In updateTask I download some xml data. Then use bussines object to process it and finaly let this bussines object to handle saving (or updating) to android db.
Based on ORMLite tutorials I should get databaseHelper by calling OpenHelperManager.getHelper(context, DatabaseHelper.class). My problem is that I need some context for OpenHelperManager which I currently don’t have.
I think that best way is pass activity’s context to updateTask but how do I do it? Also isn’t it weird to pass context further to bussines object which has nothing to do with any activity. And finally: what even is the context? Does it simply stand for activity parent or it has some deeper purpose?
Thanks 🙂
Here’s a couple ways of doing it. I’m pretty sure all 3 should work, but I haven’t tested them myself.
Method 1
Create a constructor for the AsyncTask that takes in the Context and store it so you can use it when it’s executing.
AsyncTask code
Implementation code (for an Activity)
Method 2
Pass the context in as an argument when you call the
executemethodAsyncTask code
Implementation code (for an Activity)
Method 3
Have a static instance of your context that the Async Task can access directly.
A way to do that can be found here: Static way to get 'Context' on Android?
AsyncTask code
Implementation code (for an Activity)