Populating Spinner data from SQLite Database

In this tutorial I will discus on how to populate android spinner data from SQLite Database. First we need to create the database; after that; create the interface from where we can insert data and also populate the spinner with data.

Creating SQLite Database Helper Class:
DbHelper.java

package com.bar.example.androidspinnerexample;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper{
	 // Database Version
    private static final int DB_VERSION = 1;
  
    // Database Name
    private static final String DB_NAME = "mobile.db";
  
    // Table name
    private static final String TABLE_LABELS = "mobile_names";
  
    // Column names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
	public DbHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// Create table query
        String CREATE_MOBILE_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_MOBILE_TABLE);
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
  
        // Create tables again
        onCreate(db);
		
	}
	
	 /**
     * Insert data to table
     * */
    public void saveName(String label){
        SQLiteDatabase db = this.getWritableDatabase();
         
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, label);
          
        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }
     
    /**
     * Getting all names
     * returns list of mobile name
     * */
    public List<String> getAllNames(){
        List<String> names = new ArrayList<String>();
         
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_LABELS;
      
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
      
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                names.add(cursor.getString(1));
            } while (cursor.moveToNext());
        }
         
        // closing connection
        cursor.close();
        db.close();
         
        // returning names
        return names;
    }

}

XML: Layout File Entry
res/layout/activity_spinner_ex3.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <!-- Label -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8dip"
        android:text="@string/lblAdd" />
     
    <!-- Input Text -->

    <EditText
        android:id="@+id/input_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:hint="@string/txtHint" />
     
    <!-- Add Button -->

    <Button
        android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginTop="8dip"
        android:text="@string/btnAdd" />
     
    <!-- Select Label -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8dip"
        android:text="@string/lblDisp" />
     
    <!-- Spinner Dropdown -->
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
    />
</LinearLayout>

XML: Strings File Entries
res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Spinner Example</string>
    <string name="action_settings">Settings</string>
    <string name="lblAdd">Add New Mobile Name</string>
    <string name="btnAdd">Add Name</string>
    <string name="txtHint">HTC</string>
    <string name="lblDisp">Select Name</string>

</resources>

Main Activity
SpinnerEx3Activity.java

package com.bar.example.androidspinnerexample;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinnerEx3Activity extends Activity implements
		OnItemSelectedListener {

	// Spinner element
	Spinner spinner;

	// Add button
	Button btnAdd;

	// Input text
	EditText inputName;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_spinner_ex3);

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

		// add button
		btnAdd = (Button) findViewById(R.id.btn_add);

		// new name input field
		inputName = (EditText) findViewById(R.id.input_name);

		// Spinner click listener
		spinner.setOnItemSelectedListener(this);

		// Loading spinner data from database
		loadSpinnerData();

		/**
		 * Add new name button click listener
		 * */
		btnAdd.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String label = inputName.getText().toString();

				if (label.trim().length() > 0) {
					// database handler
					DbHelper db = new DbHelper(getApplicationContext());

					// inserting new name into database
					db.saveName(label);

					// making input filed text to blank
					inputName.setText("");

					// Hiding the keyboard
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(inputName.getWindowToken(), 0);

					// loading spinner with newly added data
					loadSpinnerData();
				} else {
					Toast.makeText(getApplicationContext(),
							"Please enter Mobile name", Toast.LENGTH_SHORT)
							.show();
				}

			}
		});
	}

	/**
	 * Function to load the spinner data from SQLite database
	 * */
	private void loadSpinnerData() {
		// database handler
		DbHelper db = new DbHelper(getApplicationContext());

		// Spinner Drop down elements
		List<String> lables = db.getAllNames();

		// Creating adapter for spinner
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, lables);

		// Drop down layout style - list view with radio button
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// attaching data adapter to spinner
		spinner.setAdapter(dataAdapter);
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		// On selecting a spinner item
		String label = parent.getItemAtPosition(position).toString();

		// Showing selected spinner item
		Toast.makeText(parent.getContext(), "You selected: " + label,
				Toast.LENGTH_LONG).show();

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}
}

Emulator Screenshot:
android_spinner_ex3

You can download all android example from here.

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

18,166` Total Views

One comment

  • Hi,

    thanks for the post. I would like to populate a spinner from an existing table (created using sqlite browser)

    pl help me

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 7 = eight