AdSense

AdSense3

Monday, 5 October 2015

Android Sqlite Spinner Example

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.   
  7.      <!-- Label -->  
  8.     <TextView  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="Add New Label"  
  12.         android:padding="8dip" />  
  13.   
  14.     <!-- Input Text -->  
  15.     <EditText android:id="@+id/input_label"  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:layout_marginLeft="8dip"  
  19.         android:layout_marginRight="8dip"/>  
  20.   
  21.     <Spinner  
  22.         android:id="@+id/spinner"  
  23.         android:layout_width="fill_parent"  
  24.         android:layout_height="wrap_content"  
  25.         android:layout_alignParentLeft="true"  
  26.         android:layout_below="@+id/btn_add"  
  27.         android:layout_marginTop="23dp" />  
  28.   
  29.     <Button  
  30.         android:id="@+id/btn_add"  
  31.         android:layout_width="wrap_content"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_below="@+id/input_label"  
  34.         android:layout_centerHorizontal="true"  
  35.         android:text="Add Item" />  
  36.      
  37. </RelativeLayout>  

Activity class

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

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

Output:

android sqlite example output 1 android sqlite example output 2 android sqlite example output 3

1 comment:

  1. Croma campus is best it training insitute in noida and best class Android Training in Noida with job placement support croma campus best company job placement support. amd more it course like (SAP, SAS, JAVA, ANDROID APPS, DOT NET, INFORMATICA, PLC SCADA, EMBEDDED SYSTEMS) and more it course visit at croma campus

    ReplyDelete