我尝试编写一个图书馆应用程序。我使用 php 和 MySql。
在我的 mainActivity 中,我调用返回 3 个列表的函数:书籍、购物车和订单。第一个已满,但购物车和订单都是空的。这些函数在 myAsyncTask 中调用。
new AsyncTask<Void, Void, ArrayList<Book>>() {
@Override
protected void onPreExecute() {
}
@Override
protected ArrayList<Book> doInBackground(Void... voids) {
listBook = backend.getBookInStock();
billForMember = backend.getBillForMember(member.getMemberID());
cart = backend.getCart(member.getMemberID());
return listBook;
}
@Override
protected void onPostExecute( ArrayList<Book> list) {
searchView = (SearchView) findViewById(R.id.searchView);
listView = (ListView) findViewById(R.id.listView);
bookAdapter = new BookAdapter(CrownLibrary.this, listBook, AccessType.DIRECTOR, SearchType.BOOK_IN_STOCK, 0);
bookAdapter.addListener(CrownLibrary.this);
listView.setAdapter(bookAdapter);
}
}.execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(CrownLibrary.this, CrownLibraryDetails.class);
intent.putExtra(IntentExtra.BOOK.toString(), bookAdapter.getItem(i));
intent.putExtra(IntentExtra.MEMBER.toString(), member);
startActivity(intent);
}
});
当我调试我的应用程序时,该函数调用这 3 个函数,并很好地初始化它们。但在 doInBackground 之后,应用程序不会执行 onPOstExecute。我知道这一点,因为 listView (其位于 onPostExecute 中)从未初始化并且应用程序停止。
01-17 17:28:25.956 8002-8002/com.example.lilo.ebookstore E/AndroidRuntime: Caused by: java.lang.NullPointerException
01-17 17:28:25.956 8002-8002/com.example.lilo.ebookstore E/AndroidRuntime: at com.example.lilo.ebookstore.CrownLibrary.onCreate(CrownLibrary.java:94)
我不知道。
最佳答案
您需要在 AsyncTask 之外分配 View 。 onPostExecute 在后台执行不同线程上的操作后调用。在此之前,主线程已经到达分配 OnItemClickListener 的行。只需移动线条即可
searchView = (SearchView) findViewById(R.id.searchView);
listView = (ListView) findViewById(R.id.listView);
在 AsyncTask 之外。
关于php - onPostExecute 永远不会被调用,但 doInBackground 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34841486/