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.4 min read

React Native 0.78 Unveiled: New Features, Changes, and Benefits You’ll Love 🚀

Discover React Native 0.78! From React 19 support to Android vector drawables and better iOS integration, explore the latest features, changes, and benefits with examples to make app development faster and smoother. 🌟

.
Aneh Thakur
Aneh Thakur.4 min read

🚀 Encore.ts: Blazing Fast Backend Powerhouse – 9x Faster Than Express.js & 3x Faster Than Bun + Zod

Discover why Encore.ts outshines Express.js and Bun + Zod with 9x and 3x faster performance, respectively. Explore sample code, speed benchmarks, and see how this TypeScript framework redefines backend efficiency! ⚡

Aneh Thakur
Aneh Thakur.4 min read

Trump Unveils U.S. Crypto Strategic Reserve: Bitcoin and Altcoins Surge

Donald Trump announces a U.S. Crypto Strategic Reserve featuring Bitcoin, Ethereum, XRP, Solana, and Cardano, sparking a $300B market rally. Explore the implications and trends as of March 3, 2025.

.
Aneh Thakur
Aneh Thakur.4 min read

Prototype Your Idea in Under an Hour Using AI

Learn to create working prototypes in under an hour using AI tools like Claude and Bolt. Ideal for designers and entrepreneurs with minimal coding skills.

Aneh Thakur
Aneh Thakur.3 min read

How X’s New Grok AI Tools Make Ad Creation and Analysis a Breeze

Discover X’s latest AI-powered features—Prefill with Grok and Analyze Campaign with Grok. Learn how these tools simplify ad creation, boost campaign performance, and help advertisers save time in 2025.

Built on Koows