Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Sqlite Spinner


In this example, we are adding a label on button click and displaying all the added labels on the spinner. As you have seen in the previous example, SQLiteOpenHelper class need to be extended for performing operations on the sqlite.

We have overridden the onCreate() and onUpgrade() method of SQLiteOpenHelper class in the DatabaseHandler class that provides additional methods to insert and display the labels or data.

Android Sqlite Spinner Example

Let’s see the simple code to add and display the string content on spinner using sqlite database.

activity_main.xml

File: activity_main.xml
  1. <RelativeLayout xmlns:androclass=“http://schemas.android.com/apk/res/android”
  2.     xmlns:tools=“http://schemas.android.com/tools”
  3.     android:layout_width=“match_parent”
  4.     android:layout_height=“match_parent”
  5.     tools:context=“.MainActivity” >
  6.      <!– Label –>
  7.     <TextView
  8.         android:layout_width=“fill_parent”
  9.         android:layout_height=“wrap_content”
  10.         android:text=“Add New Label”
  11.         android:padding=“8dip” />
  12.     <!– Input Text –>
  13.     <EditText android:id=“@+id/input_label”
  14.         android:layout_width=“fill_parent”
  15.         android:layout_height=“wrap_content”
  16.         android:layout_marginLeft=“8dip”
  17.         android:layout_marginRight=“8dip”/>
  18.     <Spinner
  19.         android:id=“@+id/spinner”
  20.         android:layout_width=“fill_parent”
  21.         android:layout_height=“wrap_content”
  22.         android:layout_alignParentLeft=“true”
  23.         android:layout_below=“@+id/btn_add”
  24.         android:layout_marginTop=“23dp” />
  25.     <Button
  26.         android:id=“@+id/btn_add”
  27.         android:layout_width=“wrap_content”
  28.         android:layout_height=“wrap_content”
  29.         android:layout_below=“@+id/input_label”
  30.         android:layout_centerHorizontal=“true”
  31.         android:text=“Add Item” />
  32. </RelativeLayout>

Activity class

File: MainActivity.java
  1. package com.example.sqlitespinner;
  2. import android.os.Bundle;
  3. import android.app.Activity;
  4. import android.view.Menu;
  5. import java.util.List;
  6. import android.content.Context;
  7. import android.view.View;
  8. import android.view.inputmethod.InputMethodManager;
  9. import android.widget.AdapterView;
  10. import android.widget.AdapterView.OnItemSelectedListener;
  11. import android.widget.ArrayAdapter;
  12. import android.widget.Button;
  13. import android.widget.EditText;
  14. import android.widget.Spinner;
  15. import android.widget.Toast;
  16. public class MainActivity extends Activity implements OnItemSelectedListener{
  17.     Spinner spinner;
  18.     Button btnAdd;
  19.     EditText inputLabel;
  20.     @Override
  21.     public void onCreate(Bundle savedInstanceState) {
  22.         super.onCreate(savedInstanceState);
  23.         setContentView(R.layout.activity_main);
  24.         spinner = (Spinner) findViewById(R.id.spinner);
  25.         btnAdd = (Button) findViewById(R.id.btn_add);
  26.         inputLabel = (EditText) findViewById(R.id.input_label);
  27.         spinner.setOnItemSelectedListener(this);
  28.         // Loading spinner data from database
  29.         loadSpinnerData();
  30.         btnAdd.setOnClickListener(new View.OnClickListener() {
  31.             @Override
  32.             public void onClick(View arg0) {
  33.                 String label = inputLabel.getText().toString();
  34.                 if (label.trim().length() > 0) {
  35.                     DatabaseHandler db = new DatabaseHandler(getApplicationContext());
  36.                     db.insertLabel(label);
  37.                     // making input filed text to blank
  38.                     inputLabel.setText(“”);
  39.                     // Hiding the keyboard
  40.                     InputMethodManager imm = (InputMethodManager)
  41.                           getSystemService(Context.INPUT_METHOD_SERVICE);
  42.                     imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
  43.                     // loading spinner with newly added data
  44.                     loadSpinnerData();
  45.                 } else {
  46.                     Toast.makeText(getApplicationContext(), “Please enter label name”,
  47.                             Toast.LENGTH_SHORT).show();
  48.                 }
  49.             }
  50.         });
  51.     }
  52.     /**
  53.      * Function to load the spinner data from SQLite database
  54.      * */
  55.     private void loadSpinnerData() {
  56.         DatabaseHandler db = new DatabaseHandler(getApplicationContext());
  57.         List<String> labels = db.getAllLabels();
  58.         // Creating adapter for spinner
  59.         ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, labels);
  60.         // Drop down layout style – list view with radio button
  61.         dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  62.         // attaching data adapter to spinner
  63.         spinner.setAdapter(dataAdapter);
  64.     }
  65.     @Override
  66.     public void onItemSelected(AdapterView<?> parent, View view, int position,
  67.             long id) {
  68.         // On selecting a spinner item
  69.         String label = parent.getItemAtPosition(position).toString();
  70.         // Showing selected spinner item
  71.         Toast.makeText(parent.getContext(), “You selected: “ + label,
  72.                 Toast.LENGTH_LONG).show();
  73.     }
  74.     @Override
  75.     public void onNothingSelected(AdapterView<?> arg0) {
  76.         // TODO Auto-generated method stub
  77.     }
  78.     @Override
  79.     public boolean onCreateOptionsMenu(Menu menu) {
  80.         // Inflate the menu; this adds items to the action bar if it is present.
  81.         getMenuInflater().inflate(R.menu.activity_main, menu);
  82.         return true;
  83.     }
  84. }

DatabaseHandler class

File: DatabaseHandler.java
  1. package com.example.sqlitespinner2;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.content.ContentValues;
  5. import android.content.Context;
  6. import android.database.Cursor;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.database.sqlite.SQLiteOpenHelper;
  9. public class DatabaseHandler extends SQLiteOpenHelper {
  10.     private static final int DATABASE_VERSION = 1;
  11.     private static final String DATABASE_NAME = “spinnerExample”;
  12.     private static final String TABLE_NAME = “labels”;
  13.     private static final String COLUMN_ID = “id”;
  14.     private static final String COLUMN_NAME = “name”;
  15.     public DatabaseHandler(Context context) {
  16.         super(context, DATABASE_NAME, null, DATABASE_VERSION);
  17.     }
  18.     // Creating Tables
  19.     @Override
  20.     public void onCreate(SQLiteDatabase db) {
  21.         // Category table create query
  22.         String CREATE_ITEM_TABLE = “CREATE TABLE “ + TABLE_NAME + “(“
  23.                 + COLUMN_ID + ” INTEGER PRIMARY KEY,” + COLUMN_NAME + ” TEXT)”;
  24.         db.execSQL(CREATE_ITEM_TABLE);
  25.     }
  26.     // Upgrading database
  27.     @Override
  28.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  29.         // Drop older table if existed
  30.         db.execSQL(“DROP TABLE IF EXISTS “ + TABLE_NAME);
  31.         // Create tables again
  32.         onCreate(db);
  33.     }
  34.     /**
  35.      * Inserting new lable into lables table
  36.      * */
  37.     public void insertLabel(String label){
  38.         SQLiteDatabase db = this.getWritableDatabase();
  39.         ContentValues values = new ContentValues();
  40.         values.put(COLUMN_NAME, label);//column name, column value
  41.         // Inserting Row
  42.         db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, CotentValues
  43.         db.close(); // Closing database connection
  44.     }
  45.     /**
  46.      * Getting all labels
  47.      * returns list of labels
  48.      * */
  49.     public List<String> getAllLabels(){
  50.         List<String> list = new ArrayList<String>();
  51.         // Select All Query
  52.         String selectQuery = “SELECT  * FROM “ + TABLE_NAME;
  53.         SQLiteDatabase db = this.getReadableDatabase();
  54.         Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments
  55.         // looping through all rows and adding to list
  56.         if (cursor.moveToFirst()) {
  57.             do {
  58.                 list.add(cursor.getString(1));//adding 2nd column data
  59.             } while (cursor.moveToNext());
  60.         }
  61.         // closing connection
  62.         cursor.close();
  63.         db.close();
  64.         // returning lables
  65.         return list;
  66.     }
  67. }

download this android example

Output:

androidsqlite1

androidsqlite2

androidsqlite3

Comments

comments