Blog purpose for android basic example for android app developer. any query please my contact

Sunday, 6 December 2020

sqlite database into spinner in android

sqlite database into spinner in android

in this Article today learn how to get data from sqlite database into spinner in android.

follow the full source code how to get data from sqlite database into spinner in android:


1.MainActivity.java:

import android.content.Context;  

import android.support.v7.app.AppCompatActivity;  

import android.os.Bundle;  

import android.view.View;  

import android.view.inputmethod.InputMethodManager;  

import android.widget.AdapterView;  

import android.widget.ArrayAdapter;  

import android.widget.Button;  

import android.widget.EditText;  

import android.widget.Spinner;  

import android.widget.Toast;  

import java.util.List;  

  

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {  

    Spinner spinner;  

    Button btnAdd;  

    EditText inputLabel;  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_main);  

        spinner = findViewById(R.id.spinner);  

        btnAdd =  findViewById(R.id.btn_add);  

        inputLabel = findViewById(R.id.input_label);  

  

        spinner.setOnItemSelectedListener(this);  

  

        // Loading spinner data from database  

        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);  

  

                    // making input filed text to blank  

                    inputLabel.setText("");  

  

                    // Hiding the keyboard  

                    InputMethodManager imm = (InputMethodManager)  

                            getSystemService(Context.INPUT_METHOD_SERVICE);  

                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);  

                    // loading spinner with newly added data  

                    loadSpinnerData();  

                } else {  

                    Toast.makeText(getApplicationContext(), "Please enter label name",  

                            Toast.LENGTH_SHORT).show();  

                }  

  

            }  

        });  

    }  

  

    /** 

     * Function to load the spinner data from SQLite database 

     * */  

    private void loadSpinnerData() {  

        DatabaseHandler db = new DatabaseHandler(getApplicationContext());  

        List<String> labels = db.getAllLabels();  

  

        // Creating adapter for spinner  

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, labels);  

  

        // 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  

  

    }  

}  



2.activity_main.xml:

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    xmlns:app="http://schemas.android.com/apk/res-auto"  

    xmlns:tools="http://schemas.android.com/tools"  

    android:layout_width="match_parent"  

    android:layout_height="match_parent"  

    tools:context=".MainActivity">  

  

  

    <EditText  

        android:id="@+id/input_label"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_alignParentTop="true"  

        android:layout_centerHorizontal="true"  

        android:layout_marginTop="46dp"  

        android:hint="Add item"  

        android:ems="10" />  

  

    <Button  

        android:id="@+id/btn_add"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_below="@+id/input_label"  

        android:layout_centerHorizontal="true"  

        android:layout_marginTop="67dp"  

        android:text="Add item" />  

  

    <Spinner  

        android:id="@+id/spinner"  

        android:layout_width="match_parent"  

        android:layout_height="wrap_content"  

        android:layout_alignParentLeft="true"  

        android:layout_alignParentStart="true"  

        android:layout_below="@+id/btn_add"  

        android:layout_marginTop="70dp" />  

</RelativeLayout>  


3.DatabaseHandler.java:

import android.content.ContentValues;  

import android.content.Context;  

import android.database.Cursor;  

import android.database.sqlite.SQLiteDatabase;  

import android.database.sqlite.SQLiteOpenHelper;  

import java.util.ArrayList;  

import java.util.List;  

  

public class DatabaseHandler extends SQLiteOpenHelper {  

    private static final int DATABASE_VERSION = 1;  

    private static final String DATABASE_NAME = "spinnerExample";  

    private static final String TABLE_NAME = "labels";  

    private static final String COLUMN_ID = "id";  

    private static final String COLUMN_NAME = "name";  

  

    public DatabaseHandler(Context context) {  

        super(context, DATABASE_NAME, null, DATABASE_VERSION);  

    }  

  

    // Creating Tables  

    @Override  

    public void onCreate(SQLiteDatabase db) {  

        // Category table create query  

        String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("  

                + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT)";  

        db.execSQL(CREATE_ITEM_TABLE);  

    }  

  

    // Upgrading database  

    @Override  

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  

        // Drop older table if existed  

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);  

  

        // Create tables again  

        onCreate(db);  

    }  

  

    /** 

     * Inserting new lable into lables table 

     * */  

    public void insertLabel(String label){  

        SQLiteDatabase db = this.getWritableDatabase();  

  

        ContentValues values = new ContentValues();  

        values.put(COLUMN_NAME, label);//column name, column value  

  

        // Inserting Row  

        db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, CotentValues  

        db.close(); // Closing database connection  

    }  

  

    /** 

     * Getting all labels 

     * returns list of labels 

     * */  

    public List<String> getAllLabels(){  

        List<String> list = new ArrayList<String>();  

  

        // Select All Query  

        String selectQuery = "SELECT  * FROM " + TABLE_NAME;  

  

        SQLiteDatabase db = this.getReadableDatabase();  

        Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments  

  

        // looping through all rows and adding to list  

        if (cursor.moveToFirst()) {  

            do {  

                list.add(cursor.getString(1));//adding 2nd column data  

            } while (cursor.moveToNext());  

        }  

        // closing connection  

        cursor.close();  

        db.close();  

        // returning lables  

        return list;  

    }  

}  


4.AndroidManifest.xml:

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.sqlitespinner"

    android:versionCode="1"

    android:versionName="1.0" >


    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="16" />


    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name=".MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>


</manifest>


5.strings.xml:

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

<resources>


    <string name="app_name">Sqlite Spinner</string>

    <string name="hello_world">Hello world!</string>

    <string name="menu_settings">Settings</string>


</resources>



6.styles.xml:

<resources>


    <!--

        Base application theme, dependent on API level. This theme is replaced

        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

    -->

    <style name="AppBaseTheme" parent="android:Theme.Light">

        <!--

            Theme customizations available in newer API levels can go in

            res/values-vXX/styles.xml, while customizations related to

            backward-compatibility can go here.

        -->

    </style>


    <!-- Application theme. -->

    <style name="AppTheme" parent="AppBaseTheme">

        <!-- All customizations that are NOT specific to a particular API-level can go here. -->

    </style>


</resources>


No comments:

Post a Comment