当按钮的setOnClickListener在2次执行时

时间:2017-01-09 19:16:21

标签: java android arrays json

我按下活动上的按钮,在setOnClickListener上我有一个方法从网址获取数据,然后我尝试将其保存在一个数组中,但是当我第一次点击时我什么也得不到但是如果我回去再次点击,我得到了数据。

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) {
            }
        }
    }

}

1 个答案:

答案 0 :(得分:1)

这是因为您的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();
    }
}