SMN Shuvo
SMN Shuvo

Reputation: 5

Spinner doesn't show data when selected, also shows the spinner data lately

I am using a spinner that loads the value from making a GET request to my web server. But the problem is that the spinner does show the loaded value (though lately), but doesn't show the selected value. spinner image after selected

I checked the background color. Tried running the code on UI Thread, but it doesn't work.

<Spinner
            android:id="@+id/setup_wizard_spinner_year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            >
        </Spinner>

The activity

    adapterYear = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, viewModel.getData("Year"));
    iYearSpinner.setAdapter(adapterYear);

The method

public List<String> getData(String query){
    OkHttpClient httpClient = new OkHttpClient();
    String URL = "mysite.com?query=" + query;
    List<String> spinnerDataList = new ArrayList<String>();
    Request request = new Request.Builder()
                        .url(URL)
                        .build();
    httpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            if(response.isSuccessful()){
                String webResponse = response.body().string();
                JSONArray jsonArray = null;
                try {
                    jsonArray = new JSONArray(webResponse);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                for (int i=0;i<jsonArray.length();i++){
                    spinnerDataList.add(jsonArray.optString(i));
                }

            }
        }
    });
    return spinnerDataList;
 }

Upvotes: 0

Views: 173

Answers (2)

SMN Shuvo
SMN Shuvo

Reputation: 5

Fixed: Populate the data in UiThread, make the network call in another thread. Wait till the thread is finished executing. It may slow the apps, but I was OK with that, used handler to show spinner as my next task is depended more upon on what data I get and select.

Upvotes: 0

EraftYps
EraftYps

Reputation: 818

You're fetching the spinnerDataList from the internet, it'll take time to get the data.

Try returning LiveData and observe it in the Activity and then set the list to the adapter.

You're using R.layout.support_simple_spinner_dropdown_item instead use R.layout.support_simple_spinner_item in the ArrayAdapter constructor.

Set the layout resource to create dropdown views adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

Upvotes: 1

Related Questions