Android - 将ArrayList从后台线程返回到活动

时间:2014-01-30 04:16:59

标签: java android arraylist thread-safety

我有一个名为BuildingActivity的活动,扩展了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?
        }
        }   
    }

此后我的目标是从此返回的建筑物列表中创建一个列表。点击建筑物后,另一个活动将打开。我如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:1)

  

如何确保仅在数据之后执行此部分代码   已被退回?

而不是使用Thread在后台执行任务,而是使用AsyncTask提供doInBackground来执行后台操作,并在完成后台任务后在UI线程上运行onPostExecute方法

答案 1 :(得分:0)

这里使用此

public void myMethod(){
     Thread background = new Thread(new Runnable(){
         @Override
         public void run(){
            Looper.prepare();
            //Do your data rerieval work here
               Runnable r=new Runnable() {
               @Override
               public void run() {
                   //return your list from here                      
               }
            };
            handler.post(r);
            Looper.loop();
         }
    });
    background.start();
 }