我正在尝试创建一个对象列表(在我的示例中为List<Card>
),我使用json将对象添加到此列表中,但列表保持为空。这是我的代码:
public List<Card> readCardsFromJson() {
final List<Card> cards = new ArrayList<Card>();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
HttpReader httpReader = new HttpReader();
httpReader.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
@Override
public void resultReady(String result) {
//Add Card objects to the List<Card>
}
}
});
httpReader.execute("http://eduphp.khk.be/~r0370877/EnkelExpert.json");
}
});
thread.start();
return cards;
}
问题是我返回的列表是空的。我很确定这是一个问题,因为我在这里使用的线程。我认为返回发生在线程实际完成之前,但我该怎么办才能解决这个问题?
我似乎无法绕过这个。任何帮助将不胜感激。
答案 0 :(得分:2)
您应该返回一个非阻塞的Future<List<Card>>
,并允许您在处理HTTP请求时继续计算:
ExecutorService es = Executors.newSingleThreadExecutor();
Future<List<Card>> futureCards = es.submit(new Callable<List<Card>>() {
@Override
public List<Card> call() {
return readCards();
}
});
// do some other work ...
// ... and at some point need the List<Card>
List<Card> cards = futureCards.get(); // blocks until the future is completed
阻止readCards
方法:
private List<Card> readCards() {
final List<Card> cards = new ArrayList<Card>();
HttpReader hr = new HttpReader();
hr.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
@Override
public void resultReady(String result) {
//Add Card objects to the List<Card>
}
});
hr.execute("http://eduphp.khk.be/~r0370877/EnkelExpert.json");
return cards;
}