我有一个名为 BuildingActivity
的 Activity 延伸 ListActivity
.
在onCreate()
方法,我在后台线程中运行 7 个数据库查询。在那个后台线程中,我正在构建一个 ArrayList<String>
查询返回的数据中的对象。
现在,我想归还那个 ArrayList<String>
对象回到我的BuildingActivity
线程。
这是我正在处理的部分代码:
public class BuildingActivity extends ListActivity {
private ProgressBar mProgressBar;
public ArrayList<String> buildings;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_building);
new Thread(new Runnable() {
@Override
public void run() {
ArrayList<String> list;
DataSource dbSource = new DataSource(getApplicationContext());
dbSource.open();
list = dbSource.getBuildingsList();
dbSource.close();
//*** NOW HOW DO I PASS list BACK TO onCreate()?
//*** I WANT TO MAKE buildings = list.
}
}).start();
if(!buildings.isEmpty()) {
// do Something.
// If i do buildings = list in the background thread,
// This will always be executed because the background thread can take
// some time to return the data. How do i make sure this part of
// code is executed only after the data has been returned?
}
}
}
此后我的目标是根据返回的建筑物列表创建一个列表。单击建筑物后,将打开另一个 Activity 。我该如何解决这个问题?
谢谢!
最佳答案
How do i make sure this part of code is executed only after the data has been returned?
不要使用 Thread 在后台执行任务,而是使用 AsyncTask它提供用于在后台执行操作的doInBackground
和完成后台任务后在 UI 线程上运行的 onPostExecute
方法
关于java - Android - 从后台线程返回 ArrayList 到 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21447711/