Add dynamic data to spinner in Android application

people

Aneh Thakur

. 3 min read

In this post, I will explain to you how we can set dynamic options into our spinner. We load data from API using OKHTTP if you don’t know how to load data from Web API please check out this post Load data from Web Services using OKHTTP. So let get started.

Prerequisites

Before we start I hope you have good knowledge of Web APIs how we can load them and display their data in our Android Application.

Steps to Create Dynamic Spinner options in Android

Step 1. Create a new Android project using Android Studio.

Step 2. Give Internet Access permission in manifest.xml file and also add usesCleartextTraffic in the application as shown in the below code.

plaintext
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:usesCleartextTraffic="true"
    android:theme="@style/AppTheme">
    /...../
</application>

Step 3. Now we need to add the Okhttp3 library in our project to get data from REST API. Open your MainActivity.java class and add the below method to get data from the server and call that method in your onCreate method.

plaintext
public void getHttpResponse() {

    String url = "https://cakeapi.trinitytuts.com/api/listuser";

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url)
            .header("Accept", "application/json")
            .header("Content-Type", "application/json")
            .build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            String mMessage = e.getMessage().toString();
            Log.w("failure Response", mMessage);
            //call.cancel();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            final String mMessage = response.body().string();

            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e("Response", mMessage);
                }
            });
        }
    });
}

Step 4. Now add Spinner in your Layout file actiity_main.xml

plaintext
<Spinner
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"></Spinner>

Step 5. Now in this final step, we find spinner in layout in our MainActivity.java class and also create an array adapter and initialize our Spinner and later in our method we set data in the spinner as shown in the below code.

plaintext
public class MainActivity extends AppCompatActivity {

    Spinner spinner;
    List<String> usersList;
    ArrayAdapter<String> catAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spinner = (Spinner)findViewById(R.id.spinner);
        usersList = new ArrayList<String>();

        catAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, usersList);
        spinner.setAdapter(catAdapter);

        getHttpResponse();

    }

    public void getHttpResponse() {

        String url = "https://cakeapi.trinitytuts.com/api/listuser";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String mMessage = response.body().string();

                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("Response", mMessage);
                        try {
                            JSONObject users = new JSONObject(mMessage);
                            JSONArray usersArr = users.getJSONArray("users");

                            for(int i =0; i < usersArr.length(); i++){
                                JSONObject user = usersArr.getJSONObject(i);
                                Log.e("user", user.getString("username"));
                                usersList.add(user.getString("username"));
                            }

                            catAdapter.notifyDataSetChanged();


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
        });
    }
}
Image

That’s it, Hope this above code helps you to set dynamic data to your spinner in simple and useful steps.

More Stories from

Aneh Thakur
Aneh Thakur.3 min read

DeepSeek R1: The Free Open-Source AI Model That Rivals GPT-4

Discover DeepSeek R1, the free, open-source AI model that rivals GPT-4 in performance. Licensed under MIT, it’s cost-effective, efficient, and transforming the AI landscape. Try it now!

Aneh Thakur
Aneh Thakur.2 min read

Top 5 Best 5G Phones Under 20000 in India (2025)

Looking for the best 5G phone under 20000 in India? Check out our top picks for 2025, featuring amazing performance, stunning cameras, and excellent battery life. Read now!

.
SWATI BARWAL
SWATI BARWAL.4 min read

10 Most In-Demand SEO Services to Focus on in 2025

Stay ahead of the curve with the 9 most effective SEO services for 2025. From local SEO to content optimization and E-A-T strategies, these essential services will ensure your website ranks higher and drives more traffic.

SWATI BARWAL
SWATI BARWAL.5 min read

Is Blogging Profitable in 2025? Strategies to Thrive in the Digital Era

Discover whether blogging is profitable in 2025 and learn effective strategies to thrive in the digital age with AI tools, niche blogging, and modern monetization methods.

Vishnu Priya
Vishnu Priya.2 min read

Top 3 Phones Under ₹20,000 in India (2025) – Gaming, Cameras & Design

Discover the best smartphones under ₹20,000 in India (2025). From the gaming powerhouse Poco X6 Pro to the stylish Motorola Edge 50 Neo and the sleek Nothing Phone 2A, find the perfect phone for your needs.

.
Built on Koows