Issue
I'm attempting to run a service that accesses local storage, finds what items have not been uploaded to a server, and uploads them. When attempting to assign my file name, I've been using filesDir in my activities. I believe filesDir requires a context, which the service I'm making doesn't have. Is there an alternative to this? Here's my code:
class AuthorizationSaveTask : AsyncTask<Int, Int, String>() {
override fun onPreExecute() {
}
override fun doInBackground(vararg params: Int?): String {
val startId = params[0]
//Get data for list view
var authorizationArrayList = ArrayList<AuthorizationObject>()
try {
//Set target file to authorizations.txt
val targetFile = File(filesDir, "authorizations.txt")
//Create new file input stream
val fis = FileInputStream(targetFile)
//Create new object input stream, using fis
val ois = ObjectInputStream(fis)
//write object input stream to object
//TODO: There has to be a better syntax than this.
authorizationArrayList = (ois.readObject() as ArrayList<*>).filterIsInstance<AuthorizationObject>() as ArrayList<AuthorizationObject>
//close object output stream
ois.close()
//close file output stream
fis.close()
} catch (e: ClassNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return "Service complete $startId"
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
val counter = values[0]
Log.i("BEAU", "Service Running $counter")
}
override fun onPostExecute(result: String) {
Log.i("BEAU", result)
}
Thank you for your time! Please let me know if I can provide any additional information.
Solution
A Service
IS a Context
. More exactly a subclass of it. So you can call getFilesDir()
the same way you would in an Activity
.
However, the code you are posting does not show a Service
but rather an AsyncTask
... I don't know where you are creating your AsyncTask
but you can still pass the Context as a parameter.
EDIT
As it seems that the OP was looking for a way to pass the Context
to the AsynkTask
, I edited my answer.
Change your code to:
class AuthorizationSaveTask : AsyncTask<Int, Int, String>(val context: Context)
And wherever your are creating you Task pass the context.
val task = AuthorizationSaveTask(this)
You might also want to consider passing just the file.
class AuthorizationSaveTask : AsyncTask<Int, Int, String>(val saveDir: File)
And in your Activity
:
val task = AuthorizationSaveTask(filesDir)
Answered By - Yuenbe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.