How to Clear Spinner Value in Android

Written by Biajid

Hi there, I'm Biajid, a devoted tech lover who specializes in tackling technical difficulties relate...

https://www.androidsparks.com

   Review by Biajid

Hi there, I'm Biajid, a devoted tech lover who specializes in tackling technical difficulties relate...

https://www.androidsparks.com

How
Why

Last Updated: July 9, 2023


One of the goals of creating an application is to provide a good user experience. One of the use cases is the use of a spinner.  Many newbies don’t actually know how to clear spinner value in Android.

A spinner is a dropdown list from which you can select one option. A typical example is when creating an account for a website, you may need to insert your country. When you type a few letters in the field, a dropdown menu comes with a list of countries having similar letters. You can select your country from that list without typing the whole thing.

Now you can understand the usefulness of having a spinner in your Android app.

What is the use of a Spinner?

One should develop the application in such a way that the user has to do the least amount of work to perform a task. It is essential to be aware of this when developing an application. There are various fields where one can apply this principle. Spinner is one of those. As mentioned before, a spinner is similar to a dropdown list.

In this article, we will show you how you can clear the spinner value when entering a new one.

What Does It Mean to Clear a Spinner Value?

For those who are unsure, clearing a spinner means emptying a spinner with no items. For example, you have two spinners in your app. One is for selecting the country, and the other is for choosing the state. When you choose a value from the first spinner, you want the spinner to be clear, right?  You don’t want the values of the first spinner to flood the second spinner. To avoid this problem, we need to clear the spinner values before moving to the next spinner.

How to Clear a Spinner Value?

The best way to learn something is by doing it with the instructor. For this, we have devised an example for you to practice. Through this, you will be able to learn how to clear a spinner value in no time!

In this example, we will create two spinners. The first spinner is for selecting the year, and the latter spinner is for choosing the date. Our example is given using Kotlin, but the same applies to Java as well. The process of clearing a spinner value is given below:

  • Create a new project in Android Studio and select Empty Activity.
  • In the activity_main.xml file, add the following code. This code is to create our layout, add a button and spinners.
<?xm1 version="1.on encoding-"utf-8"?>
RelativeLayout xmins:android-"http://schemas.android.com/apk/res/android"
android: layout width="match parent" android: layout height-'match_parent"»
<LinearLayout
android: layout width-'match_ parent" android: layout height-twrap content" android:gravity="center vertical" android:orientation-"horizontal" android:padding="10dp">
<RelativeLayout
android: layout width="odp" android: layout height-"wrap content" android:layout marginstart-Tadp" android: layout marginEnd="3dp" android:layout weight="30" android-background-nedrawab1e/spinnel pg" android:padding="2dp">
<Spinner
android:id="@+id/yearSpinner" android:layout_width="match_parent"
android:layout height="wrap content" android:entries="@array/years" android:textAlignment="center" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/layoutDateSpinner1" android:layout width="odp"
android: layout height="wrap content" android: layout marginstart="3dp" android:layout marginEnd="3dp" android: layout weight="45"
android:background="(drawable/spinner bg" android:padding="2dp">
candroidx.appcompat.widget.AppCompatSpinner
android: id="(+id/weekSpinner"
android:layout widthe"match parent"
android:layout height="vrap content"
android:layout marginstart="5dp"
android:layout marginEnd-"Sdp"
android:textA11gnment=”centex"/
</RelativeLayouts
candroidx.appcompat.widget.AppCompatButton
android: id="@+id/buttonSearch"
android:layout width=*0dp"
android: layout height-"match parent"
android: layout marginstart="'5dp"
android: layout marginEnd= "Sdp"
android: layout weight=*25"
android:background="@drawable/buttonbg"
android:minHeight="25dp"
android: text="@string/search"
android: textColor="@android: color/white"
android:textsize="12sp" /5
</LinearLayout>
«TextView
android:id="@+id/hintTextView"
android:layout width="wrap content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android: text="selected week: "/>
  • Now, write the following code in the strings.xml file. This portion adds the options in the string, which the spinner will display.
<resources>
<string name="app name"›SpinnerTest1</string>
 <string name="search"›Search‹/string>
<string-array name="years"> <item>2019</items <item>2020</item> <item>2021</items <item>2022</item> <item>2023</item> <item>2024</item> <item>2025</item> <item>2026</item> <item>2027</item> <item>2028</items <item>2029</items <item>2030</item>
</string-array>
</resources>

Image for better understanding

How to Clear Spinner Value in Android
  • Once you complete this part, it’s time to add some styles to our application. If the software doesn’t look good, the user wouldn’t want to use it, right? Write the following code in the spinner_bg.xml file to style the spinners.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android: shape="rectangle">
 <corners android:radius="10dp" /> <solid android:color="@android: color/transparent" /› <stroke
android:width="0.5dp" android:color="#656565" />
</ shape>
How to Clear Spinner Value in Android
  • Now it’s time to style the button. This code is for the button_bg.xml file.
<?xm1 version="1.0" encoding="utf-8"?> 
<shape xmlns: android="http: //schemas.android.com/apk/res/android"
android: shape="rectangle"> <corners android:radius="15dp" /> <solid android:color="#2196F3" />
</ shape>
How to Clear Spinner Value in Android
  • Once you finish styling, the interface should look like this.
How to Clear Spinner Value in Android
  • We are almost at the end. Now, we work on the main activity. Open the MainActivity.kt / MainActivity.java file to bind the data to the spinners. The code for this part is as follows:
package com.codestringz. spinnertest1
import androidx. appcompat. app. AppCompatActivity 
import android.os. Bundle 
import android.view.View import android.widget.* import java. text. DateFormat
import java.text. SimpleDateFormat import java.util.* 
import kotlin.collections.ArrayList
Telass MainActivity : AppCompatActivity () (
override fun onCreate (savedInstanceState: Bundle?) (
super. onCreate (savedInstanceState)
setContentView(Alayout.activity main)
initUI ()
private fun initUi() (
find views
val yearspinner = findViewById<Spinner> (R.id.yearSpinner)
val weekSpinner = findViewById<Spinner> (R.id.weekSoinner)
val searchButton - findViewById<Buttons (R.id. buttonSearch)
val hintTextView = findViewById<TextView> (R.id.hintTextView)
/create a blank week spinner adapter
val weekSpinnerAdapter = ArrayAdapter (
this, android.R.layout. simple_spinner_item, arrayListof ("")
)
weekspinnerAdapter.setDropDownViewResource(android.R.layout.simple spinner dropdown item)
/set the adapter to the week spinner
weekSpinner.adapter = weekSpinnerAdapter


//add year spinner item selection yearSpinner.onItemSelectedListener =
object AdapterView.OnItemSelectedListener {
override fun onItemSelected( parent: AdapterView<*>?, view: View?,
) {
position: Int,
id: Long
if (!weekSpinnerAdapter.isEmpty) weekSpinnerAdapter.clear()
//get all weeks of the selected year
val weeks =
getAllSundayDate (resources.getStringArray (R. array. years) [position].toInt()) //add all weeks to the spinner adapter weekSpinnerAdapter.addAll(weeks)
//notify the adapter for the data changes weekSpinnerAdapter.notifyDataSetChanged()
override fun onNothingSelected (parent: AdapterView<*>?) {
}
//set search button click listener
searchButton.setOnClickListener {
if (weekSpinner.selectedItem != null) {
hintTextView.text weekSpinner.selectedItem.toString()
}
}
}

fun getAllSundayDate (year: Int): ArrayList<String> {
//create a blank arrayList
val weekList: ArrayList<String> = ArrayList()
//it helps us to format the date
val dateFormat: DateFormat = SimpleDateFormat ("MM/dd/yyyy", Locale.US)
val calendar
Calendar.getInstance()
//starting from first day and first month of the year
calendar.time = GregorianCalendar (year, Calendar.JANUARY, 1).time
//loop through the all month
for (month in 0..11) {
}
val daysInMonth
calendar.getActualMaximum (Calendar. DAY_OF_MONTH)
//loop through the all days in the month
for (day in 1..daysInMonth) {
}
calendar.set (year, calendar [Calendar. MONTH), day) val dayOfWeek= calendar [Calendar.DAY_OF_WEEK] //check the current day
if (dayOfWeek == Calendar.SUNDAY) {
}
weekList.add(dateFormat. format (calendar.time))
calendar.add (Calendar.MONTH, 1)
return weekList
}
  • Now we add the part about clearing the spinners. We could have added this in the previous point, but in this way, you will have a clearer idea of how and where to use this code. The basic idea is to save a reference to your adapter in a variable. Then, when you want to clear the spinner, call the clear() function to remove the items and then update the spinner view. The code goes as follows:
weekSpinnerAdapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, year); spinner.setAdapter (weekSpinnerAdapter);
weekSpinnerAdapter.clear(); // clear items
weekSpinnerAdapter.notifyDataSetChanged(); // update spinner view
How to Clear Spinner Value in Android
  • After completing all the parts successfully, here’s what the output looks like –
How to Clear Spinner Value in Android

Try switching from one spinner to another and selecting values from them. They should work fine like any other app out there. If you were successful, congratulations! Now you know how to clear a spinner in Android!

Conclusion

Creating an Android app is a challenging task. There are so many things to know of, so many things to maintain. Not to mention, it is time-consuming as well. Some of the features are easy to learn, and some are hard. Again, some are easy but tricky to have a grasp. Clearing a spinner value is one of them. We hope this article helped you in this regard. We tried to make it as easy as possible to make coding simpler for you.

Biajid

Hi there, I'm Biajid, a devoted tech lover who specializes in tackling technical difficulties related to Android phones and operating systems. Over the years, I've gained extensive experience in resolving complex issues and have become a seasoned expert in the field. I'm delighted to have you on my website, and I'm confident that the resources and solutions provided here will prove to be valuable to you

UnhelpfulMostly unhelpfulPossibly helpfulMostly helpfulVery helpful (No Ratings Yet)
Loading...

Last Updated: July 9, 2023

Post View : 711

Recent Posts