问题
I read in some links that i need to convert my runOnUiThread to AsyncTask: Android: RunOnUiThread vs AsyncTask
But I am unable to get it done. I am implementing an AutoCompleteText which takes query from a database.
My runOnUiThread along with the new thread (it compiles):
new Thread(new Runnable() {
public void run() {
final DataBaseHelper dbHelper = new DataBaseHelper(ActivityName.this);
dbHelper.openDataBase();
item_list = dbHelper.getAllItemNames();
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
ArrayAdapter<String> sAdapter = new ArrayAdapter<String>(
ActivityName.this,
android.R.layout.simple_dropdown_item_1line,
item_list);
itemNameAct = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView_item_name);
itemNameAct.setAdapter(sAdapter);
}
});
}
}).start();
I put the worker thread part in doInBackground and the runOnUiThread part of code in onPostExecute but it crashes on launch.
回答1:
This is awkward. I asked a question and am answering it myself :/ Actually I was trying AsyncTask(Object, Void, Cursor) and it was not doing me any good.
Here is the class which is working:
class autoComplete extends AsyncTask<Void, Void, Void> {
final DataBaseHelper dbHelper = new DataBaseHelper(ActivityName.this);
@Override
protected Void doInBackground(Void... params) {
dbHelper.openDataBase();
item_list = dbHelper.getAllItemNames();
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<String> sAdapter = new ArrayAdapter<String>(
ClassName.this, android.R.layout.simple_dropdown_item_1line,
item_list);
itemNameAct= (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView_item_name);
itemNameAct.setAdapter(sAdapter);
}
}
and then in onCreate i initialize it as:
new autoComplete().execute();
来源:https://stackoverflow.com/questions/14291215/converting-runonuithread-to-asynctask