2016-12-30 1 views
1

좋은 친구, 내 안드로이드 응용 프로그램입니다. wep api에서 데이터를 가져 와서 목록보기에 표시하려고합니다. 이제 수업을 시작하겠습니다.이 수업은 http 요청을 통해 데이터를 가져옵니다.HTTP 요청으로 데이터 가져 오기 Android Xamarin C#

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; 
    } 

나는 항목 속성을 가진 모델했습니다 :

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

} 

그리고 내 주요 활동은 다음과 같습니다 그래서

[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; 
    } 
} 

내 목록보기 표시이 내 응용 프로그램을 실행하고있을 때 내역 : enter image description here

아무도 도와 줄 수 있고 내가 뭘 잘못하고 있는지 설명 할 수 있습니다.

+1

나는 Xamarin이나 C#으로 작업 한 적이 없지만 스크린 샷과 코드를 보면 ArrayAdapter가 주어진 목록의 객체를 제대로 렌더링 할 수없는 것 같다 : List , 어떤 의미가있다. 예 : 어댑터가 목록에 표시 할 항목을 알 수있는 방법은 무엇입니까?, 항목의 'Id'만? 또는 '콘텐츠'또는 어쩌면 모두 함께? 나는 당신이 필요로하는 것이 맞춤형 어댑터라고 믿는다. –

+0

고맙습니다. 맞춤 어댑터에 대해 자세히 알아 보겠습니다. 맞춤 어댑터가 데이터를 바인딩합니다. 그렇습니까? –

+1

정확히, 사용자 지정 어댑터는 복잡한 데이터를 목록보기에 바인딩하는 데 사용됩니다. –

답변

2

해결책을 찾았습니다. 아마도 새로운 Android 개발자에게 도움이 될 것입니다. 올바른 방법 덕분에 AndyRes에게 감사드립니다. 데이터를 올바르게 표시하려면 사용자 지정 어댑터를 만들어 데이터를 바인딩해야합니다. 먼저 만들어야합니다 Item 클래스, 내가 그것을 전화 했어 모델 :

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; 
    } 
} 

이제 사용자 정의 어댑터 :

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; 

    } 
} 

그리고 마지막으로 활동의 변화합니다

[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", "მესამე მანალითი") 
      }); 

    } 

잊지 마십시오을 각 항목을 표시 할 특별 레이아웃을 만들려면

<?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> 

그리고 주요 레이아웃의 장소 목록. 다시 한번 감사드립니다.

관련 문제