在我的应用程序中,我尝试将书籍与MBaaS Backendless同步。因此,我从Backendless获取它们之后生成一个List以保存所有书籍。我从服务器获得了正确的数据(没有重复),但我的for循环开始得太早,所以没有数据可以迭代。 在开始for循环之前,如何轻松完成List的填充? 这是我的代码:
final List<String> all_books_without_duplicates = new ArrayList<String>();
// queryId = Id of the user
Backendless.Data.of(Books.class).find(queryId, newLoadingCallback<BackendlessCollection<Books>>(this, getString(R.string.loading_books), true) {
@Override
public void handleResponse(BackendlessCollection<Books> booksBackendlessCollection) {
Iterator<Books> booksIterator = booksBackendlessCollection.getCurrentPage().iterator();
while (booksIterator.hasNext()) {
Books booksonline = booksIterator.next();
final String book_title = booksonline.getBookTitle();
// avoid duplictes
if (!all_books_without_duplicates.contains(book_title)) {
all_books_without_duplicates.add(book_title);
Log.d("added book title:", book_title);
}}}});
Log.d("for-loop elements: ", String.valueOf(all_books_without_duplicates));
for (int x=0; x<all_books_without_duplicates.size(); x++){
final String book_title_value = all_books_without_duplicates.get(x);
String whereClause = "booktitle LIKE '%" + book_title_value + "%'";
QueryOptions queryOptions = new QueryOptions();
queryOptions.setRelated(Arrays.asList("book"));
BackendlessDataQuery query = new BackendlessDataQuery(queryOptions);
query.setWhereClause(whereClause);
// get all book-ids from Backendless where title is x
Backendless.Data.of(BookIds.class).find(query, new LoadingCallback<BackendlessCollection<BookIds>>(MainActivity.this, getString(R.string.loading_books), true) {
@Override
public void handleResponse(BackendlessCollection<BookIds> bookIDsBackendlessCollection) {
super.handleResponse(bookIDsBackendlessCollection);
Iterator<BookIds> bookIDsSyncIterator = bookIDsBackendlessCollection.getCurrentPage().iterator();
while (bookIDsSyncIterator.hasNext()){
BookIds book_ids = bookIDsSyncIterator.next();
String book_id_be = book_ids.getObjectId();
// get all book-ids from SQLite-DB
DatabaseHelper db=new DatabaseHelper(getApplicationContext());
final List<String>bookIds_sql = db.getAllBookIds();
// save new book in SQLite if it lacked so far
if(bookIds_sql.contains(book_id_be)){
// book already exists
}
else{
saveNewBookFromBackendless(book_id_be);
}
}}});}
答案 0 :(得分:0)
正在发生的是您的代码正在执行find
方法,该方法异步执行后端调用(在不同的线程中),然后它直接进入Log.d
和{ {1}}循环指令,只有当后端响应准备就绪时,它才会调用for
方法。
解决此问题的最简单方法是在handleResponse
循环之后将for
循环移到handleResponse
内;取决于您希望如何构建代码,还有其他方法可以通过在方法中编写for循环并从while
调用此方法来实现,并且还有一些方法可以选择执行此代码的线程。但问题中没有足够的信息可以为您提供适当的建议。