In my original version I populated my spinner from an Array, placed in strings.xml
And to know which selection the user made, he used the following code
code 1
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// get selected option
String[] names = getResources().getStringArray(R.array.confirmation_memo);
selectedName = names[position];
}
But now I get the array from a URL and for that I had to implement the AsyncTask method to get the OnLine data from the company's website.
with the following code:
code 2
public class JSONOAsyncTask extends AsyncTask<String, Void, Boolean> implements AdapterView.OnItemSelectedListener{
private Spinner spinner;
private ArrayAdapter<String> dataAdapter;
@Override
protected void onPreExecute() {
super.onPreExecute();
spinner = (Spinner) findViewById( R.id.memo_confirmation_spinner );
spinner.setOnItemSelectedListener(PostConfirmationActivity.this);
}
@Override
protected Boolean doInBackground(String... urls) {
try {
Log.e("****** MESSAGE ******", " Json Object = " + JSONParser.getJSONFromUrl( URL ).get("ReportDetailTextList"));
List < String > categories = new ArrayList < String > ();
JSONArray array = (JSONArray) JSONParser.getJSONFromUrl(URL).get("ReportDetailTextList");
for (int i = 0; i < array.length(); i++) {
categories.add(array.get(i).toString());
// puting the first option from the URL, to be the "default memo field".
if(i == 0) {
selectedName = array.get(i).toString();
}
}
dataAdapter = new ArrayAdapter < String > (getBaseContext(), android.R.layout.simple_spinner_dropdown_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
// putting adapter in to data
spinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
And everything works fine , unless I can not get "code 1" to use the URL array of AsyncTask) ... and so make the choice in the spinner,
That is:
Inside AsyncTask, I create ARRAY on the line:
JSONArray array = (JSONArray) SONParser.getJSONFromUrl(URL).get("ReportDetailTextList");
And I would like to use this OUTPUT AsyncTask array in code
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// get selected option
String[] names = getResources().getStringArray(R.array.confirmation_memo);
selectedName = names[position];
}
Or is there a better way to pick up the spinner's choice? following the idea of using AsyncTask?