How do I check spinner is empty?

android spinner required validation
android spinner default value empty
spinner with textview in android
android spinner default text
set spinner value android
spinner android
how to set default value in spinner in android
spinner kotlin

I need to check if mine spinner is empty. But when there's a data inside of spinner, it's still showing me toast it's empty, does not contain any data. The main problem is that the spinner is already containing data from database,but program keeps adding new data after again app open.

Main activity

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    spinner = (Spinner) findViewById(R.id.spinner);
    databaseHelper db = new databaseHelper(getApplicationContext());


    if (spinner.getCount() == 0){
        Toast.makeText(MainActivity.this,"Spinner will be populated now",Toast.LENGTH_LONG).show();
        db.insertData();
    }else {
        Toast.makeText(MainActivity.this,"Spinners is already populated",Toast.LENGTH_LONG).show();
    }
    loadData();
}

public void loadData(){
    databaseHelper db = new databaseHelper(getApplicationContext());
    List<String> labels = db.getAllLabels();
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, labels);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(dataAdapter);
}

@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
    String label = adapterView.getItemAtPosition(i).toString();
    Toast.makeText(adapterView.getContext(),"Selected: "+label,Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
}

Database

public databaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_2 + " TEXT," + COLUMN_3 + " TEXT," + COLUMN_4 + " TEXT)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public boolean insertData() {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_2, "1");
    contentValues.put(COLUMN_3, "2");
    contentValues.put(COLUMN_4, "3");
    long result = db.insert(TABLE_NAME, null, contentValues);

    if (result == -1) {
        return false;
    } else
        return true;
}

public List<String> getAllLabels() {
    List<String> labels = new ArrayList<String>();

    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            labels.add(cursor.getString(1));
            labels.add(cursor.getString(2));
            labels.add(cursor.getString(3));
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();

    return labels;
}
}

You should not do time consuming works like calling db from main application thread. call db asynchronously for example use AsyncTask.

you can get spinner items count like this:

int count = spinner.getAdapter() != null ? spinner.getAdapter().getCount() : 0;

Displaying Error if no item from a spinner is selected, Check if spinner is empty. Get the default selected view. Request Focus for the same view. Set some error message to be displayed. You can  How to do this : Check if spinner is empty. Get the default selected view. Request Focus for the same view. Set some error message to be displayed. You can also perform a click on the spinner so that the spinner list is displayed. (additional option).

I've been checked your code and always is calling db.insertData() because the spinner getCount at beginning always is 0.

So I let you some changes that I made in your MainActivity and also I created a method in Database class to know when I need to populate the db or not.

MainActivity

public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
    private Spinner spinner;
    private Database db;

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

            spinner = findViewById(R.id.spinner);
            db  = new Database(getApplicationContext());

            if(db.shouldPopulate()){
                db.insertData();
            }

            loadData();
        }

    public void loadData(){
        List<String> labels = db.getAllLabels();

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, labels);

        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setOnItemSelectedListener(this);
        spinner.setAdapter(dataAdapter);

    }

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String label = adapterView.getItemAtPosition(i).toString();
            Toast.makeText(adapterView.getContext(),"Selected: "+label,Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
}

Database Here I changed the condition of the result in the insertData method for the result of the insertion.

And I created a method to know when you should insert the data.

public boolean insertData() {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_2, "1");
        contentValues.put(COLUMN_3, "2");
        contentValues.put(COLUMN_4, "3");

        return db.insert(TABLE_NAME, null, contentValues) != -1;
    }

    public boolean shouldPopulate(){
        return  getAllLabels().isEmpty();
    }

I hope this code helps you.

IMPORTANT

You should wrap your db calls in a background handler, this is very important in Android apps for performance and as good practices.

Spinner in android with default selected value as empty/null, will teach you How to set first value (default value) in spinner as empty. View 2 replies Duration: 9:45 Posted: May 10, 2018 Hello, I want to validate a spinner value. But I do not want to select or click on the spinner. My code is like this.

Where are you adding data to your spinner? You just declare it:

spinner = (Spinner) findViewById(R.id.spinner);

You should use Adapter to add data to your Spinner:

// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);

And what spinner.getCount() means? May be it must refers to the adapter?

How to handle spinner.getSelectedText() with custom object in , getItemAtPosition(stationSpinner.getSelectedItemPosition());. But I get nullPointerException because getItemAt Position returns null.. and I don't know why. Testing your fidget spinner yourself is likely the only certain way to actually know whether the specific device you have poses a hazard. The site by Tamara has explained her method for testing several types of spinners and public health specialis

android.widget.Spinner.getSelectedItem java code examples, @Override public void onClick(View v) { Object o = spinner.getSelectedItem(); if (​o != null && o.toString().length() > 0 && !nameToFullName.isEmpty()) { String  This tutorial will give you a hands on experience in using Android Spinner as a drop down menu, passing data using android bundle and showing popup notification using android toast. We will create an android application that consists of a simple spinner that allows selecting an item from a drop down list. We will display static data in the spinner.

Spinner in Kotlin, Android Spinner is a view similar to dropdown list which is used to select one option val spinner = findViewById (R.id.spinner) if (spinner != null) { val adapter​  Thank you for buying the 360° Cordless Spinner VacTM. Please read the instruction manual carefully before using . Product images are for reference only . Models may vary . WARNING: TO REDUCE THE RISK OF ELECTRIC SHOCK OR INJURY DO NOT USE OUTDOORS OR ON WET SURFACES. 1 . DO NOT use or charge the unit outdoors and on wet surfaces . 2 .

Setting selected item of Spinner by value rather than by position , Setting selected item of Spinner by value rather than by position. Home · Community setAdapter(adapter); if (compareValue != null) { int spinnerPosition = adapter. See, both are used to retrieve something READ MORE. Empty data insertion is one of the most big problems in online registration word because sometimes application user just to check our app is working properly or not they trying to send empty data to server but after putting empty condition on EditText app user is compulsory bound to enter some values inside EditText. So here is the complete

Comments
  • Thank you for a tip,but i've never used before AsyncTask,so i will have to learn this. For now,i just want to make everything work,there's no problem if app will be must take a while to "calculate" the instructions. It's just a dummy version of app. In final version,it will be replaced with better code. I've puted your string into Main Activity,but the result is still same - spinner still downloading data from db.
  • @Muszy1 sure when onCreate is called spinner is just created and it is empty just like it is created for first time.
  • @Muszy1 if you want to reuse fetched arrayList , you have to put it in a bundle in onSaveInstanceState and reuse it in onCreate. as you can see onCreate has an argoument of bundle type this bundle may contains saved states but for first run this bundle is null. you should check that bundle not to be null then get back what you have saved in it. you can save to that in onSaveInstanceState which also has a bundle argument.