Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling UI thread method from AsyncTask

I have a problem with calling the setadapter() method from the inside of AsyncTaskActivity onPostExecute() method. I've read docs about AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result) but found no answer how to achieve that. Should I use an Intent to do so? I'm new to a Android development so please forgive me if it's a kind of stupid question.

MainActivity

public class MainActivity extends ListActivity {

private String[] columns = new String[] {"foreign_word", "native_word"};
private int[] target = new int[] { R.id.foreign_word, R.id.native_word };
private Cursor cur = null;

 @Override
 protected void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);

     new AsyncTaskActivity(this).execute();
 }

    public void setadapter(Cursor cur)  {
        SimpleCursorAdapter aaa = new SimpleCursorAdapter(this.getApplicationContext(), R.layout.list_entry, cur, columns, target, 0);
        this.setListAdapter(aaa);
    }
}

AsyncTaskActivity

public class AsyncTaskActivity extends AsyncTask<Void, Void, Cursor> {

Activity activity = null;
private SQLiteDatabase db = null;
private String[] selection = {"_id", "native_word", "foreign_word"};
Cursor cur = null;


public AsyncTaskActivity(Activity activity) {
    this.activity = activity;
}

@Override
protected Cursor doInBackground(Void... params) {
    DbAdapter mSQLadapter = new DbAdapter(activity);
    db = mSQLadapter.getWritableDatabase();
    Cursor cur = db.query("words", selection, "foreign_word='car'", null, null, null, null);
    return cur;
}

protected void onPostExecute(Cursor cur) {

// I'd like to call setadapter() ,passing it Cursor as a parameter

   }

}
like image 984
XorOrNor Avatar asked Sep 20 '26 16:09

XorOrNor


1 Answers

Assuming that your AsyncTask is always called by MainActivity, do this

protected void onPostExecute(Cursor cur) {
   MainActivity mActivity = (MainActivity) activity;
   mActivity.setadapter();
   }

You can specify more parameters for your setAdapter method so you can pass off the Cursor, String Array, etc.

However an even better method if the AsyncTask is only called from MainActivity is to make this AsyncTask a private inner class inside MainActivity. This will allow it to access all the global variables and methods of MainActivity

like image 118
A--C Avatar answered Sep 22 '26 10:09

A--C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!