Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Add Items in Spinner By using SQLite DataBase

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 206
    Comment on it

    In the below example code I have created and example, to add item in Spinner By using SQLite Database. here In activity_main.xml layout I have added EditText, Button and Spinner. Now See programming area, here I have Created a DataBaseHelper Class for inserting items into Spinner and to store Items in database. In MainActivity I have created SpinnerData() method to load items in Spinner from SQLite database.
     
    When you can add something in EditText and press Add Button then Item will be inserted into spinner easily .  
    See below example code it clearify you to "Add Items By using SQLite DataBase".

    Step(1)activity_main.xml layout-

    <?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" >
    
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:id="@+id/edit_text"
            android:hint="Add Item.."
            android:maxLength="10"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:id="@+id/btn_add"
            android:textStyle="bold"
            android:text="Add"
            android:background="@color/btn_backgraund"/>
      <Spinner
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:id="@+id/spinner"
         android:layout_margin="10dp">
    
      </Spinner>
    </LinearLayout>

    Step(2)-Created a New DataBaseHelper class-

    public class DataBaseHelper extends SQLiteOpenHelper {
        private static final int DATABASE_VERSION=1;
    
        private static final String DATABASE_NAME="Add_Items";
    
        private static final String TABLE_LABELS="labels";
    
        private  static final String KEY_ID="id";
        private static final String KEY_NAME="name";
    
        public DataBaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
    
        public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, 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();
        }
        public List<String>getAllLabels(){
            List<String>labels= new ArrayList<>();
            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(3)-MainActivity-
     

    public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
        Spinner spinner;
        Button btnAdd;
        EditText edit;
    
        @Override
        protected 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);
            edit=(EditText)findViewById(R.id.edit_text);
            spinner.setOnItemSelectedListener(this);
            SpinnerData();
            btnAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    String label = edit.getText().toString();
                    if(label.trim().length()>0){
                        DataBaseHelper db = new DataBaseHelper(getApplicationContext());
                        db.insertLabel(label);
                        edit.setText("");
                        InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputMethodManager.hideSoftInputFromWindow(edit.getWindowToken(),0);
                        SpinnerData();
                    }else {
                        Toast.makeText(getApplicationContext(),"Please enter Text",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        private void SpinnerData(){
            DataBaseHelper db= new DataBaseHelper(getApplicationContext());
            List<String> labels= db.getAllLabels();
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, labels);
            spinner.setAdapter(dataAdapter);
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        @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<?> parent) {
    
        }
    }
    
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: