// Get the JSON object from db that was saved, 10 spinner values already selected by user
JSONObject json = new JSONObject(string);
JSONArray jsonArray = json.getJSONArray("answer");
// get the current class that Spinner is called in
Class<? extends MyActivity> cls = this.getClass();
// loop through all 10 spinners and set the values with reflection
for (int j=1; j< 11; j++) {
JSONObject obj = jsonArray.getJSONObject(j-1);
String movieid = obj.getString("id");
// spinners variable names are s1,s2,s3...
Field field = cls.getDeclaredField("s"+ j);
// find the actual position of value in the list
int datapos = indexedExactSearch(Arrays.asList(Arrays.asList(this.data).toArray()), "value", movieid) ;
// find the position in the array adapter
int pos = this.adapter.getPosition(this.data[datapos]);
// the position in the array adapter
((Spinner)field.get(this)).setSelection(pos);
}
这里是索引搜索,你可以使用几乎任何列表,只要字段是在对象的顶层。
/**
* Searches for exact match of the specified class field (key) value within the specified list.
* This uses a sequential search through each object in the list until a match is found or end
* of the list reached. It may be necessary to convert a list of specific objects into generics,
* ie: LinkedList<Device> needs to be passed as a List<Object> or Object[ ] by using
* Arrays.asList(device.toArray( )).
*
* @param list - list of objects to search through
* @param key - the class field containing the value
* @param value - the value to search for
* @return index of the list object with an exact match (-1 if not found)
*/
public static <T> int indexedExactSearch(List<Object> list, String key, String value) {
int low = 0;
int high = list.size()-1;
int index = low;
String val = "";
while (index <= high) {
try {
//Field[] c = list.get(index).getClass().getDeclaredFields();
val = cast(list.get(index).getClass().getDeclaredField(key).get(list.get(index)) , "NONE");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (val.equalsIgnoreCase(value))
return index; // key found
index = index + 1;
}
return -(low + 1); // key not found return -1
}
可以为所有原语创建的强制转换方法是string和int。
/**
* Base String cast, return the value or default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type String
*/
public static String cast(Object object, String defaultValue) {
return (object!=null) ? object.toString() : defaultValue;
}
/**
* Base integer cast, return the value or default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type integer
*/
public static int cast(Object object, int defaultValue) {
return castImpl(object, defaultValue).intValue();
}
/**
* Base cast, return either the value or the default
* @param object - generic Object
* @param defaultValue - default value to give if Object is null
* @return - returns type Object
*/
public static Object castImpl(Object object, Object defaultValue) {
return object!=null ? object : defaultValue;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
cursor.moveToFirst();
int row_count = 0;
int spinner_row = 0;
while (spinner_row < 0 || row_count < cursor.getCount()){ // loop until end of cursor or the
// ID is found
int cursorItemID = bCursor.getInt(cursor.getColumnIndexOrThrow(someTable.COLUMN_ID));
if (knownID==cursorItemID){
spinner_row = row_count; //set the spinner row value to the same value as the cursor row
}
cursor.moveToNext();
row_count++;
}
}
spinner.setSelection(spinner_row ); //set the selected item in the spinner
}
mySpinner.setSelection(getIndex(mySpinner, myValue));
//private method of your class
private int getIndex(Spinner spinner, String myString){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
return i;
}
}
return 0;
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int spinnerPosition;
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.ccy_array,
android.R.layout.simple_spinner_dropdown_item);
adapter1.setDropDownViewResource(android.R.layout.simple_list_item_activated_1);
// Apply the adapter to the spinner
spinner1.setAdapter(adapter1);
// changes to remember last spinner position
spinnerPosition = 0;
String strpos1 = prfs.getString("SPINNER1_VALUE", "");
if (strpos1 != null || !strpos1.equals(null) || !strpos1.equals("")) {
strpos1 = prfs.getString("SPINNER1_VALUE", "");
spinnerPosition = adapter1.getPosition(strpos1);
spinner1.setSelection(spinnerPosition);
spinnerPosition = 0;
}
And put below code where you know latest spinner values are present, or somewhere else as required.
This piece of code basically writes the spinner value in SharedPreferences.
private int getIndex(Spinner spinner, String columnName, String searchString) {
//Log.d(LOG_TAG, "getIndex(" + searchString + ")");
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
Cursor cursor = (Cursor)spinner.getItemAtPosition(0);
int initialCursorPos = cursor.getPosition(); // Remember for later
int index = -1; // Not found
for (int i = 0; i < spinner.getCount(); i++) {
cursor.moveToPosition(i);
String itemText = cursor.getString(cursor.getColumnIndex(columnName));
if (itemText.equals(searchString)) {
index = i; // Found!
break;
}
}
cursor.moveToPosition(initialCursorPos); // Leave cursor as we found it.
return index;
}
}
private int getIndex(Spinner spinner, String searchString) {
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equals(searchString)) {
return i; // Found!
}
}
return -1; // Not found
}
};
private int getIndexByString(Spinner spinner, String string) {
int index = 0;
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(string)) {
index = i;
break;
}
}
return index;
}
private int getArrayPositionForValue(final int arrayResId, final String value) {
final Resources english = Utils.getLocalizedResources(this, new Locale("en"));
final List<String> arrayValues = Arrays.asList(english.getStringArray(arrayResId));
for (int position = 0; position < arrayValues.size(); position++) {
if (arrayValues.get(position).equalsIgnoreCase(value)) {
return position;
}
}
Log.w(TAG, "getArrayPosition() --> return 0 (fallback); No index found for value = " + value);
return 0;
}
ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinnerCountry.getAdapter();
int position = adapter.getPosition(obj.getCountry());
spinnerCountry.setSelection(position);