Spinner Data from Database



This is an example of simple label management module is explained where you can insert new label into SQLite database and spinner will fetch with the set labels from database.

Example

This example demostrate about how to integrate Android Spinner Data from Database.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.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" >
   <TextView
      android:layout_width = "fill_parent"
      android:layout_height = "wrap_content"
      android:text = "Add New Label"
      android:padding = "8dip" />
   <EditText android:id = "@+id/input_label"
      android:layout_width = "fill_parent"
      android:layout_height = "wrap_content"
      android:layout_marginLeft = "8dip"
      android:layout_marginRight = "8dip"/>
   <Button android:id = "@+id/btn_add"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "Add Label"
      android:layout_marginLeft = "8dip"
      android:layout_marginTop = "8dip"/>
   <TextView
      android:layout_width = "fill_parent"
      android:layout_height = "wrap_content"
      android:text = "Select Label"
      android:padding = "8dip" />
   <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>

Step 3 − Add the following code to src/MainActivity.java

package myapplication.example.com.myapplication;

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 MainActivity extends Activity implements OnItemSelectedListener { 
   Spinner spinner;
   Button btnAdd;
   EditText inputLabel;
   
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      spinner = (Spinner) findViewById(R.id.spinner);
      btnAdd = (Button) findViewById(R.id.btn_add);
      inputLabel = (EditText) findViewById(R.id.input_label);
      spinner.setOnItemSelectedListener(this);
      loadSpinnerData();
      
      btnAdd.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View arg0) {
            String label = inputLabel.getText().toString();
            
            if (label.trim().length() > 0) {
               DatabaseHandler db = new DatabaseHandler(getApplicationContext());
               db.insertLabel(label);
               inputLabel.setText("");
               InputMethodManager imm = (InputMethodManager) getSystemService(
                  Context.INPUT_METHOD_SERVICE);
                  
               imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
               loadSpinnerData();
            } else {
               Toast.makeText(getApplicationContext(), "Please enter label name",
                  Toast.LENGTH_SHORT).show();
            } 
         } 
      });
   } 
   
   private void loadSpinnerData() {
      DatabaseHandler db = new DatabaseHandler(getApplicationContext());
      List<String> lables = db.getAllLabels();
      ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, 
         android.R.layout.simple_spinner_item, lables);
         
      dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spinner.setAdapter(dataAdapter);
   } 
   
   @Override
   public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
      String label = parent.getItemAtPosition(position).toString();
      Toast.makeText(parent.getContext(), "You selected: " + label, 
         Toast.LENGTH_LONG).show(); 
   } 
   
   @Override
   public void onNothingSelected(AdapterView<?> arg0) {
   }
}

Step 4 − Add the following code to src/DatabaseHandler.java

package myapplication.example.com.myapplication;

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 DatabaseHandler extends SQLiteOpenHelper {
   private static final int DATABASE_VERSION = 1;
   private static final String DATABASE_NAME = "spinnerExample";
   private static final String TABLE_LABELS = "labels";
   private static final String KEY_ID = "id";
   private static final String KEY_NAME = "name";
   
   public DatabaseHandler(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
   } 
   
   @Override
   public void onCreate(SQLiteDatabase db) {
      String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
         + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
         db.execSQL(CREATE_CATEGORIES_TABLE);
   } 
   
   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
      onCreate(db);
   } 
   
   public void insertLabel(String label){
      SQLiteDatabase db = this.getWritableDatabase();
      ContentValues values = new ContentValues();
      values.put(KEY_NAME, label);
      db.insert(TABLE_LABELS, null, values);
      db.close(); // Closing database connection
   } 
   
   public List<String> getAllLabels(){
      List<String> labels = new ArrayList<String>();
      String selectQuery = "SELECT  * FROM " + TABLE_LABELS;
      SQLiteDatabase db = this.getReadableDatabase();
      Cursor cursor = db.rawQuery(selectQuery, null);
      
      if (cursor.moveToFirst()) {
         do {
            labels.add(cursor.getString(1));
         } while (cursor.moveToNext());
      } 
      cursor.close();
      db.close();
      return labels;
   }
}

Step 5 − Add the following code to manifest.xml

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "myapplication.example.com.myapplication">
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Spinner
Advertisements