Get Data with HTTP request Android Xamarin C#

1.8k views Asked by At

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: enter image description here

But my data is: enter image description here

Can anybody help me and explain what I'm doing wrong.

1

There are 1 answers

0
Archil Labadze On BEST ANSWER

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:

public class Item
{
    public string Id { get; set; }
    public string Content { get; set; }

    public Item(string Id, string Content)
    {
        this.Id = Id;
        this.Content = Content;
    }
}

Now Custom Adapter:

class ItemListAdapter : BaseAdapter<Item>
{
    Activity context;
    public List<Item> listItems { get; set; }
    public ItemListAdapter(Activity context, List<Item> Items) : base()
    {
        this.context = context;
        this.listItems = Items;
    }
    public override Item this[int position]
    {
        get
        {
            return this.listItems[position];
        }
    }

    public override int Count
    {
        get
        {
            return this.listItems.Count;
        }
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        Item item = listItems[position];
        View view = convertView;
        if (convertView == null || !(convertView is LinearLayout))

            view = context.LayoutInflater.Inflate(Resource.Layout.Itemlayout, parent, false);
        TextView itemId = view.FindViewById(Resource.Id.textItemId) as TextView;
        TextView itemContent = view.FindViewById(Resource.Id.textItemContent) as TextView;

        itemId.SetText(item.Id, TextView.BufferType.Normal);
        itemContent.SetText(item.Content, TextView.BufferType.Normal);

        return view;

    }
}

And finally make changes in Activity:

[Activity(Label = "CustomAdapterAndroidApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    private ListView listItems;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        listItems = FindViewById<ListView>(Resource.Id.listViewItems);
        PopulateItemsList();
    }

    private void PopulateItemsList()
    {
        listItems.Adapter = new ItemListAdapter(
           this, new List<Item>
            {
                new Item("222", "First Sample"),
                new Item("111", "Второй пример"),
                new Item("333", "მესამე მანალითი")
            }); 

    }

Do not forget to create special layout to display each item:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
<TextView
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textItemId" />
<TextView   
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textItemContent" />
</LinearLayout>

And sure place list in main layout. Thanks again.