M
M
maximilan2015-06-17 01:33:50
Java
maximilan, 2015-06-17 01:33:50

How to change the data in the spinner, depending on the selection in another spinner?

In general, the essence, there are two spinners. In one, there is a list of car brands, in the other there are already specific names of cars that should be loaded, depending on the choice in the first spinner.
In MainActivity I set OnItemSelectedListener on the first spinner:

brandsSpinner.setOnItemSelectedListener(new BrandsAdapterListener());

BrandsAdapterListener class code:
public class BrandsAdapterListener extends MainActivity implements OnItemSelectedListener  {

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        String selectedBrand = parent.getItemAtPosition(position).toString();
        JSONObject request = new JSONObject();

        try{
            request.put("BrandName", selectedBrand);
            String json = request.toString();
            String response = new CarTask().execute(
                    "*****", // здесь ссылка на апи
                    json ).get();
            JSONObject responseJsonObject = new JSONObject(response);
            JSONArray cars = responseJsonObject.getJSONArray("cars");
            String[] carsNames = new String[cars.length()];
            for (int i =0;i<cars.length();i++){
                JSONObject car = cars.getJSONObject(i);
                carsNames[i] = car.getString("name");
            }
// собственно пытаюсь использовать вот такой код, только видимо не так его готовлю
            ArrayAdapter carAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, carsNames);
            carAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            Spinner carsSpinner = (Spinner) findViewById(R.id.spinner2);
            carsSpinner.setAdapter(carAdapter);

            // Toast.makeText(parent.getContext(), response, Toast.LENGTH_LONG).show();


        }
        catch (Exception e){
            Toast.makeText(parent.getContext(),"error " + e.toString(), Toast.LENGTH_LONG).show();
        }


        Log.d("brand", selectedBrand);

    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }
}

With this code, toast gets the error "System services not available to Activities before onCreate()” . At the same time, the listener is assigned in the onCreate method, so I don’t know where to dig.
Accordingly, in this class I somehow use the arrayAdapter wrong and don’t so I assign it to the spinner.Does anyone know how to implement this correctly?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question