所以我的代码似乎运行得很好,直到它到达这一行
adapter.notifyDataSetChanged();
logcat中弹出的错误是CalledFromWrongThreadException。调试还显示正在后台线程中运行的处理程序。如何让处理程序绑定到主线程,而不是后台?我以为我只需要在主线程中创建处理程序,但我想我错了,很可能我是andriod的新手。我该如何解决这个问题?
//Imports are included
public class DirectoryActivity extends ListActivity {
private ProgressDialog ProgressDialog = null;
private ArrayList<DirectoryListing> listing = null;
private DirectoryAdapter adapter;
private Runnable viewOrders;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directory);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (listing != null && listing.size() > 0) {
adapter.notifyDataSetChanged();
for (int i = 0; i < listing.size(); i++)
adapter.add(listing.get(i));
Log.e("log_tag", "\nStill running\n");
}
ProgressDialog.dismiss();
adapter.notifyDataSetChanged();
}
};
listing = new ArrayList<DirectoryListing>();
adapter = new DirectoryAdapter(this, R.layout.rows, listing);
setListAdapter(adapter);
ProgressDialog = ProgressDialog.show(DirectoryActivity.this, "Please wait...", "Retrieving data ...", true);
viewOrders = new Runnable() {
@Override
public void run() {
listing = PreparePage.getArrayList();
handler.handleMessage(null);
}
};
Thread thread = new Thread(null, viewOrders, "Background");
thread.start();
}
private static class PreparePage {
protected static ArrayList<DirectoryListing> getArrayList() {
ArrayList<DirectoryListing> listings = new ArrayList<DirectoryListing>();
JSONObject information = GetPageData.getJSONFromURL(url);
Iterator key = information.keys();
while (key.hasNext()) {
String id = (String) key.next();
JSONObject info = null;
try {
info = information.getJSONObject(id);
} catch (JSONException e) {
e.printStackTrace();
}
String name = "", title = "", photo = "";
try {
name = info.get("firstName") + " " + info.get("lastName");
title = info.getJSONObject("position").getString("name");
photo = info.optString("photoPath", "none");
} catch (JSONException e) {
e.printStackTrace();
}
listings.add(new DirectoryListing(name, title, photo));
}
return listings;
}
}
}
答案 0 :(得分:1)
根据我的经验,您应该创建自己的类,扩展AsyncTask类以在后台执行某些操作。这比使用线程+处理程序更简单,更有效。
答案 1 :(得分:1)
尝试拨打handler.sendEmptyMessage(0);
而不是handler.handleMessage(null);
我不知道为什么会导致你看到的错误,但是当我使用处理程序和线程而不是AsyncTask时,这就是我设置它的方式。而且我从未见过这样做错误。
@Nguyen是正确的,虽然AsyncTask是现在处理这些类型的事情的首选方式。它实际上使它更容易做到。