刷新

时间:2016-03-23 19:35:26

标签: c# listview xamarin xamarin.android

我有一个不同的textview布局(我们称之为WeekReservations),它代表了本月的日子。每天都有预订的列表视图。列表视图是每天不同的。此外,每个选定日期,您都可以预订。

首次登陆WeekReservations

enter image description here 在您选择一天之前,首次登陆此页面不会显示任何内容。

选择一天后

enter image description here

默认情况下,如果我登陆此页面,则没有选定日期。这意味着在我选择一天之前我无法看到列表视图。当我进行预订并提交时,我将被定向回到WeekReservations页面(为了重定向它们,我已经刷新了这个页面)。

要进行刷新,我使用了以下代码行:

var intent = new Intent (this, typeof(WeekViewActivity));
            intent.SetFlags (ActivityFlags.ClearTop);
            StartActivity (intent);

所有数据都将正确更新。直到这里一切正常。

但问题是,当我被引导回WeekReservations页面时,我将不会看到我预订的预订列表中的那一天。我需要再次选择一天(我预订的那天)来查看我最近的预订。

我已经尝试记住所选日期并将其传递给活动并将其传递回WeekReservations活动。但这给了我一个错误。因为如果它第一次登陆这个页面就没有任何东西要传递给这个WeekReservations活动。

我的问题是:

有没有办法记住用户选择哪一天(进行预订)并在刷新后用预订列表显示此选定日期?

如果我仍然不清楚我在询问或缺少详细信息,请随时指出。我会尽力解释自己

更新

以下是我的代码,直到现在我是如何做到的:

WeekViewActivity.cs

选择日期并显示列表视图和进行预订的代码

namespace iChargeClassTest
{
    [Activity (Label = "WeekViewActivity", Theme =     "@android:style/Theme.NoTitleBar")]          
    public class WeekViewActivity : Activity
{
    List<WeekReservationClass> result;
    string myCPID;
    string myCPAddress;

    TextView showDay1, showDay2, showDay3, showDay4, showDay5, showDay6, showDay7, selectedDay;
    Button makeBooking;

    int totalDays;
    DateTime chosenDateCP;
    List<WeekReservationClass> newList = new List<WeekReservationClass> ();

    private List<ReservationTime> myItems;
    private ListView mListView;

    protected async override void OnCreate (Bundle savedInstanceState)
    {
        base.OnCreate (savedInstanceState);
        SetContentView (Resource.Layout.WeekViewLayout);

        TextView showCurrentMonth = FindViewById<TextView> (Resource.Id.txtCurrentMonth);
        showCurrentMonth.Text = DateTime.Now.ToMonthName ();

        showDay1 = FindViewById<TextView> (Resource.Id.txtToday);
        showDay2 = FindViewById<TextView> (Resource.Id.txtDay2);
        showDay3 = FindViewById<TextView> (Resource.Id.txtDay3);
        showDay4 = FindViewById<TextView> (Resource.Id.txtDay4);
        showDay5 = FindViewById<TextView> (Resource.Id.txtDay5);
        showDay6 = FindViewById<TextView> (Resource.Id.txtDay6);
        showDay7 = FindViewById<TextView> (Resource.Id.txtDay7);

        makeBooking = FindViewById<Button> (Resource.Id.btnBooking);

        selectedDay = FindViewById<TextView> (Resource.Id.txtSelectedDay);

        showDay1.Text = DateTime.Today.Day.ToString ();
        showDay2.Text = DateTime.Today.AddDays (1).Day.ToString ();
        showDay3.Text = DateTime.Today.AddDays (2).Day.ToString ();
        showDay4.Text = DateTime.Today.AddDays (3).Day.ToString ();
        showDay5.Text = DateTime.Today.AddDays (4).Day.ToString ();
        showDay6.Text = DateTime.Today.AddDays (5).Day.ToString ();
        showDay7.Text = DateTime.Today.AddDays (6).Day.ToString ();

        mListView = FindViewById<ListView> (Resource.Id.myListView);
        myItems = new List<ReservationTime> ();

        myCPID = Settings.CharchingPoint_ID;
        myCPAddress = Settings.CharchingPointAddress;
        selectedDay.Text = myCPAddress;

        //get all the reservations from webservice
        try {
            string pathUrl = "reservations/weekReservations/";
            string currentToken = Settings.Token;

            var getResponse = await RequestClass.GetData (pathUrl, currentToken);

            result = JsonConvert.DeserializeObject<List<WeekReservationClass>> (getResponse);

        } catch (Exception ex) {
            Console.WriteLine ("Check error: " + ex);
        }

        showDay1.Click += ShowDay1_Click;
        showDay2.Click += ShowDay2_Click;
        showDay3.Click += ShowDay3_Click;
        showDay4.Click += ShowDay4_Click;
        showDay5.Click += ShowDay5_Click;
        showDay6.Click += ShowDay6_Click;
        showDay7.Click += ShowDay7_Click;

        makeBooking.Click += MakeBooking_Click;
    }

    void MakeBooking_Click (object sender, EventArgs e)
    {
        Settings.ChosenReservationDate = chosenDateCP.ToString ();
        Settings.CharchingPoint_ID = myCPID;
        StartActivity (typeof(ReservationHoursActivity));
    }

    //get and show reservation in listview
    void ShowDay7_Click (object sender, EventArgs e)
    {
        totalDays = int.Parse (showDay7.Text) - DateTime.Today.Day;
        chosenDateCP = DateTime.Today.AddDays (totalDays);

        myItems.Clear ();
        newList.Clear ();
        mListView.Adapter = null;

        //loop through json to get only reservation for day 7
        for (int i = 0; i < result.Count; i++) {
            Console.WriteLine (Convert.ToDateTime (result [i].startTime));

            if (Convert.ToDateTime (result [i].startTime).Date == chosenDateCP.Date && result [i].chargingPointID == myCPID) {

                var newReservation = new WeekReservationClass ();

                newReservation._id = result [i]._id;
                newReservation.endTime = result [i].endTime;
                newReservation.startTime = result [i].startTime;
                newReservation.chargingPointID = result [i].chargingPointID;
                newReservation.userID = result [i].userID;
                newReservation.__v = result [i].__v;
                newReservation.modified_at = result [i].modified_at;
                newReservation.created_at = result [i].created_at;

                newList.Add (newReservation);
            } else {
                Console.WriteLine ("failed");
            }
        }

        //loop through filtered list and show in listview
        for (int j = 0; j < newList.Count; j++) {
            Console.WriteLine (newList [j].startTime);
            myItems.Add (new ReservationTime () {
                StartTime = Convert.ToDateTime (newList [j].startTime), EndTime = Convert.ToDateTime (newList [j].endTime)
            });
        }
        MyListViewAdapter myadapter = new MyListViewAdapter (this, myItems);

        if (myadapter.IsEmpty) {
            Toast.MakeText (this, "There are no reservations for today", ToastLength.Long).Show ();
        } else {
            mListView.Adapter = myadapter;
        }

    }

    void ShowDay6_Click (object sender, EventArgs e)
    {
        totalDays = int.Parse (showDay6.Text) - DateTime.Today.Day;
        chosenDateCP = DateTime.Today.AddDays (totalDays);

        myItems.Clear ();
        newList.Clear ();
        mListView.Adapter = null;

        for (int i = 0; i < result.Count; i++) {
            Console.WriteLine (Convert.ToDateTime (result [i].startTime));
            if (Convert.ToDateTime (result [i].startTime).Date == chosenDateCP.Date && result [i].chargingPointID == myCPID) {

                var newReservation = new WeekReservationClass ();

                newReservation._id = result [i]._id;
                newReservation.endTime = result [i].endTime;
                newReservation.startTime = result [i].startTime;
                newReservation.chargingPointID = result [i].chargingPointID;
                newReservation.userID = result [i].userID;
                newReservation.__v = result [i].__v;
                newReservation.modified_at = result [i].modified_at;
                newReservation.created_at = result [i].created_at;

                newList.Add (newReservation);
            } else {
                Console.WriteLine ("failed");
            }
        }
        for (int j = 0; j < newList.Count; j++) {
            Console.WriteLine (newList [j].startTime);
            myItems.Add (new ReservationTime () {
                StartTime = Convert.ToDateTime (newList [j].startTime), EndTime = Convert.ToDateTime (newList [j].endTime)
            });
        }
        MyListViewAdapter myadapter = new MyListViewAdapter (this, myItems);

        if (myadapter.IsEmpty) {
            Toast.MakeText (this, "There are no reservations for today", ToastLength.Long).Show ();
        } else {
            mListView.Adapter = myadapter;
        }
    }
}

}

ReservationHoursActivity.cs

进行预订的代码并将其提交给webwervice

namespace iChargeClassTest
{
[Activity (Label = "ReservationHoursActivity", Theme = "@android:style/Theme.NoTitleBar")]          
public class ReservationHoursActivity : Activity, TimePickerDialog.IOnTimeSetListener
{
    string myDate;
    string myCP_ID;
    string selectedButtonDate;

    Button submitButtonMyslot;

    protected override void OnCreate (Bundle savedInstanceState)
    {
        base.OnCreate (savedInstanceState);
        SetContentView (Resource.Layout.ReservationHoursLayout);

        myDate = Settings.ChosenReservationDate;
        myCP_ID = Settings.CharchingPoint_ID;

        submitButtonMyslot = FindViewById<Button> (Resource.Id.btnSubmitSlot);
        submitButtonMyslot.Click += SubmitButtonMyslot_Click;

        /*
        Code for time picker
        */
    }

    /*
        methodes for time picker
    */

    //submit reservation
    async void SubmitButtonMyslot_Click (object sender, EventArgs e)
    {
        //post submitted data to webservice
        try {
            string stringDateTimeEND = Convert.ToDateTime (myDate).ToShortDateString () + " " + Convert.ToDateTime (time_display_End.Text).ToLongTimeString ();
            string stringDateTimeSTART = Convert.ToDateTime (myDate).ToShortDateString () + " " + Convert.ToDateTime (time_display_Start.Text).ToLongTimeString ();

            DateTime dtEnd = Convert.ToDateTime (stringDateTimeEND);
            DateTime dtStart = Convert.ToDateTime (stringDateTimeSTART);

            string utcEnd = dtEnd.ToUniversalTime ().ToString ("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
            string utcStart = dtStart.ToUniversalTime ().ToString ("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

            var postData = "endTime=" + utcEnd;
            postData += "&startTime=" + utcStart;
            postData += "&chargingPointID=" + myCP_ID;
            postData += "&userID=" + Settings.User_ID;

            string pathUrl = "reservations/add";

            var post_response = await RequestClass.PostData (postData, pathUrl, Settings.Token);

            Toast.MakeText (this, "Your Booking is succefully send!", ToastLength.Long).Show ();

            //restart weekactivity to refresh
            var intent = new Intent (this, typeof(WeekViewActivity));
            intent.SetFlags (ActivityFlags.ClearTop);
            StartActivity (intent);

            Finish ();//close the reservationHoursActivity

        } catch (WebException exception) {
            string responseText;
            using (var reader = new StreamReader (exception.Response.GetResponseStream ())) {
                responseText = reader.ReadToEnd ();
                Console.WriteLine (responseText);
            }
            Toast.MakeText (this, "Reservation Failed!", ToastLength.Long).Show ();
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

添加新预订后,您不应该重新启动活动。您应该打开&#34;新预订&#34; StartActivityForResult的活动,然后在OnActivityResult覆盖方法中处理返回的值。

您不需要实际返回任何内容,只需一个OK结果就会让您知道刷新数据(取消添加的用户会返回取消结果)。

就像......

private void AddReservationButtonClick(object sender, EventArgs e)
{
     var intent = new Intent(this, typeof(AddReservationActivity));
     StartActivityForResult(intent, 1000); // 1000 is just a random number, though it needs to match the value in OnActivityResult
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
     if (resultCode == Result.Cancelled)
     {
        // user cancelled the reservation add, so don't refresh
        return;
     }

     if (requestCode == 1000)
     {
         RefreshReservationData();
     }
}

这样可以避免重新创建Activity,这可能会节省内存。这也将解决你记住所选日期的问题,因为那天仍将被选中。

这是儿童活动的典型方式,让父母活动知道它已经完成了某些事情。