How to load SQL Server data into a combobox in Android Studio using Volley?

Asked

Viewed 185 times

2

Currently, for testing purposes, I am using a spinner, but I now want to implement the data that comes from the BD. Is it possible to put in this same spinner or should I create another application? I really don’t know how to start, or what to use. (Note: I’m a beginner on Android and I’m using Volley + PHP Nector in all database requests). I created by an internet manual, a spinner and a class, only I’m not getting an answer. Returns empty in the spinner.

php.

    <?php

    $serverName = "server"; 
    $connectionInfo = array( "Database"=>"database");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);

    if( !$conn ) {
        echo "Não conectou";
         die( print_r( sqlsrv_errors(), true));
    }


    $sql = "SELECT nomeTorneio FROM Torneios";
    $stmt = sqlsrv_query( $conn, $sql );
    if( $stmt === false) {
        echo "sem conexao, sem dados\n";
        die( print_r( sqlsrv_errors(), true) );
    }


    $json = array();
    do {
         while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            $json[] = $row;
         }
    } while ( sqlsrv_next_result($stmt) );
        echo json_encode($json);
        sqlsrv_free_stmt( $stmt);
        sqlsrv_close( $conn);

?>

Partidaconfiguracao.class

public class PartidaConfiguracao extends AppCompatActivity {
    Spinner spinner;
    String URL = "http://localhost/busca_torneios.php";
    ArrayList<String> CountryName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_partida_configuracao);
        CountryName=new ArrayList<>();
        spinner=(Spinner)findViewById(R.id.spinnerTorneio);
        loadSpinnerData(URL);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String country=   spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
                Toast.makeText(getApplicationContext(),country,Toast.LENGTH_LONG).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // DO Nothing here
            }
        });
    }
    private void loadSpinnerData(String url) {
        RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject=new JSONObject(response);
                    if(jsonObject.getInt("success")==1){
                        JSONArray jsonArray=jsonObject.getJSONArray("torneios");
                        for(int i=0;i<jsonArray.length();i++){
                            JSONObject jsonObject1=jsonArray.getJSONObject(i);
                            String country=jsonObject1.getString("nomeTorneio");
                        }
                    }
                    spinner.setAdapter(new ArrayAdapter<String>(PartidaConfiguracao.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
                }catch (JSONException e){e.printStackTrace();}
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        int socketTimeout = 30000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);
        requestQueue.add(stringRequest);
    }
}

Result in browser:

{"tournaments":[{"nomeTorneio":"Brasileirao"},{"nomeTorneio":"Copa Do Brasil "},{"nomeTorneio":"Gauchao "},{"nomeTorneio":"Eurocopa"},{"nomeTorneio":"Campeonato Da Paraiba"},{"nomeTorneio":"Campeonato Teste "}]}

  • It is possible, but Arrayadapter has to contain the list that was generated after consultation with the bank. The way it is there your question gets very wide because there are several ways to do this.

  • 1

    That is, first you connect to the server with Volley... Generates the list that will be used... Then you enter the list in Arrayadapter... And then you insert the array into the spinner.

  • Got it. From the bank to an Adapter array, and from this to popular spinner. I’ll try that and get back to you soon. Thanks so far.

  • Andrei, I tried some 3 different modes, but without success. I could take a look at the new code I made?

  • I’ll take a look later.

  • Andrei, I tried a few times as you suggested, with parsed Json data playing on an array, which enters the Adapter, which populates the spinner. See below the final answer second solution you presented. THANK YOU!

Show 1 more comment

1 answer

1


Here is the solution, as Andrei proposed. Thank you.

Aqui popula o spinner com dados do banco.

private void loadSpinnerData(String urlSpin) {
    final ArrayList<String> listaTorneios = new ArrayList<>();
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    StringRequest stringRequest = new StringRequest(Request.Method.GET, urlSpin, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("torneios");
                listaTorneios.add("Selecione o torneio:");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    idTorneio = jsonObject1.getInt("ID_torneio");
                    String nomeTorneio = jsonObject1.getString("nomeTorneio");
                    String var = String.valueOf(idTorneio);
                    listaTorneios.add(var+" "+nomeTorneio);
                }
                spinner.setAdapter(new ArrayAdapter<String>(AcoesFutsal.this, android.R.layout.simple_spinner_dropdown_item, listaTorneios));

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    requestQueue.add(stringRequest);
}

Here shows the spinner:

loadSpinnerData(URLsp);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String torneio = spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

And here takes the selected item in the spinner

final String stIDnomeTorneio = (String) spinner.getSelectedItem();
  • 1

    very good! Congratulations!

  • Put it down as right!

  • Comments I can only put as useful, not as correct. I can only put "correct" for answers. Answer with any comment I vote for there. Thank you!

  • No Paul! Put YOUR ANSWER as correct!

  • 1

    Okay, Andrei. I didn’t understand. Okay.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.