Reputation: 163
I am trying to create a UI Handler to refresh the gridview after i execute the parseURL ASyncTask class and return an Arraylist back to the MainActivity to print out on the gridview.
The code i have compiles and run without any errors but the gridview does not refresh after clicking the button. In the debugger it shows that the parseURL class is successfully returning the list and the handler message has a what
value of 1. However the handler does not seem to work.
Main Activity Class
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.what == 1) {
List<String> list = (List) msg.obj;
updateUI(list);
}
}
}
public void onButtonClick(View v) {
EditText text = (EditText)findViewById(R.id.editText1);
String id = text.getText().toString();
new parseURL() {
@Override
protected void onPostExecute(List<String> list) {
handler.obtainMessage(1, list);
}
}
}
private void updateUI(List<String> list) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
GridView grid = (GridView)findViewById(R.id.gridView1);
grid.setAdapter(adapter);
adapter.notifyDataSetChanged();
//grid.invalidateViews();
}
Upvotes: 0
Views: 759
Reputation: 3621
Try this code.
private final Handler handler = new Handler();
public void onButtonClick(View v) {
EditText text = (EditText)findViewById(R.id.editText1);
String id = text.getText().toString();
new parseURL() {
@Override
protected void onPostExecute(List<String> list) {
handler.post(new Runnable() {
@Override
public void run() {
updateUI(list);
}
})
}
}
}
Or
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.what == 1) {
List<String> list = (List) msg.obj;
updateUI(list);
}
}
}
public void onButtonClick(View v) {
EditText text = (EditText)findViewById(R.id.editText1);
String id = text.getText().toString();
new parseURL() {
@Override
protected void onPostExecute(List<String> list) {
handler.obtainMessage(1, list).sendToTarget();
}
}
}
If you want to use obtainMessage and handleMessage method pairs, you should call sendToTarget
method, like this handler.obtainMessage(1, list).sendToTarget()
. obtainMessage() only returns message.
public final Message obtainMessage ()
Added in API level 1 Returns a new Message from the global message pool. More efficient than creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this). If you don't want that facility, just call Message.obtain() instead.
Upvotes: 2