Arraylist 不工作,项目不堆叠

Posted

技术标签:

【中文标题】Arraylist 不工作,项目不堆叠【英文标题】:Arraylist not working, items do not stack up 【发布时间】:2020-05-21 07:20:53 【问题描述】:

所以,我试图从database 获取一些信息并将其保存到ArrayList,以便稍后我可以根据该列表中的lengthitems 动态添加buttons

代码:

private List<String> probleme = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    if (SharedPrefManager.getInstance(this).isLoggedIn()) 
        CautaProbleme();
        for(int i=0; i<probleme.size(); i++) 
            Button myButton = new Button(this);
            myButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            myButton.setText(probleme.get(i));
            LinearLayout layout = (LinearLayout) findViewById(R.id.linear_home);
            layout.addView(myButton);
        
    `

CautaProbleme 方法:

private void CautaProbleme()
    class CautaProbleme extends AsyncTask<Void, Void, String> 
        User user = SharedPrefManager.getInstance(getApplicationContext()).getUser();
        final String departament = String.valueOf(user.getDepartament());
        @Override
        protected String doInBackground(Void... voids) 
            //creating request handler object
            RequestHandler requestHandler = new RequestHandler();

            //creating request parameters
            HashMap<String, String> params = new HashMap<>();
            params.put("departament", departament);

            //returing the response
            return requestHandler.sendPostRequest(URLs.URL_PROBLEME, params);
        

        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            //displaying the progress bar while user registers on the server
        

        @Override
        protected void onPostExecute(String s) 
            super.onPostExecute(s);
            //hiding the progressbar after completion

            try 
                //converting response to json object
                JSONObject obj = new JSONObject(s);

                //if no error in response
                if (!obj.getBoolean("error")) 
                    JSONArray problemeArray = obj.getJSONArray("probleme");
                    for (int i = 0; i < problemeArray.length(); i++) 
                        JSONObject problema = problemeArray.getJSONObject(i);
                        // Verificare daca s-au primit probleme trimise de server
                        if (!problema.isNull("Problema")) 
                            String situatie = problema.getString("Problema");
                            probleme.add(situatie);
                        
                    

                 else 
                    Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
                
             catch (JSONException e) 
                e.printStackTrace();
            
        
    
    CautaProbleme ru =new CautaProbleme();
    ru.execute();

JSON 响应没关系,problemeArray 看起来不错,但问题是.add() 命令没有将strings 添加到列表中,所以用于创建buttonsfor 确实什么都不做,有一个空的list。我已经在全球范围内声明了private List probleme = new ArrayList&lt;&gt;();

【问题讨论】:

如果方法名称以大写字母开头,有经验的开发人员会更难阅读。请遵循推荐的命名约定geeksforgeeks.org/java-naming-conventions 【参考方案1】:

AsyncTask 是异步执行的,所以你必须等到执行完成才能获取数据。更好的选择是在操作完成时使用回调来调用。

步骤 - 1:onCreate 中移除按钮创建代码并将其添加到回调中

@Override
protected void onCreate(Bundle savedInstanceState) 

    ....

    if (SharedPrefManager.getInstance(this).isLoggedIn()) 
        CautaProbleme();
    

在此处添加回调函数和更新逻辑

private void createButtonDynamically() 
    LinearLayout layout = (LinearLayout) findViewById(R.id.linear_home);

    for (int i = 0; i < probleme.size(); i++) 
        Button myButton = new Button(this);
        myButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        myButton.setText(probleme.get(i));
        layout.addView(myButton);
    

步骤 - 2: 操作完成时从onPostExecute 调用回调

class CautaProbleme extends AsyncTask<Void, Void, String> 

    ....

    @Override
    protected void onPostExecute(String s) 
        super.onPostExecute(s);

        ....

        createButtonDynamically();
    

【讨论】:

现在就像一个魅力。事实上,我没想过等到AsyncTask 结束。【参考方案2】:

CautaProbleme 在您进行for 循环时在后台运行。 您应该将带有onReady() 方法的接口发送到ASyncTask 并从onPostExecute 调用它。

然后,在你实现(Activity)onReady()的地方,你可以做

 for(int i=0; i<probleme.size(); i++) 
        Button myButton = new Button(this);
        myButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        myButton.setText(probleme.get(i));
        LinearLayout layout = (LinearLayout) findViewById(R.id.linear_home);
        layout.addView(myButton);
    

【讨论】:

以上是关于Arraylist 不工作,项目不堆叠的主要内容,如果未能解决你的问题,请参考以下文章

Array和ArrayList的异同点

java用poi往excel里写数据遇到换行问题

纯并行添加的Java ArrayList.add() 方法线程安全吗? [复制]

Java集合框架

ArrayList详细介绍

Java集合之ArrayList