Home > database >  how to add another column in another spinner of same or other table in android studio
how to add another column in another spinner of same or other table in android studio

Time:08-11

how to add second column value of same or other table in another spinner from sqlite database using button click in android studio

    retrievebtn.setOnClickListener(arg0 -> {

        // TODO Auto-generated method stub
        nos.clear();
        names.clear();

        //OPEN
        db.openDB();

           //RETRIEVE
           Cursor c = db.getAllValues();

        c.moveToFirst();
        while(!c.isAfterLast())
        {
            String no = c.getString(0);
            nos.add(no);
            String name = c.getString(1);
            names.add(name);
            c.moveToNext();
        }

               //CLOSE
               c.close();
               db.close();

               //SET IT TO SPINNER
               sp1.setAdapter(adapter);
               sp2.setAdapter(adapter);


    });

CodePudding user response:

Perhaps consider the following working example.

This consists of 2 spinners and 3 buttons. The buttons controlling from which of the 3 tables the data is extracted for the 2nd spinner.

The trick, as such, used is to use AS to utilise a standard column name, irrespective of the actual column name. The one difference is that this rather than using a normal adapter, it utilises a CursorAdapter (SimpleCursorAdapter as it's quite flexible) and thus you can extract the data directly.

First the SQLite side i.e. the class that extends SQLiteOpenHelper :-

class DBHelper extends SQLiteOpenHelper {
   public static final String DATABASE_NAME = "the_database.db";
   public static final int DATABASE_VERSION = 1;
   public static final String TABLE1_TABLE = "_table1";
   public static final String TABLE1_ID_COL = BaseColumns._ID;
   public static final String TABLE1_NAME_COL = "_name";
   public static final String TABLE1_DESC_COL = "_desc";
   private static final String TABLE1_CREATE_SQL =
           "CREATE TABLE IF NOT EXISTS "   TABLE1_TABLE   "("  
                   TABLE1_ID_COL   " INTEGER PRIMARY KEY"  
                   ","   TABLE1_NAME_COL   " TEXT UNIQUE"  
                   ","   TABLE1_DESC_COL   " TEXT "  
                   ");";

   public static final String TABLE2_TABLE = "_table2";
   public static final String TABLE2_ID_COL = BaseColumns._ID;
   public static final String TABLE2_TABLE1_ID_MAP_COL = "_table1_id_map";
   public static final String TABLE2_NAME_COL = "_name";
   private static final String TABLE2_CREATE_SQL =
           "CREATE TABLE IF NOT EXISTS "   TABLE2_TABLE   "("  
                   TABLE2_ID_COL   " INTEGER PRIMARY KEY"  
                   ","   TABLE2_TABLE1_ID_MAP_COL   " INTEGER "  
                   ","   TABLE2_NAME_COL   " TEXT"  
                   ");";

   public static final String TABLE3_TABLE = "_table3";
   public static final String TABLE3_ID_COL = BaseColumns._ID;
   public static final String TABLE3_TABLE2_ID_MAP_COL = "_table2_id_map";
   public static final String TABLE3_NAME_COL = "_name";
   private static final String TABLE3_CREATE_SQL =
           "CREATE TABLE IF NOT EXISTS "   TABLE3_TABLE  "("  
                   TABLE3_ID_COL   " INTEGER PRIMARY KEY"  
                   ","   TABLE3_TABLE2_ID_MAP_COL   " INTEGER "  
                   ","   TABLE3_NAME_COL   " TEXT "  
                   ");";

   private static volatile DBHelper INSTANCE;
   private SQLiteDatabase db;
   public static final String SPINNER_COLUMN1 = "_spc1";
   public static final String SPINNER_COLUMN2 = "_spc2";

   private DBHelper(Context context) {
      super(context,DATABASE_NAME,null,DATABASE_VERSION);
      db = this.getWritableDatabase();
   }

   public static DBHelper getInstance(Context context) {
      if (INSTANCE==null) {
         INSTANCE = new DBHelper(context);
      }
      return INSTANCE;
   }

   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL(TABLE1_CREATE_SQL);
      db.execSQL(TABLE2_CREATE_SQL);
      db.execSQL(TABLE3_CREATE_SQL);
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int i, int i1) {

   }

   public long insertTable1Row(String name,String description) {
      ContentValues cv = new ContentValues();
      cv.put(TABLE1_NAME_COL,name);
      cv.put(TABLE1_DESC_COL,description);
      return db.insert(TABLE1_TABLE,null,cv);
   }
   public long insertTable2Row(String name, long table1_id) {
      ContentValues cv = new ContentValues();
      cv.put(TABLE2_NAME_COL,name);
      cv.put(TABLE2_TABLE1_ID_MAP_COL,table1_id);
      return db.insert(TABLE2_TABLE,null,cv);
   }

   public long insertTable3Row(String name, long table2_id) {
      ContentValues cv = new ContentValues();
      cv.put(TABLE3_NAME_COL,name);
      cv.put(TABLE3_TABLE2_ID_MAP_COL,table2_id);
      return db.insert(TABLE3_TABLE,null,cv);
   }

   public Cursor getSpinnerData(String table, long map) {

      String[] columns = new String[]{};
      String whereClause = "";
      String[] whereArgs = new String[]{String.valueOf(map)};
      switch (table) {
         case TABLE1_TABLE:
            columns = new String[]{TABLE1_ID_COL,TABLE1_NAME_COL   " AS "   SPINNER_COLUMN1,TABLE1_DESC_COL   " AS "   SPINNER_COLUMN2};
            whereClause = "";
            break;
         case TABLE2_TABLE:
            columns = new String[]{TABLE2_ID_COL ,TABLE2_NAME_COL   " AS "   SPINNER_COLUMN1,"'-' AS "   SPINNER_COLUMN2};
            whereClause = TABLE2_TABLE1_ID_MAP_COL   "=?";
            break;
         case TABLE3_TABLE:
            columns = new String[]{TABLE3_ID_COL, TABLE3_NAME_COL   " AS "   SPINNER_COLUMN1,"'~' AS "   SPINNER_COLUMN2};
            whereClause = TABLE3_TABLE2_ID_MAP_COL   "=?";
            break;
      }
      if (map < 0) {
         whereClause="";
         whereArgs = new String[]{};
      }
      if (columns.length > 0) {
         return db.query(table,columns,whereClause,whereArgs,null,null,null);
      } else {
         return db.query(TABLE1_TABLE,new String[]{"0 AS "   TABLE1_ID_COL   ",'ooops' AS "   SPINNER_COLUMN1,"'ooops' AS "   SPINNER_COLUMN2},null,null,null,null,null,"1");
      }
   }
}
  • as said there are three tables
  • a singleton approach has been utilised for the DBHelper
  • the most relevant aspect in regards to switching spinner data is the getSpinnerData function, which takes two parameters, the most relevant being the first the tablename which drives the resultant query.
  • Note the use of BaseColumns._ID ALL Cursor adapters must have a column name _id (which is what BaseColumns._ID resolves to). The column should be an integer value that uniquely identifies the row.
  • the 2nd parameter caters for the selection of only related data, but a negative is used to ignore this aspect.

The Activity "MainActivity" used to demonstrate is :-

public class MainActivity extends AppCompatActivity {

    Button btn1, btn2, btn3;
    Spinner sp1,sp2;
    String[] spinnerColumns = new String[]{DBHelper.SPINNER_COLUMN1,DBHelper.SPINNER_COLUMN2};
    SimpleCursorAdapter sca1,sca2;
    String sp1_table_name = DBHelper.TABLE1_TABLE;
    String sp2_table_name = DBHelper.TABLE2_TABLE;
    Cursor csr1, csr2;
    DBHelper dbHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = this.findViewById(R.id.button1);
        btn2 = this.findViewById(R.id.button2);
        btn3 = this.findViewById(R.id.button3);
        sp1 = this.findViewById(R.id.spinner1);
        sp2 = this.findViewById(R.id.spinner2);
        dbHelper = DBHelper.getInstance(this);
        Cursor test4Data = dbHelper.getWritableDatabase().query(DBHelper.TABLE1_TABLE,null,null,null,null,null,null, "1");
        if (test4Data.getCount() < 1) {
            addSomeData();
        }
        test4Data.close();
        sp1_table_name = DBHelper.TABLE1_TABLE;
        sp2_table_name = DBHelper.TABLE2_TABLE;
        setUpButtons();
        setOrRefreshSpinner1();
        setOrRefreshSpinner2();
    }

    void setUpButtons() {
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sp2_table_name = DBHelper.TABLE1_TABLE;
                setOrRefreshSpinner2();
                setOrRefreshSpinner1();
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sp2_table_name = DBHelper.TABLE2_TABLE;
                setOrRefreshSpinner2();
                setOrRefreshSpinner1();
            }
        });
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sp2_table_name = DBHelper.TABLE3_TABLE;
                setOrRefreshSpinner2();
                setOrRefreshSpinner1();
            }
        });
    }

    void setOrRefreshSpinner1() {
        csr1 = dbHelper.getSpinnerData(sp1_table_name,-1);
        if (sca1==null) {
            sca1 = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    csr1,
                    spinnerColumns,
                    new int[]{android.R.id.text1, android.R.id.text2},0
            );
            sp1.setAdapter(sca1);
        } else {
            sca1.swapCursor(csr1);
        }
    }
     void setOrRefreshSpinner2() {
        csr2 = dbHelper.getSpinnerData(sp2_table_name,-1);
        if (sca2==null) {
            sca2 = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    csr2,
                    spinnerColumns,
                    new int[]{android.R.id.text1, android.R.id.text2},0
            );
            sp2.setAdapter(sca2);
        } else {
            sca2.swapCursor(csr2);
        }
     }

     private void addSomeData() {
        long n1 = dbHelper.insertTable1Row("NAME001","The first name.");
        long n2 = dbHelper.insertTable1Row("NAME002","The second name.");
        long n3 = dbHelper.insertTable1Row("NAME003","The third name");
        long t2n1 = dbHelper.insertTable2Row("CHILDNAME001",n1);
        long t2n2 = dbHelper.insertTable2Row("CHILDNAME002",n2);
        long t2n3 = dbHelper.insertTable2Row("CHILDNAME003", n3);
        dbHelper.insertTable3Row("GRANDCHILDNAME001",t2n1);
        dbHelper.insertTable3Row("GRANDCHILDNAME002",t2n1);
        dbHelper.insertTable3Row("GRANDCHILDNAME003",t2n1);
        dbHelper.insertTable3Row("GRANDCHILDNAME004",t2n2);
        dbHelper.insertTable3Row("GRANDCHILDNAME005",t2n3);
     }
}

Result The above when run starts of with :- enter image description here

With the first spinner dropdown shown :-

enter image description here

With the second spinner dropdown shown :- enter image description here

If Button1 is clicked then both spinners (i.e. spinner2 has been changed to select data from Table1 rather than Table2) show data from Table1 (useless but for demonstration) :-

enter image description here

If Button3 is clicked then data from Table3 is displayed in the second spinner:-

enter image description here

Clicking Button2 shows data from Table2.

Of course the principle could be applied in many different ways.

CodePudding user response:

my adapters were not set so I made below changes and got expected result.

 //RETERIEVE
    retrievebtn.setOnClickListener(arg0 -> {

        // TODO Auto-generated method stub
        nos.clear();
        names.clear();

        //OPEN
        db.openDB();

           //RETRIEVE
           Cursor c = db.getAllValues();

        c.moveToFirst();
        while(!c.isAfterLast())
        {
            String no = c.getString(0);
            nos.add(no);

            String name = c.getString(1);
            names.add(name);
            c.moveToNext();
        }

               //CLOSE
               c.close();
               db.close();

               //SET IT TO SPINNER
        ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, nos);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);

        sp1.setAdapter(adapter1);
        sp2.setAdapter(adapter2);


    });
  • Related