我在活动上按下按钮,在setOnClickListener上,我有一个方法可以从url获取数据,然后尝试将其保存在数组中,但是当我第一次单击时,我什么也没有得到,但是如果我返回然后再次单击,我得到数据。

package com.example.fabio.domoticaa;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class AddCenario extends AppCompatActivity {
    String input,pls, kappa;
    Integer podeIR = 0,x;
    EditText editText,esc;
    String  idDivisao;
    private String my_sel_items;
    ArrayAdapter adapter;
    String[] id = new String[1];
    ArrayList<String> getid = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        final ArrayList<String> divisoes = new ArrayList<>();
        my_sel_items=new String();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_cenario);
        editText = (EditText) findViewById(R.id.editText4);
        final ListView listView = (ListView) findViewById(R.id.listview);

        Button btnCriar = (Button) findViewById(R.id.button_criarr);


        RequestQueue queue = Volley.newRequestQueue(AddCenario.this.getApplicationContext());
        try {
            String url = "http://brunos.000webhostapp.com/teste/listar_divisoes.php";
            JsonArrayRequest jsonRequest = new JsonArrayRequest
                    (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
                        public void onResponse(JSONArray response) {
                            try {
                                adapter = new ArrayAdapter(getApplicationContext(),R.layout.custom_divi_mult,divisoes);
                                Integer i = 0;
                                String divisao;
                                while (i!= response.length()){
                                    JSONObject obj = response.getJSONObject(i);
                                    idDivisao = obj.getString("id");
                                    divisao = obj.getString("descricao");
                                    divisoes.add(divisao);i++;
                                }
                                listView.setAdapter(adapter);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            error.printStackTrace();
                        }
                    });
            queue.add(jsonRequest);
        } catch (Exception ex) {
        } finally {
        }



        btnCriar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SparseBooleanArray checked = listView.getCheckedItemPositions();
                ArrayList<String> selectedItems = new ArrayList<String>();
                for (int i = 0; i < checked.size(); i++) {
                    // Item position in adapter
                    int position = checked.keyAt(i);
                    // Add sport if it is checked i.e.) == TRUE!
                    if (checked.valueAt(i))
                        selectedItems.add((String) adapter.getItem(position));
                }

                final String[] outputStrArr = new String[selectedItems.size()];

                for (int i = 0; i < selectedItems.size(); i++) {
                    outputStrArr[i] = selectedItems.get(i);
                }



                test1(outputStrArr);

                String[] teste = new String[getid.size()];

                for (int f = 0; f < getid.size();f++){
                    teste[f] = getid.get(f);
                }

                for (int va = 0; va < teste.length;va++){
                    pls +=teste[va];

                }
                editText.setText(pls);

                Intent x = new Intent(AddCenario.this, GerirCenario.class);
                Bundle b = new Bundle();


                b.putStringArray("selectedItems", outputStrArr);
                String text = editText.getText().toString();
                x.putExtra("ola" , text);
                x.putExtras(b);
                startActivity(x);
                listView.getSelectedItem();
            }
        });

    }


    public void test1 (String[] outputStrArr){
        Log.e("teste", String.valueOf(outputStrArr.length));
        for (x = 0; x < outputStrArr.length;x++) {
            try {

                RequestQueue queue = Volley.newRequestQueue(AddCenario.this);

                String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + outputStrArr[x] ;

                JsonArrayRequest jsonRequest = new JsonArrayRequest
                        (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
                            @Override
                            public void onResponse(JSONArray response) {
                                try {
                                    for (int i = 0; i < response.length(); ++i) {
                                        JSONObject obj = response.getJSONObject(i);
                                        id[0] = obj.getString("id");
                                        getid.add(id[0]);
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                error.printStackTrace();
                            }
                        });
                queue.add(jsonRequest);

            } catch (Exception ex) {
            }
        }
    }

}

最佳答案

这是因为您的JsonArrayRequest是异步的。您可以在onResponse中获取数据。因此,您对数据的处理也应该放在其中。否则,您将进入数据逻辑,而不必等待JsonArrayRequest完成其响应(检索数据)。

test1(outputStrArr)以下与处理/作用于新数据outputStrArr有关的所有内容

String[] teste = new String[getid.size()];
  ...
listView.getSelectedItem();


应该移到onResponse

public void onResponse(JSONArray response) {
    try {
        for (int i = 0; i < response.length(); ++i) {
            JSONObject obj = response.getJSONObject(i);
            id[0] = obj.getString("id");
            getid.add(id[0]);
        }
        // MOVE YOUR STUFF TO HERE
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

10-06 01:04