2016-04-04 6 views
1

私はXamarin Androidの初心者です。私は、サーバーからデータを取得するためにRESTサービスを使用するアプリケーションを構築しようとしています。 私は、リサイクラビューを使用してデータの内容をリストするフラグメント内のWebサービスを呼び出そうとしています。問題は、リサイクラー・アダプター・クラスが呼び出された後にクライアント関数の呼び出しが行われ、データが取り込まれないということです。フラグメント内でRESTサービスを呼び出し、リサイクルビュー内のデータを取り込む

public override void OnCreate(Bundle savedInstanceState) 
      { 
       base.OnCreate(savedInstanceState); 

       notifications = new List<Notification_Struct>(); 
       mClient = new WebClient(); 

       Url = new Uri("http://10.71.34.1:63026/api/notifications/PetePentreath"); 

       mClient.DownloadDataAsync(Url); 

       mClient.DownloadDataCompleted+= MClient_DownloadDataCompleted; 

       // Create your fragment here 
      } 

      public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
      { 
       // Use this to return your custom view for this Fragment 
       // return inflater.Inflate(Resource.Layout.YourFragment, container, false); 

       View view = inflater.Inflate(Resource.Layout.recyclerviewcontainer, container, false); 

       notifitem = view.FindViewById<RecyclerView>(Resource.Id.rv); 
       notifitem.HasFixedSize = true; 



       layoutmanager = new LinearLayoutManager(Activity); 
       adapter = new NotificationAdapter(notifications); 

       notifitem.SetLayoutManager(layoutmanager); 
       notifitem.SetAdapter(adapter); 

       return view; 
      } 

      void MClient_DownloadDataCompleted (object sender, DownloadDataCompletedEventArgs e) 
      { 
       string json = Encoding.UTF8.GetString(e.Result); 

       notifications = JsonConvert.DeserializeObject<List<Notification_Struct>>(json); 
      } 
     } 

OnCreateViewの内側にそれを呼び出すとDownloadDataCompletedイベントを起動していないので、私はOnCreateの内部Webサービスを呼び出しています:

は、ここに私のフラグメント・クラスのコードです。 通知クラスにリサイクラー・ビュー・アダプターに渡すデータがあるように、アダプター・クラスが呼び出される前にこのイベントを発生させます。これをどのように達成するのですか?

何か助けていただければ幸いです。

ありがとうございます!要するに

+0

あなたのアダプターを取り付ける前に完了することが要求を待つ必要があります。初めて空のアダプタを設定する可能性があります。そして、あなたの 'MClient_DownloadDataCompleted'であなたは再びアダプタを設定することができます。 それ以外の場合は、代わりに 'async/await'プラクティスを調べます。 –

+0

@Jon Douglas自分のコードで非同期待機を実装するにはどうすればよいですか? –

+0

https://visualstudiomagazine.com/articles/2013/10/01/asynchronous-operations-with-xamarin.aspxかなり上手なチュートリアルです。 –

答えて

2

は:

あなたは完了するために、あなたの要求を待ついずれかの必要があるか、要求が完了した後、アダプタをリセットする必要があります。私はasync/awaitに読んで推薦:https://github.com/xamarin/mobile-samples/tree/master/AsyncAwait

すなわち

 void MClient_DownloadDataCompleted (object sender, DownloadDataCompletedEventArgs e) 
     { 
      string json = Encoding.UTF8.GetString(e.Result); 

      notifications = JsonConvert.DeserializeObject<List<Notification_Struct>>(json); 

      //Get a reference to your RecyclerView 
      //Set the adapter with your notifications 
      recyclerView = (RecyclerView) FindViewById(R.id.myRecyclerView); //Or keep a reference from before 
      adapter = new NotificationAdapter(notifications); 
      recyclerView.setAdapter(adapter); 
     } 
関連する問題