Dynamically creating a spinner and setting its Value from SQLite

柔情痞子 提交于 2019-12-19 10:14:21

问题


Found my problem check under "Update" for the code

Okay, I have a problem loading the right value from Sqlite into my Spinner. Here is how my app is constructed

my onCreate() sets up a spinner called spinTypes by:

public class MyClass extends Activity{
 // local members . . . 
     .
     .
     .
 //spinner 
 private Spinner spinTypes, spinNames = null;

 // string array decl.
 private String [] types, names1, names2, names3 = null;

 // array adapters for string arrays
 private ArrayAdapter<String> typesAdapter, names1Adapter,
                             names2Adapter, names3Adapter;

 // create a Dbhelper object to access the db
 private DbHelper mdbHelper = null;

// on create
 @Override
 public void onCreate(Bundle savedIstanceState){
  // call to super class
  // set my content view
  // instantiate all members 

  // Dbhelper object to access the db
  mdbHelper = new DbHelper(getBaseContext());

  // spinners
  spinTypes = (Spinner) findViewById(R.id.spin_types);
  spinNames = (Spinner) findViewById(R.id.spin_names);

 // get string arrays from resources and create a ArrayAdapter<string>
 types = getResources().getStringArray(R.array.types);

 typesAdapter = new ArrayAdapter<String>(getBaseContext(),
                                        android.R.layout.simple_spinner_item, types);
 typesAdapter. setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

 // want to create a dynamic spinner based on these arrays
 names1 = getResources().getStringArray(R.array.names_1); 
 names2 = getResources().getStringArray(R.array.names_2);
 names3 = getResources().getStringArray(R.array.names_3);

 // do this for all names++ arrays
 names1Adapter = new ArrayAdapter<String>(getBaseContext(),
                                        android.R.layout.simple_spinner_item, names1);
 names1Adapter. setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

 // etc . . . for the other two

 // set the adapter for the types spinner
 spinTypes.setAdapter(typesAdapter);

}

I have a creation method for inserting all my data into the db that works fine, my problem is when i want to try and populate the spinners for editing an entry.

The app works as so: you press an add button to popup a dialog that creates a list item in the calling view. I use two spinners to create it, one for the type which dynamically populates the second names spinner based on the type.

when i access the database object i return the strings from the spinner but for some reason when i create my if statement checking the position of the string in the array the second spinner sets position 0 every time.

the method including the if statement i mentioned above is as so:

public void populate(){
  mdbHelper.open();
  // if there is an item create a cursor rowId != null
  Cursor mTypes = mdbHelper.fetchItem(rowId);
   if(mTypes.moveToFirst()){
   String tType = mTypes.getString(mTypes.getColumnIndexOrThrow(DbAdapter.KEY_TYPE));
   String tName = mTypes.getString(mTypes.getColumnIndexOrThrow(DbAdapter.KEY_NAME));

  int t = spinTypes.getPosition(tType);
  spinTypes.setSelection(t);

  // ** this does not seem to do the job i want it to**
  if(t == 0){
    spinNames.setAdapter(names1Adapter); // set the adapter based on t value
    int n1 = names1Adapter.getPosition(tName); // use name return from db to get pos
    spinNames.setSelection(n1);            // set the position
  }else if(t ==1){
    spinNames.setAdapter(names2Adapter);
    int n2 = names1Adapter.getPosition(tName);
    spinNames.setSelection(n2);
  }else{
    spinNames.setAdapter(names3Adapter);
    int n3 = names3Adapter.getPosition(tName);
    spinNames.setSelection(n3);
  }

}// end populate

} // end class

The spinners all work but they do not end up on the value with tName i am returning.

Can anyone help with this?

** I am logging the name returned from the db and using it to find the index of the item in my error and i return the correct value, yet the spinner still defaults to 0**

Anyone know what my error may be? please

Update(final code posted below) I made quite a bit of changes to get this to work, in order to understand what i did you should read this whole post so you don't miss anything!

added a variable before onCreate() private int spinNamePos;

added this line after my last line of the onCreate()

// add a listener to the spinner
spinTypes.setOnItemSelectedListener(TypesListener);

and created this listener as so

OnItemSelectedListener TypesListener = new OnItemSelectedListener(){
  public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
    // use the position of this spinner to set the second spinner
     switch(pos){
     case 0 :
        spinNames.setAdapter(names1Adapter);
        break;
      //etc. .  for the other two
     case 1:
        // etc
       break;
     }
     case 2:
        // etc
       break;
     }
     // created an int for the position of the second spinner before calling onCreate()
     // and use it to set this spinners position
     spinNames.setSelection(spinNamePos); 
 // this value is grabbed in onSavedInstanceState() and used to set the pos when onRestoreInstanceState() is called to handle orientation changes and activity paused
  }
 };

i then changed my onPopulate() to work as so calling a new method to set the second spinner's position

 public void populate(){
  mdbHelper.open();
  // if there is an item create a cursor rowId != null
  Cursor mTypes = mdbHelper.fetchItem(rowId);
   if(mTypes.moveToFirst()){
   String tType = mTypes.getString(mTypes.getColumnIndexOrThrow(DbAdapter.KEY_TYPE));
   String tName = mTypes.getString(mTypes.getColumnIndexOrThrow(DbAdapter.KEY_NAME));

  int t = spinTypes.getPosition(tType);
  spinTypes.setSelection(t);

  // call to the new method
  spinNamePos = setSpinNamesPos( t, tName);
  // set the position
  spinNames.setSelection(spinNamePos)


}// end populate

// new method to set the position when i want to update/change the list item

private int setSpinNamesPos(int m, String name){
 int pos = 0;
 switch(m){
  case 0:
    pos = names1Adapter.getPosition(name);
    break;
  case 1:
    pos = names2Adapter.getPosition(name);
    break;
   case 2:
    pos = names3Adapter.getPosition(name);
    break;
  }
 return pos;
}

So happy to see this working any questions or comments are encouraged


回答1:


Okay so I have seemed to figure out my own answer, weeks later! The problem I was having is that i was unaware that my OnItemSelectedListener() gets called every time my adapter is set for my first spinner.

So now realizing this, i set the first spinner in OnItemSelectedListener() then use this spinner id to set my second spinner adapter.(i.e based on the id I set the adapter of my second spinner to 1 of 3 choices.)

After this adapter is set I use the value returned from my cursor to find the string in this adapter and set the spinner to the position of the string in my array.

It all works great now and I will be putting the final code above under the UPDATE title. Thanks for all help.



来源:https://stackoverflow.com/questions/12962268/dynamically-creating-a-spinner-and-setting-its-value-from-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!