0

I have got one table with two column (id,name). Toast should show the "name" details from sqlite while choosing the id from spinner.

Ex: Sqlite table 1,899,Chris and 2,890,David.

Whenever i select value 899 from spinner then Toast should display Chris and if i select spinner 890 then Toast should display David. Suggestion needed.

Code: SpinnerEx4Activity.Java

package com.bar.example.androidspinnerexample;



import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;

import android.widget.Button;
import android.widget.CheckBox;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleCursorAdapter;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.content.Intent;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnClickListener;
import android.util.Log;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.EditText;
import java.util.LinkedList;
import android.view.inputmethod.InputMethodManager;
public class SpinnerEx4Activity extends Activity implements
    AdapterView.OnItemSelectedListener {
Spinner s1,s2;
Button btnAdd;
EditText inputLabel;
DatabaseHandler dbhndlr;        //<<<<< Single instance for Database handler
Cursor spinner1csr;
Cursor spinner2csr;   //<<<<< Cursor for spinner (close in onDestroy)



 @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_ex4);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        s1.setOnItemSelectedListener(this);
        dbhndlr = new DatabaseHandler(this);    //<<<< Instantiate Databasehandler
        //loadSpinnerData();                            //<<<< commented out


        altLoadSpinnerData();
        altLoadSpinnerData1();//<<<< Load via cursor
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.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();                    //<<<< commeneted out
                    altLoadSpinnerData();
                    altLoadSpinnerData1();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });


    }
    // New method to utilise Cursor adapter
    private void altLoadSpinnerData() {
        spinner1csr = dbhndlr.getAllLabelsAsCursor();
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, // Layout to show 2 items
                spinner1csr, // Cursor
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},// Views into which data is shown
                0
        );
              s1.setAdapter(sca);
    }
    private void altLoadSpinnerData1 () {
        // get the cursor
        spinner2csr = dbhndlr.getAllLabelsAsCursor();
        // Instantiaie Simple Cursor Adapter
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2, // Layout to show 2 items
                spinner2csr, // Cursor
                new String[]{DatabaseHandler.KEY_ID}, // Source data
                new int[]{android.R.id.text2}, // Views into which data is shown
                0
        );
        s2.setAdapter(sca);
        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " " +
                                spinner2csr.getString(
                                        spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                        Toast.LENGTH_SHORT

                ).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
}}

And Databasehandler.java

package com.bar.example.androidspinnerexample;

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 {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    private static final String TABLE_LABELS = "labels";

    // Labels Table Columns names
    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);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_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_LABELS);

        // 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(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }

    /**
     * Getting all labels
     * returns list of labels
     * */
    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return labels;
    }
}

And activity_spinner_ex4.xml is

<?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" >

    <!-- Label -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8dip"
        android:text="@string/lblAcc" />

    <!-- Spinner Dropdown -->

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:layout_marginTop="10dip"
         />

    <!-- Select Label -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8dip"
        android:text="@string/lblSubAcc" />

    <!-- Spinner Dropdown -->
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="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"/>

    <!-- Add Button -->
    <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"/>
</LinearLayout>

Inserting the spinner and checkbox value into another table. i am able to insert all data. but all checkbox text is saving instead of selected one.could you assist.

main activity.

 btnAdd.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                        //String label = inputLabel.getText().toString();
                    String SaveString="No";

                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    String message1= ((Cursor) s1.getSelectedItem()).getString(2);
                    String message2= ((Cursor) s2.getSelectedItem()).getString(1);
                    String message = inputLabel.getText().toString();
                   // String message1 = s1.getSelectedItem().toString();
                   // String message2 = s2.getSelectedItem().toString();
                    String message10 = s3.getSelectedItem().toString();
                    String message4 = ck1.getText().toString();
                    String message5 = ck2.getText().toString();
                    String message6 = ck3.getText().toString();
                    String message7 = ck4.getText().toString();
                    String message9 = ck6.getText().toString();
                    String message3 = ck7.getText().toString();
                    String message8 = ck8.getText().toString();
                    db.insertLabel(message1,message2,message5,message6,message7,message9,message3,message4,message8,message10);

                    if (ck1.isChecked())
                    { SaveString="Yes";
                    }
                    else
                    {  SaveString="No";
                    }

                    if (ck2.isChecked())
                    { SaveString="Yes";
                    }
                    else
                    {  SaveString="No";
                    }

                    if (message.trim().length() > 0) {
                        // database handler commeneted out, use dbhndlr instance instead
                        // inserting new label into database


                        // 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
                        spinner1csr = dbhndlr.getAllLabelsAsCursor();
                        spinner2csr = dbhndlr.getByRowid(spinner1_selected);
                        sca.swapCursor(spinner1csr);
                        sca2.swapCursor(spinner2csr);
                    } else {
                        Toast.makeText(getApplicationContext(), "Please enter label name",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

Database .

     public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();

            values.put(KEY_1, message1);
            values.put(KEY_2, message2);
            values.put(KEY_10,message10);
            values.put(KEY_3,message3);
            values.put(KEY_4,message4);
            values.put(KEY_5,message5);
            values.put(KEY_6,message6);
            values.put(KEY_7,message7);
            values.put(KEY_9,message9);

            values.put(KEY_8,message8);


            // Inserting Row
            db.insert(TABLE_LABELS2, null, values);
            db.close(); // Closing database connection
        }
Mecido
  • 29
  • 1
  • 10

3 Answers3

1

Alternative/Improved SpinnerEx4Activity.Java

public class SpinnerEx4Activity extends Activity {
    Spinner s1,s2;
    Button btnAdd;
    EditText inputLabel;
    DatabaseHandler dbhndlr;
    Cursor spinner1csr, spinner2csr;
    SimpleCursorAdapter sca, sca2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
        dbhndlr = new DatabaseHandler(this);

        // If no data in database then load data for testing purposes only
        if (DatabaseUtils.queryNumEntries(
                dbhndlr.getWritableDatabase(),
                DatabaseHandler.TABLE_LABELS) < 1)
        {
            dbhndlr.insertlabel("899","Chris");
            dbhndlr.insertlabel("890","David");
        }

        // Get Cursors for Spinners
        spinner1csr = dbhndlr.getAllLabelsAsCursor();
        spinner2csr = dbhndlr.getAllLabelsAsCursor();

        //Setup Adapter for Spinner 1
        sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,spinner1csr,
                new String[]{DatabaseHandler.KEY_ID},
                new int[]{android.R.id.text1},
                0
        );
        //Steup Adapter for Spinner2
        sca2 = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,
                spinner2csr,
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},
                0
        );
        // Set the Adapters to the Spinners
        s1.setAdapter(sca);
        s2.setAdapter(sca2);
        // Set Spinner1 OnSelectedItemListener
        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner1csr.getString(
                                        spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        // Set Spinner2 OnSelectedItemListener
        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " " +
                                spinner2csr.getString(
                                        spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.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();                    //<<<< commeneted out
                    spinner1csr = dbhndlr.getAllLabelsAsCursor();
                    spinner2csr = dbhndlr.getAllLabelsAsCursor();
                    sca.swapCursor(spinner1csr);
                    sca2.swapCursor(spinner2csr);
                    //altLoadSpinnerData();
                    //altLoadSpinner2Data();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Notes

  • No longer implements AdapterView.OnItemSelectedListener
  • No longer creates new Instance of adapters reuses the existing ones
  • Due to above uses adapter.swapCursor(new_cursor) to keep spinners in sync with data entered.
  • 1st Spinner will display blank lines, 2nd will result in Toast showing id followed bu null.
    • Both of the above are because when entering a new label, no ID (not rowid) is assigned. Due to adding only using 'dbhndlr.insertLabel(label);' thus the KEY_ID column is null. I have no idea how you assign ID's to Labels(names). However, notice how I created an alternative insertlabel method that takes ID and NAME/LABEL parameters.

Amended as per comment

here i am talking now about select spinner s1 value(ex:123) then spinner s2 should different value(Mike Trae) as per table.

i.e. spinners should exclude the selected value in the other spinner (spinners are inter-dependant)

  • Note! I changed to display names in both spinners as id's can be null and confusing (see previous notes)

SpinnerEx4Activity

public class SpinnerEx4Activity extends Activity {
    Spinner s1,s2;
    Button btnAdd;
    EditText inputLabel;
    DatabaseHandler dbhndlr;
    Cursor spinner1csr, spinner2csr;
    SimpleCursorAdapter sca, sca2;
    long spinner1_selected = 0, spinner2_selected = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
        dbhndlr = new DatabaseHandler(this);

        // If no data in database then load data for testing purposes only
        if (DatabaseUtils.queryNumEntries(
                dbhndlr.getWritableDatabase(),
                DatabaseHandler.TABLE_LABELS) < 1)
        {
            dbhndlr.insertlabel("899","Chris");
            dbhndlr.insertlabel("890","David");
        }

        // Get Cursors for Spinners
        spinner1csr = dbhndlr.getAllLabelsExceptedSelected(spinner2_selected);
        //Setup Adapter for Spinner 1
        sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,spinner1csr,
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},
                0
        );

        // Set the Adapters to the Spinners
        s1.setAdapter(sca);
        // Set Spinner1 OnSelectedItemListener
        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner1csr.getString(
                                        spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
                                " - " + spinner1csr.getString(spinner1csr.getColumnIndex(DatabaseHandler.KEY_ID))
                        ,
                        Toast.LENGTH_SHORT).show();
                spinner1_selected = id;
                spinner2csr = dbhndlr.getAllLabelsExceptedSelected(spinner1_selected);
                sca2.swapCursor(spinner2csr);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //Steup Adapter for Spinner2
        spinner2csr = dbhndlr.getAllLabelsExceptedSelected(spinner1_selected);
        sca2 = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,
                spinner2csr,
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},
                0
        );
        s2.setAdapter(sca2);
        // Set Spinner2 OnSelectedItemListener
        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner2csr.getString(
                                        spinner2csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
                                " - " + spinner2csr.getString(spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                        Toast.LENGTH_SHORT).show();
                spinner2_selected = id;
                spinner1csr = dbhndlr.getAllLabelsExceptedSelected(spinner2_selected);
                sca.swapCursor(spinner1csr);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.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();                    //<<<< commeneted out
                    spinner1csr = dbhndlr.getAllLabelsExceptedSelected(spinner2_selected);
                    spinner2csr = dbhndlr.getAllLabelsExceptedSelected(spinner1_selected);
                    sca.swapCursor(spinner1csr);
                    sca2.swapCursor(spinner2csr);
                    //altLoadSpinnerData();
                    //altLoadSpinner2Data();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        spinner1csr.close();
        spinner2csr.close();
        super.onDestroy();
    }
}

DatabaseHandler

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    public static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    public static final String TABLE_LABELS = "labels"; //<<<< Made public

    // Labels Table Columns names
    public static final String KEY_ID = "id";           //<<<< Made public
    public static final String KEY_NAME = "name";       //<<<< made public

    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_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_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_LABELS);

        // 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(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }

    // Added for adding new data
    public void insertlabel(String id, String label) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(KEY_ID,id);
        cv.put(KEY_NAME,label);
        db.insert(TABLE_LABELS,null,cv);
        db.close();
    }

    // Added to get Cursor for Simple CursorAdapter
    public Cursor getAllLabelsAsCursor() {
        String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
        return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
    }

    public Cursor getAllLabelsExceptedSelected(long selected) {
        String[] columns = new String[]{"rowid AS _id, *"};
        String whereclause = "rowid <> ?";
        String[] whereargs = new String[]{String.valueOf(selected)};
        return this.getWritableDatabase().query(TABLE_LABELS,
                columns,
                whereclause,
                whereargs,
                null,
                null,
                null
        );
    }
}

Amendments after comments :-

But i want it one-way only Spinner1 selection first column(Database) should show in spinner 2(Second Column)database.

No need from spinner 2 to spinner.

1.Also note that my table having 1000 datas*(rows)*.

ex: Database: { dbhndlr.insertlabel("9001234","Chris") dbhndlr.insertlabel("9001235","Cdedd"); dbhndlr.insertlabel("9003457","Dcdtt"); dbhndlr.insertlabel("9001231","Chrdis"); dbhndlr.insertlabel("9003451","Ddavid");}

ex: If spinner 1 select 9001231 then spinner 2 should show Chrdis and if spinner 1 selected 9001234 then spinner2 should show Chris.

1) Added new method getByRowid to Databasehandler.java :-

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    public static final int DATABASE_VERSION = 1;

    // Database Name
    public static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    public static final String TABLE_LABELS = "labels"; //<<<< Made public

    // Labels Table Columns names
    public static final String KEY_ID = "id";           //<<<< Made public
    public static final String KEY_NAME = "name";       //<<<< made public

    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_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_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_LABELS);

        // 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(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }

    // Added for adding new data
    public void insertlabel(String id, String label) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(KEY_ID,id);
        cv.put(KEY_NAME,label);
        db.insert(TABLE_LABELS,null,cv);
        db.close();
    }

    // Added to get Cursor for Simple CursorAdapter
    public Cursor getAllLabelsAsCursor() {
        String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
        return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
    }

    public Cursor getAllLabelsExceptedSelected(long selected) {
        String[] columns = new String[]{"rowid AS _id, *"};
        String whereclause = "rowid <> ?";
        String[] whereargs = new String[]{String.valueOf(selected)};
        return this.getWritableDatabase().query(TABLE_LABELS,
                columns,
                whereclause,
                whereargs,
                null,
                null,
                null
        );
    }

    public Cursor getByRowid(long id) {
        String[] columns = new String[]{"rowid AS _id, *"};
        return this.getWritableDatabase().query(
                TABLE_LABELS,
                columns,
                "rowid=?",
                new String[]{String.valueOf(id)},
                null,null,null
        );
    }
}

The Amended SpinnerEx4Acitivity.java :-

public class MainActivity extends Activity {
    Spinner s1,s2;
    Button btnAdd;
    EditText inputLabel;
    DatabaseHandler dbhndlr;
    Cursor spinner1csr, spinner2csr;
    SimpleCursorAdapter sca, sca2;
    long spinner1_selected = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
        dbhndlr = new DatabaseHandler(this);

        // If no data in database then load data for testing purposes only
        if (DatabaseUtils.queryNumEntries(
                dbhndlr.getWritableDatabase(),
                DatabaseHandler.TABLE_LABELS) < 1)
        {
            dbhndlr.insertlabel("899","Chris");
            dbhndlr.insertlabel("890","David");
        }

        // Get Cursors for Spinners
        spinner1csr = dbhndlr.getAllLabelsAsCursor();
        //Setup Adapter for Spinner 1
        sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,spinner1csr,
                new String[]{DatabaseHandler.KEY_ID},
                new int[]{android.R.id.text1},
                0
        );

        // Set the Adapters to the Spinners
        s1.setAdapter(sca);
        // Set Spinner1 OnSelectedItemListener
        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner1csr.getString(
                                        spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
                                " - " + spinner1csr.getString(spinner1csr.getColumnIndex(DatabaseHandler.KEY_ID))
                        ,
                        Toast.LENGTH_SHORT).show();
                spinner1_selected = id;
                spinner2csr = dbhndlr.getByRowid(spinner1_selected);
                sca2.swapCursor(spinner2csr);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //Steup Adapter for Spinner2
        spinner2csr = dbhndlr.getByRowid(spinner1_selected);
        sca2 = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,
                spinner2csr,
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},
                0
        );
        s2.setAdapter(sca2);
        // Set Spinner2 OnSelectedItemListener
        /* Not needed
        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner2csr.getString(
                                        spinner2csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
                                " - " + spinner2csr.getString(spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                        Toast.LENGTH_SHORT).show();
                spinner2_selected = id;
                spinner1csr = dbhndlr.getAllLabelsExceptedSelected(spinner2_selected);
                sca.swapCursor(spinner1csr);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        */
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.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
                    spinner1csr = dbhndlr.getAllLabelsAsCursor();
                    spinner2csr = dbhndlr.getByRowid(spinner1_selected);
                    sca.swapCursor(spinner1csr);
                    sca2.swapCursor(spinner2csr);
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        spinner1csr.close();
        spinner2csr.close();
        super.onDestroy();
    }
}
MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Hello Mike tried with that. but i do not see any changes its remains . same. – Mecido Jan 18 '18 at 14:40
  • @Mecido The difference is that the 2nd spinner doesn't show the name that is selected by the 1st spinner and the 1st does not show the name that is selected by the 2nd spinner, so you can't select the same name. If that isn't what you want then I have no idea what you want. PS the Amended as per comment code (you did use just this) has been changed to now properly refresh cursors after adding a new name/label. (uses variables `spinner1_selected` and `spinner2_selected`, I also re-ordered some of the code and also added onDestroy to close the cursors) – MikeT Jan 18 '18 at 19:54
  • Mike thank you . But i want it one-way only Spinner1 selection first column(Database) should show in spinner 2(Second Column)database.No need from spinner 2 to spinner 1.Also note that my table having 1000 datas. ex: Database: { dbhndlr.insertlabel("9001234","Chris") dbhndlr.insertlabel("9001235","Cdedd"); dbhndlr.insertlabel("9003457","Dcdtt"); dbhndlr.insertlabel("9001231","Chrdis"); dbhndlr.insertlabel("9003451","Ddavid");} ex: If spinner 1 select 9001231 then spinner 2 should show Chrdis. and if spinner 1 select 9001234 then spinner2 should show Chris. – Mecido Jan 19 '18 at 06:09
  • By Date do you mean KEY_ID? What's the use of the 2nd Spinner if it's only going to show 1 thing? Might as well just have a textView or just have Spinner 1 show both KEY_NAME and KEY_ID. Of course it can easily be done. ooops thought you said date but u said datas. However confirm KEY_ID. – MikeT Jan 19 '18 at 06:15
  • OK think that's what you've described. Code is from ***Amendments after comments*** i.e. the last two pieces of code. – MikeT Jan 19 '18 at 06:46
  • MikeT wonderful. I am done with your amended code. I would say that this code is first time available in Stackoverflow .Thank you MikeT & Stackoverflow Team....Also this code is nowhere available apart from Stackoverflow – Mecido Jan 19 '18 at 08:23
  • Just one question would there be multiple names per ID, if so the code is wrong as it's just selecting the one name. – MikeT Jan 19 '18 at 08:31
  • Mike thanks . I might need like this . Revised table.col1,col2,col3,col4. and data is ex: Database: { dbhndlr.insertlabel("9001234","Chris","Gold","North") dbhndlr.insertlabel("9001235","Mark","Silver","West"). So in this case while choosing spinner sp1 ex:9001234. should show result in sp2 Chris, and sp3 Gold,sp4 North. And sp2,sp3,sp4 can be spinner nor textview. – Mecido Jan 19 '18 at 08:50
  • That's just a matter of repeating the code used for sp2 making the appropriate changes. e.g. using s3, spinner3csr, sca3 etc and changing the column used to the respective column. You should be able to do that. I'd suggest doing one at a time. – MikeT Jan 19 '18 at 09:04
  • Hello Mike.What is the best to way to store the all selected spinner value,checkbox value,edit text value in to another table...Could you advise, – Mecido Jan 19 '18 at 18:52
  • Typically you'd store strings into a column of type TEXT, checkbox as an INTEGER (0 false 1 true) numbers if integers (int/long) with a type of INTEGER, decimal (float/double) as a type of REAL. However SQLite's flexibility allows you to store any value in any column type although you might have to do some manipulation. I'd suggest looking into Database [design](https://www.ntu.edu.sg/home/ehchua/programming/sql/Relational_Database_Design.html) and [normalisation](https://en.wikipedia.org/wiki/Database_normalization). – MikeT Jan 19 '18 at 20:00
  • hello mike i have done so and able to insert the spinner and checkbox value in to the sql table. but issue is all the checkbox text is getting saved instead of selected checkbox. do you have any guess to insert only selected. ex if selected = 1 and if not selected = 0. and revised code pasted above – Mecido Jan 20 '18 at 14:13
  • `String message 4 = "0"; if(ck1.isChecked) { message4 = "1" };` etc. Well done managing on you own. You should really ask new questions. It's considered bad to keep adding to a question, as SO is about providing for the community rather individuals; questions and answers should be useful for all. String message 4 = "0"; if(ck1.isChecked) { message4 = "1" }; etc – MikeT Jan 20 '18 at 21:20
  • Hello mike can you help me with spinner value change based on textview change ... – Mecido Mar 25 '18 at 14:17
0

You should include one method to get just one Label.

public String getLabelsById(int id){ 
 String result = null;

    // Select Query
    String selectQuery = "SELECT  * FROM " + TABLE_LABELS + " WHERE " + "id" +" = ?";

    SQLiteDatabase db = this.getReadableDatabase();
    cursor = db.rawQuery(selectQuery, new String[] {String.valueOf(id)});

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {

            result = (cursor.getString(0));
    }

    // closing connection
    cursor.close();
    db.close();

    // returning lables
    return labels;
}

You should create a class to store a user, with two atributes: name and number. And then you should modify this function with something like:

 User user = new User();

And then, insted of return a string:

 user.setName(cursor.getString(1));
 user.setNumber(cursor.getString(2));
pcampana
  • 2,413
  • 2
  • 21
  • 39
  • Hi thank you. But i unable to display the name details while choosing number from spinner. In other way what is the best way to display in textview for edittext(Should show the name against the spinner value).. – Mecido Jan 17 '18 at 19:18
0

There are a few ways in which this could be achieved.

The easiest to implement would be to add another method (e.g. getNameById) to Databasehandler.java that will return the name from the labels table and to then call this within the Spinner's overridden onItemSelected method. public String getNameById(String id) { String rv = "No Name Found"; SQLiteDatabase db = this.getReadableDatabase(); Cursor csr = db.query(TABLE_LABELS, null, KEY_ID + "=?", new String[]{id}, null,null,null,null );

    if (csr.moveToFirst()) {
        rv = csr.getString(csr.getColumnIndex(KEY_NAME));
    }
    csr.close();
    db.close();
    return rv;
}
  • This assumes that id will be unqiue
  • Using getColumnIndex(column_name) is more flexible and less likely to result in errors than using hard coded column offsets.

The Overridden onItemSelected method in SpinnerEx4Activity.Java could then be :-

@Override
public void onItemSelected(AdapterView<?> parent, View view, int arg2, long id) {
    // On selecting a spinner item
    DatabaseHandler db = new DatabaseHandler(parent.getContext());
    String label = parent.getItemAtPosition(arg2).toString();

    // Showing selected spinner item
    Toast.makeText(parent.getContext(), "You selected: " + id + " " + db.getNameById(label),Toast.LENGTH_LONG).show();
}

Alternative Approach - using a Cursor Adapter

An alternative approach would be to use a CursorAdapter (SimpleCursorAdapter), which would then allow direct access to all columns.

1) This would require a method in DatabaseHandler.java that returns a cursor. Noting that a column named _id must exist. As the table is not defined with the WITHOUT ROWID keywords then a column named rowid exists (not normally visible). So we can use rowid AS _id to get this. The following could be added to DatabaseHandler.java (note other changes made so see complete DatabaseHandler.java below.)

// Added to get Cursor for Simple CursorAdapter
public Cursor getAllLabelsAsCursor() {
    String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
    return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
}

2) A call, in the Spinner's Activity, to the the new method getAllLabelsAsCursor to retrieve the cursor. (see below)

3) A replacement for the loadSpinner method that utilises a SimpleCursorAdapter.

In addition to the above a few changes have also been made (see comments with //<<<<).

The full working code is :-

Databasehandler.java

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    public static final String TABLE_LABELS = "labels"; //<<<< Made public

    // Labels Table Columns names
    public static final String KEY_ID = "id";           //<<<< Made public
    public static final String KEY_NAME = "name";       //<<<< made public

    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_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_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_LABELS);

        // 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(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }

    //<<<< Added for adding new data for testing
    public void insertlabel(String id, String label) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(KEY_ID,id);
        cv.put(KEY_NAME,label);
        db.insert(TABLE_LABELS,null,cv);
        db.close();
    }

    /**
     * Getting all labels
     * returns list of labels
     * */
    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return labels;
    }

    // Added to get Cursor for Simple CursorAdapter
    public Cursor getAllLabelsAsCursor() {
        String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
        return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
    }
}

SpinnerEx4Activity.Java

public class SpinnerEx4Activity extends Activity implements
        AdapterView.OnItemSelectedListener {
    Spinner s1,s2;
    Button btnAdd;
    EditText inputLabel;
    DatabaseHandler dbhndlr;        //<<<<< Single instance for Database handler
    Cursor spinner1csr;             //<<<<< Cursor for spinner (close in onDestroy)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
        s1.setOnItemSelectedListener(this);
        dbhndlr = new DatabaseHandler(this);    //<<<< Instantiate Databasehandler
        //loadSpinnerData();                            //<<<< commented out

        // If no data in database then load data
        if (DatabaseUtils.queryNumEntries(dbhndlr.getWritableDatabase(),DatabaseHandler.TABLE_LABELS) < 1) {
            dbhndlr.insertlabel("899","Chris");
            dbhndlr.insertlabel("890","David");
        }
        altLoadSpinnerData();                           //<<<< Load via cursor
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.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();                    //<<<< commeneted out
                    altLoadSpinnerData();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });


    }
    // New method to utilise Cursor adapter
    private void altLoadSpinnerData() {
        // get the cursor
        spinner1csr = dbhndlr.getAllLabelsAsCursor();
        // Instantiaie Simple Cursor Adapter
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2, // Layout to show 2 items
                spinner1csr, // Cursor
                new String[]{DatabaseHandler.KEY_ID,DatabaseHandler.KEY_NAME}, // Source data
                new int[]{android.R.id.text1,android.R.id.text2}, // Views into which data is shown
                0
        );
        //
        //sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(sca);
}


    private void loadSpinnerData() {
        // Spinner Drop down elements
        List<String> lables = dbhndlr.getAllLabels();

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, lables);

        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        s1.setAdapter(dataAdapter);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // Note id will be the same as position for ArrayAdapter but for CursorAdapter
        // will be the _id column (in this case rowid)
        // On selecting a spinner item
        //String label = parent.getItemAtPosition(arg2).toString(); //<<<< no need

        // Showing selected spinner item
        Toast.makeText(parent.getContext(),
                "You selected: " + id +
                        " " +
                        spinner1csr.getString(
                                spinner1csr.getColumnIndex(
                                        DatabaseHandler.KEY_NAME)
                        ) ,
                Toast.LENGTH_LONG).show();

    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }
}

Notes

  • The above includes a check for no data and loads the two rows mentioned above.
  • Making the table and column names public allows them to be accessed (much better to use column names rather than offsets for cursor get???? methods).
  • Code has been changed to utilise a single instance of the DatabaseHandler, replacing the creation of multiple instances of DatabaseHandler db = new DatabaseHandler(getApplicationContext());
  • The Cursor should be closed, override the onDestroy method. However, you don't need to close the Database itself although doing so has been left in.
  • The Spinner shows two items in both the selected view and the drop down view (commented out the setDropdownViewresource, you may wish to experiment, perhaps provide your own layout(s)).

Example Screen Shot(s) :-

enter image description here

enter image description here

  • Note labels (LabelAcc and LabelSubACc) are as such due to me overriding the String resources with text, rather than guess the values of the String resources.

Edit re comment

Spinner1 only working.spinner 2 no reaction.

1) Add new method (could be in the one method but probably best to keep them separate. If in the one method then 3 isn't required) :-

// New method to utilise Cursor adapter for 2nd Spinner
private void altLoadSpinner2Data() {
    // get the cursor
    spinner2csr = dbhndlr.getAllLabelsAsCursor();
    // Instantiaie Simple Cursor Adapter
    SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_1, // Layout to show 2 items
            spinner2csr, // Cursor
            new String[]{DatabaseHandler.KEY_NAME}, // Source data
            new int[]{android.R.id.text1}, // Views into which data is shown
            0
    );
    //
    //sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s2.setAdapter(sca);
    s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(parent.getContext(),
                    "You Selected: " + id + " " +
                    spinner2csr.getString(
                            spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                    Toast.LENGTH_SHORT

            ).show();
        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
}
  • Note uses 2nd Cursor so each can have their own position
  • Includes it's own slightly different (show's ID seelected) OnSelectedItemListener

2) Change Cursor declaration to be for 2 cursor so it is :-

    Cursor spinner1csr, spinner2csr;             //<<<<< Cursor for spinner (close in onDestroy)

3) Add call to load 2nd spinner, after/before 1st as per :-

    altLoadSpinner2Data();
MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Hello Mike you saved my day. I reached almost as per your magic codes. But what is the best way to show separately instead of showing both in same spinner.Ex Select "spinner1"(id) and display in another "spinner2"(name) nor Textview – Mecido Jan 18 '18 at 06:23
  • @Mecido in Spinner1 just use `android.R.layout.simple_list_item_1` not 2. Remove 2nd column i.e. `new String[]{DatabaseHandler.KEY_ID}`and remove 2nd view text2 i.e `new int[]{android.R.id.text1}`. For 2nd Spinner use same BUT change column to name (could use the same cursor for both). I'm assuming you're using CursorAdapter. – MikeT Jan 18 '18 at 06:35
  • Spinner1 only working.spinner 2 no reaction. private void altLoadSpinnerData1() { spinner2csr = dbhndlr.getAllLabelsAsCursor(); SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, spinner2csr, // Cursor new String[]{DatabaseHandler.KEY_NAME}, new int[]{android.R.id.text2}, 0 ); s2.setAdapter(sca); } – Mecido Jan 18 '18 at 06:58
  • private void altLoadSpinnerData() { spinner1csr = dbhndlr.getAllLabelsAsCursor(); SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, // Layout to show 2 items spinner1csr, // Cursor new String[]{DatabaseHandler.KEY_ID}, new int[]{android.R.id.text1},// Views into which data is shown 0 ); s1.setAdapter(sca); } – Mecido Jan 18 '18 at 07:02
  • @Mecido see Edit to Asnwer – MikeT Jan 18 '18 at 08:28
  • Hello MikeT thank you for your support. Is it possible to share the full revised code since i am facing challenges. – Mecido Jan 18 '18 at 09:09
  • @Mecido Just about to add 2nd answer, doing away with some issues (such as creating new instances of adapters). Should be 5 minutes. – MikeT Jan 18 '18 at 09:30
  • Thanks for your time and support. I do edited my first posting with amendments as per your suggestion. Could you review and confirm. If this is correct. Also note that i am getting error in following line items ,public class SpinnerEx4Activity extends Activity implements AdapterView.OnItemSelectedListener { – Mecido Jan 18 '18 at 11:31
  • You should've copied the code should be `public class SpinnerEx4Activity extends Activity` i.e. no `implements AdapterView.OnItemSelectedListener` (also said this in notes). Done away with that and added specific listeners. – MikeT Jan 18 '18 at 11:40
  • Hi, After changing to public class SpinnerEx4Activity extends Activity { .i force to remove the line s1.setOnItemSelectedListener(this); .. once removal . upon running app is same . there is no changes in spinner 2 while choosing spinner. Are you talking about toast or multiple spinner. here i am talking now about select spinner s1 value(ex:123) then spinner s2 should different value(Mike Trae) as per table. – Mecido Jan 18 '18 at 11:53
  • Spinner's aren't magic you will have to extract a cursor that excludes the other spinner's selection. So select something in spinner 1 then that should run a query to build spinner 2's cursor then swap the cursor for spinner 2's adapter. When spinner 2 is selected then this should do the same for spinner 1's cursor, heeding the note/link re firing onItemSelected. Basically it's not the easiest thing to do. However it is doable. This link may be of use [how to make spinner depends on another spinner](https://stackoverflow.com/questions/29474829/how-to-make-spinner-depends-on-another-spinner) – MikeT Jan 18 '18 at 12:13
  • Hello MikeT thanks your information and reference. But the link which given is exactly what i want but the challenge between mine and that link is database vs string. Since my source code is depends on sql whereas most of the link i am google it from string to string.. let me know if easiest way from spinner to spinner or spinner to text view either way/// – Mecido Jan 18 '18 at 12:41
  • @Mecido OK updated. p.s I'm off to bed now. Oh just realised I haven't tested adding new Names. Just tested not 100% but very close might need 2 variables to hold latest names to exclude. – MikeT Jan 18 '18 at 12:51
  • Hello Mike thanks your effort. take your time .meanwhile i am googling and testing on the same. Also please do post with your updated magic revised code while you finish.... – Mecido Jan 18 '18 at 12:59
  • Hello Mike, what is the best way to show spinner selection value in to the textview field instead of spinner to spinner? – Mecido Mar 19 '18 at 06:26
  • Hi i am also looking for the same.. Would like to populate textview or edittext details against the spinner selection.. – Leace Mar 19 '18 at 08:21
  • @Mecido assuming the TextView is **`spinner1_selection`** then in the **`onItemSelected`** method simply add `spinner1_selection.setText( spinner1csr.getString( spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME) ) );` of course assuming that you want the name. – MikeT Mar 19 '18 at 10:04
  • Hello mike thank you its works. But what is they way for reverse search i mean. Spinner data change against the textview or edittext value ? – Mecido Mar 19 '18 at 11:16
  • You'd use a `addTextChangedListener` (only to EditText). and then use the same methodology as used in the answer to adjust the Spinner accordingly. – MikeT Mar 19 '18 at 11:43
  • Mike thanks. I am trying with this s6.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before,int count) { } what are the changes needed ? can you advise with piece of code for the same . – Mecido Mar 19 '18 at 16:11
  • Hello mike i am trying but unable to reach to the desire output. Could you share the code as per your advise.. – Mecido Mar 20 '18 at 13:23
  • Tried in different way but no luck ..edit.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { try { int nPosition = Integer.parseInt(s.toString()); if (nPosition >= 1 && nPosition <= 12) spinner.setSelection(nPosition - 1); } catch(NumberFormatException nfe) { } } }); – Mecido Mar 21 '18 at 05:36
  • Even i do have same situation. Created new question for this requirement. Changing Spinner value based on textview.. – Leace Mar 21 '18 at 13:27
  • @MikeT need your support. – Mecido Apr 04 '18 at 14:26