Beginner
Beginner

Reputation: 29563

Android SQLite Async Task Error

 private class UploadFilesTask extends AsyncTask<Object, Object, Object> {
    @Override
    protected Object doInBackground(Object... arg0) {  
        SQLiteDatabase db = dbs.getWritableDatabase(); 
ContentValues values = new ContentValues();
                        values.put(DBAdapter.KG_ID,  "q");
                        values.put(DBAdapter.KG_Used,  "False");
                        values.put(DBAdapter.KG_UsedDate,  "");
                    db.insert(DBAdapter.KG_ThisPDAIncidentIDPreAllocations, null, values);

In my application as soon as the code hits the line SQLiteDatabase db = dbs.getWritableDatabase(); i get an error. Can a database be accessed in a AsynTask? It is in a separate service class.

Upvotes: 0

Views: 1448

Answers (3)

Beginner
Beginner

Reputation: 29563

Got it to work...needed this.dbs = new DBAdapter(getApplicationContext());

Upvotes: 1

bytebender
bytebender

Reputation: 7491

Have you tried running SQLiteDatabase db = dbs.getWritableDatabase();outside of the AsyncTask?

If you have never run that code before I could have something to do with your database and not the AsyncTask.

I know I have used database inside of AsyncTask a couple of times now...

Edit: Where is dbs created/declared? I am assuming that is your SqlLiteHelper. If you declared that in your activity than it would be part of the UI thread. Try moving your declaration of dbs inside of doInBackground(Object... arg0).

If you can't move the declaration of dbs inside of doInBackgroud(Object... arg0) (being used other places in Activity) then make sure it is declared with final

I would not recommend trying to pass dbs or db as a parameter to doInBackground.

Upvotes: 0

Stefan Bossbaly
Stefan Bossbaly

Reputation: 6794

I would try to send in the database via the parameters. That way you are not calling UI methods from a different thread. Like so.

UploadFilesTask extends AsyncTask<SQLiteDatabase, Void, SQLiteDatabase>
    @Override
protected SQLiteDatabase doInBackground(SQLiteDatabase... params) {
            //Do something with database and return it
            params[0].doSomeThing();
            return params[0];
}

@Override
protected void onPostExecute(SQLiteDatabase result) {
    //Here is the database after the processing
}

And this is how you would construct and call the AsyncTask.

UploadFilesTask task = new UploadFilesTask();
task.execute(dbs.getWritableDatabase());

Upvotes: 0

Related Questions