Good day friends, this is my first Android Application, I'm trying get data from wep api and display in a list view. Now I'll tell my steps first I made class and this class gets data via http request.
class WebRequests
{
public static List<Item> GetAllItems()
{
List<Item> lp = new List<Item>();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = client.GetAsync("https://MyUrlToApi/api/myitems").Result;
if (response.IsSuccessStatusCode)
{
lp = JsonConvert.DeserializeObject<Item[]>(response.Content.ReadAsStringAsync().Result).ToList();
}
}
catch
{
}
return lp;
}
I've made a model with item properties:
public class Item
{
public string Id { get; set; }
public string Content { get; set; }
}
And my main Activity is:
[Activity(Label = "GetDataFromWebApiAndroid", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
ListView listView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
var result = WebRequests.GetAllItems();
listView = FindViewById<ListView>(Resource.Id.listAll);
listView.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, result);
listView.ChoiceMode = ChoiceMode.None;
}
}
So when I'm running my application my list view displays this:
Can anybody help me and explain what I'm doing wrong.
I found solution, maybe this will help new Android developers. Special thanks to AndyRes for right way. So to display data correctly I should create custom adapter to bind data. First must be created Item class, I'm calling it model:
Now Custom Adapter:
And finally make changes in Activity:
Do not forget to create special layout to display each item:
And sure place list in main layout. Thanks again.