Khaled Md. Tuhidul Hossain Khaled Md. Tuhidul Hossain - 1 month ago 37
Android Question

Bind Android Spinner with Http reponse data (json) in Xamarin

i am learning xamarin android. I am stuck in something strange.

Normally i wanted to bind my android spinner with my json data which i pulled from my webapi. i wrote this block of code.

var spinner = FindViewById<Spinner>(Resource.Id.RouteSelect);

string url = "http://localhost/api/android/pullroutes";
JsonValue json = await FetchWeatherAsync(url);
string temp = "";
for (int i = 0; i < json.Count; i++) {
//temp += json[i]["name"].ToString();
temp += json[i]["name"].ToString() ;
}


var items = new List<string>() { temp };
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);
spinner.Adapter = adapter;


But it shows me data in spinner as text but not like drop down style.

Android Spinner View

anything i wrote wrong?

Answer
string temp = "";
ArrayList items = new ArrayList();

for (int i = 0; i < json.Count; i++) {
    temp = json[i]["name"].ToString();
    items.Add(temp);
}

var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);
spinner.Adapter = adapter;

You see the difference? You have one LONG string in temp because you are doing +=.

Each String has to be added to the ArrayList as an item. What you have right now is a List with one item and that item contains a long string.

Note: I'm giving the answer based on Java. I understand this is Xamarin/C# but you should be able to do similar.