AsyncTask 请求数据晚于我根据这些数据创建按钮

AsyncTask request data later than I create button depending on these data

这是我第一次写 Android 代码,我有一个明显的问题。

在 MainActivity 中,我使用 AsyncTask 请求 "Category" 列表来创建按钮。可以单击 MainActivity 按钮,它会重定向到带有附加字符串 "Category(e.g.drink)" 的 GetProductsActivity。在 GetProductsActivity 中,我再次请求服务器使用 "Category" 获取 "Products" 列表以创建产品按钮。

问题是:代码先创建按钮,然后AsyncTask请求服务器获取"Products"列表,我想在创建按钮之前获取"Products"列表。我该怎么办?

"orga.getAttributes"是请求服务器的函数。 这是 MainActivity

public class MainActivity extends AppCompatActivity {
    private ArrayList<String> data = new ArrayList<String>();
    List<String> attributes = new ArrayList<String>();
    List<String> categoryList = new ArrayList<String>();
    final Organisation orga = Organisation.getInstance();
    private class CallSocketTask extends AsyncTask<Integer, Integer, String> {

        protected String doInBackground(Integer... nochnix) {

            orga.SetInit();
            categoryList = orga.getAttributes(orga.GET_CATEGORIES,null,true);

            return null;
        }

        protected void onPostExecute(String string) {
            //attributes = orga.getAttributes(orga.GET_PRODUCTS_BY_CATEGORY,null,true);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new CallSocketTask().execute();//orga.stop();
        //requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_main);
        LinearLayout layer = (LinearLayout) findViewById(R.id.layer);
        //getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.activity_main);
        for(int i=0; i < categoryList.size(); i++)
        {
            Button button = new Button(this);
            button.setId(i);
            final String category = categoryList.get(i);
            button.setText(category);
            //click action
            View.OnClickListener productHandler = new View.OnClickListener(){
                public void onClick(View v) {
                    // doStuff
                    Intent intentMain = new Intent(MainActivity.this ,
                            GetProductsActivity.class);
                    intentMain.putExtra("categroy",category);
                    MainActivity.this.startActivity(intentMain);
                    Log.i("Content "," Main layout Click to Get Products by Category");

                }
            };
            button.setOnClickListener(productHandler);
            layer.addView(button);
        }
    }
}

这里是 GetProductsActivity

public class GetProductsActivity extends AppCompatActivity{
    private ArrayList<String> data = new ArrayList<String>();
    List<String> attributes = new ArrayList<String>();
    final Organisation orga = Organisation.getInstance();
    String category;

    private class CallSocketTask extends AsyncTask<Integer, Integer, String> {


        protected String doInBackground(Integer... nochnix) {
            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                category = extras.getString("categroy");
                Log.i("Category Selected",category);
            }
            //orga.SetInit();
            attributes = orga.getAttributes(orga.GET_PRODUCTS_BY_CATEGORY,category);
            Log.i("Product number ",attributes.size()+"");
            //attributes = orga.getAttributes("getProducts","getCategories","Orangensaft");
            return null;
        }

        protected void onPostExecute(String string) {
            //Log.i("Result ","");
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //this.notifyAll();
        CallSocketTask myTask = new CallSocketTask();
        myTask.execute();//orga.stop();
        setContentView(R.layout.get_products);
        LinearLayout layer = (LinearLayout) findViewById(R.id.productsLayer);
        //getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.activity_main);
        //Bundle extras = getIntent().getExtras();
        //data= extras.getStringArrayList("products");
        Log.i("Product number OnCreate",attributes.size()+"");
        for(int i=0; i < attributes.size(); i++)
        {
            Log.i("Product",attributes.get(i));
            Button button = new Button(this);
            button.setId(i);
            button.setText(attributes.get(i));

            layer.addView(button);
        }
    }
}

将设置按钮的代码移到 onPostExecute 中。

解决问题很简单:在 onCreate() 函数中使用 Thread.sleep() ,这样循环按钮就可以等待 AsyncTask 运行.

非静态内部AsyncTask可能会导致内存泄漏,检查一些gotchas

Thread.sleep() 是一种糟糕的方法。如果请求 "Category" 由于网络问题运行时间变长怎么办?

可以在方法 YourActivity.createButtons() 中创建按钮,该方法应在 onPostExecute() 中调用。