我正在用在线数据库(Firestore)替换我的Sqlite数据库。为此,数据库的每个答案都会通过回调返回给我。
问题在于,我在填充表的循环中多次调用数据库,并且除非最后声明表,否则该表不可访问,因此无法更改它。
所以我正在寻找一种无需完全修改已经存在的代码即可填充此表的方法。我看到了ArrayBlockingQueue
,但我想知道是否不存在更简单的解决方案。
如果可能的话,我想将所有变量保留在函数中,但我还没有找到解决方案。
我知道在此示例中我们不一定需要一个表,但我想保留它,因为它只是一个示例;)
(SQLite之前)
public int player_in_x_game(int id_player) {
int gamesWherePlayerIsHere = 0;
ArrayList<Games> gamesArray = Database.getGamesArray();
for (Game game: gamesArray)
if(Utils.isPlayerPresentInGame(game.getId(), idPlayer))
gamesWherePlayerIsHere++;
return gamesWherePlayerIsHere;
}
之后(带有回调)
private static int counter= 0;
private static int resultNP = 0;
private static ArrayBlockingQueue<Integer> results;
public static void numberGamesWherePlayerIsPresent(final long idPlayer, final Callbacks.IntCallback callback){
Thread thread = new Thread() {
@Override
public void run() {
games(new Callbacks.ListGameCallback() {
@Override
public void onCallback(ArrayList<Game> gameArrayList) {
counterNumberGamesWherePlayerIsPresent= gameArrayList.size();
results = new ArrayBlockingQueue<>(gameArrayList.size());
for (Game game: gameArrayList){
Utils.isPlayerPresentInGame(game.getId(), idPlayer, new Callbacks.BooleanCallback() {
@Override
public void onCallback(boolean bool) {
if (bool)
results.add(1);
else
results.add(0);
}
});
}
int result;
try {
while (counter > 0) {
result = results.take();
counter--;
resultNP += result;
}
}catch (InterruptedException ie){
ie.fillInStackTrace();
Log.e(TAG,"results.take() failed");
}
callback.onCallback(resultNP);
}
});
}
};
thread.setName("Firestore - numberGamesWherePlayerIsPresent()");
thread.start();
}