Forum Xamarin Xamarin.Android

how to get the value of the dynamic table row and add into a list

JunCainJunCain Member ✭✭✭
edited March 2019 in Xamarin.Android

I have dynamic table row and each dynamic table row has a three child (one spinner and two edittext). and I put it into a list each of my spinner and edittext value, but the problem is when I click the button send some values are not added into my list..

namespace MhylesApp
{
    [Activity(Label = "ToExistingCustomer", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Landscape)]
    public class ToExistingCustomer : Android.Support.V7.App.AppCompatActivity, ActivityCompat.IOnRequestPermissionsResultCallback
    {
        private static readonly int REQUEST_SENDSMS = 0;
        private SmsManager _smsManager;
        private static string _recipient = "0", _agent = "0", _cust = "0";
        private BroadcastReceiver _smsSentBroadcastReceiver, _smsDeliveredBroadcastReceiver;
        TableLayout tbleLayout;
        TableRow tr, _tr;
        private static string myResult;
        private static Button btn;
#pragma warning disable CS0618 // Type or member is obsolete
        public static ProgressDialog progressDialog;
#pragma warning restore CS0618 // Type or member is obsolete
        List<string> prodArray = new List<String>();
        private static Spinner spinner, spinner1, spinner2, spinner3, _spinner;
        private EditText qty, unit, _td1, _td2;
        private TextView txtdate;
        private static int agentID, custID, prodID;
        private static Button removeBtn;
        private static string agentName, custName, prodName, _prodId = "0", __prodId, __prodQty, __prodUnit, _var1 = "0", _var2 = "0";
        private List<string> recipient = new List<String>();
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.ExistingCustomer);
            recipient.Add("Select Recipient Number");
            recipient.Add("+639123456789");
            recipient.Add("+639112245678");
            layout = FindViewById(Resource.Id.ToExistingCust);
            qty = FindViewById<EditText>(Resource.Id.qty);
            unit = FindViewById<EditText>(Resource.Id.unit);
            txtdate = FindViewById<TextView>(Resource.Id.txtdate);
            DateTime now = DateTime.Now.ToLocalTime();
            txtdate.Text = "Date : " + now.ToString();

            _smsManager = SmsManager.Default;

            qty.TextChanged += Qty_TextChanged;
            unit.TextChanged += Unit_TextChanged;

            tbleLayout = FindViewById<TableLayout>(Resource.Id.tbleLayout);
            tr = FindViewById<TableRow>(Resource.Id.tr);

            removeBtn = FindViewById<Button>(Resource.Id.btnRemove);

            var btnSend = FindViewById<Button>(Resource.Id.btnSend);

            btnSend.Click += BtnSend_Click;

            spinner = FindViewById<Spinner>(Resource.Id.spinner);

            spinner1 = FindViewById<Spinner>(Resource.Id.spinner1);

            spinner2 = FindViewById<Spinner>(Resource.Id.spinner2);

            //spinner2 = new Spinner(new ContextThemeWrapper(this, Resource.Style.edit_spinner));

            spinner3 = FindViewById<Spinner>(Resource.Id.spinner3);
            btn = FindViewById<Button>(Resource.Id.btn);
            var adapter3 = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, recipient);
            //adapter3.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner3.Adapter = adapter3;
            spinner3.ItemSelected += Spinner3_ItemSelected;

            removeBtn.Click += RemoveBtn_Click;
            spinner1.ItemSelected += Spinner1_ItemSelected;
            spinner2.ItemSelected += Spinner2_ItemSelected;
            spinner.ItemSelected += Spinner_ItemSelected;



            GetProdData();
            GetAgentData();
            GetCustData();
            //disabledBtn();

            //<Generate new table row, spinnerand edittext>//
            btn.Click += (sender, e) =>
            {

                _tr = new TableRow(this);
                _spinner = new Spinner(this);
                _td1 = new EditText(this);
                _td2 = new EditText(this);

                if (tbleLayout.ChildCount == 12)
                {
                    Toast.MakeText(this, "Sorry, you can only order 10 products at a time", ToastLength.Short).Show();
                    return;
                }
                else
                {

                    _tr = new TableRow(new ContextThemeWrapper(this, Resource.Style.tableRow));

                    _td1.LayoutParameters = new TableRow.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);

                    _td1.SetBackgroundResource(Resource.Drawable.auto_borderColor);
#pragma warning disable CS0618 // Type or member is obsolete
                    _td1.SetTextColor(Resources.GetColorStateList(Resource.Drawable.myColors));
#pragma warning restore CS0618 // Type or member is obsolete
                    _td1.SetHint(Resource.String.qty);

                    _td2.LayoutParameters = new TableRow.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);

                    _td2.SetBackgroundResource(Resource.Drawable.auto_borderColor);
#pragma warning disable CS0618 // Type or member is obsolete
                    _td2.SetTextColor(Resources.GetColorStateList(Resource.Drawable.myColors));
#pragma warning restore CS0618 // Type or member is obsolete
                    _td2.SetHint(Resource.String.unit);


                    _spinner = new Spinner(new ContextThemeWrapper(this, Resource.Style.edit_spinner));
                    _spinner.SetBackgroundResource(Resource.Drawable.auto_DDarrow);

                    _spinner.SetPopupBackgroundResource(Resource.Drawable.spinnerPopBackground);

                    _spinner.Adapter = new ProductAdapter(prodData);

                    _tr.AddView(_spinner);

                    _tr.AddView(_td1);
                    _tr.AddView(_td2);
                    tbleLayout.AddView(_tr);

                    _td1.TextChanged += _td1_TextChanged;
                    _td2.TextChanged += _td2_TextChanged;
                    _spinner.ItemSelected += _spinner_ItemSelected;

                    if (__prodId != "0" || __prodQty != null || __prodQty != "" || __prodUnit != null || __prodUnit != "")
                    {
                        //for (int i = 3; i < tbleLayout.ChildCount; i++)
                        //{
                            String vars = __prodId;
                            String var1 = __prodQty;
                            String var2 = __prodUnit;

                            if (vars != null && var1 != null && var2 != null)
                            {
                                prodArray.Add(vars + "*" + var1 + "*" + var2);
                            }
                        //}
                    }


                }

            };

        }

Answers

  • JunCainJunCain Member ✭✭✭

    private void Spinner1_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
    {
    if(custData[e.Position].custID.ToString() != "0")
    {
    _cust = custData[e.Position].custID.ToString();
    }
    }

            private void Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
            {
                if(agentData[e.Position].agentID.ToString() != "0")
                {
                    _agent = agentData[e.Position].agentID.ToString();
                }
            }
    
            private void BtnSend_Click(object sender, EventArgs e)
            {
                if(qty.Text.Length == 0)
                {
    
                    qty.RequestFocus();
    #pragma warning disable CS0618 // Type or member is obsolete
                    qty.SetError(Html.FromHtml("<font color='red'>Quantity field cannot be empty!</font>"), null);
    #pragma warning restore CS0618 // Type or member is obsolete
    
                }
                if(unit.Text.Length == 0)
                {
                    unit.RequestFocus();
    #pragma warning disable CS0618 // Type or member is obsolete
                    unit.SetError(Html.FromHtml("<font color='red'>Unit field cannot be empty!</font>"), null);
    #pragma warning restore CS0618 // Type or member is obsolete
                }
                if (tbleLayout.ChildCount > 3)
                {
                    if (_td1.Text.Length == 0)
                    {
                        _td1.RequestFocus();
    #pragma warning disable CS0618 // Type or member is obsolete
                        _td1.SetError(Html.FromHtml("<font color='red'>Quantity field cannot be empty!</font>"), null);
    #pragma warning restore CS0618 // Type or member is obsolete
                    }
                    if (_td2.Text.Length == 0)
                    {
                        _td2.RequestFocus();
    #pragma warning disable CS0618 // Type or member is obsolete
                        _td2.SetError(Html.FromHtml("<font color='red'>Unit field cannot be empty!</font>"), null);
    #pragma warning restore CS0618 // Type or member is obsolete
                    }
                }
    
                prodArray.Add(_prodId + "*" + _var1 + "*" + _var2);
                String vars = __prodId;
                String var1 = __prodQty;
                String var2 = __prodUnit;
    
                if (vars != null && var1 != null && var2 != null)
                {
                    prodArray.Add(vars + "*" + var1 + "*" + var2);
                }
    
    #pragma warning disable CS0618 // Type or member is obsolete
                progressDialog = new ProgressDialog(this);
    #pragma warning restore CS0618 // Type or member is obsolete
                progressDialog.SetTitle("Sending");
                progressDialog.SetMessage("Sending message..Please wait!");
                progressDialog.SetCancelable(false);
                progressDialog.Show();
                if (_recipient == "0" || _agent == "0" || _cust == "0" || _prodId == "0" || _var1 == "0" || _var2 == "0" || TextUtils.IsEmpty(qty.Text) || TextUtils.IsEmpty(unit.Text))
                {
    #pragma warning disable CS0618 // Type or member is obsolete
                    Toast.MakeText(this, Html.FromHtml("<font color='red'>Please fill out all the fields!</font>"), ToastLength.Short).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                    progressDialog.Dismiss();
                    return;
                }
                else
                {
                    if (tbleLayout.ChildCount > 3)
                    {
                        int res = 1;
                        for (int i = 0; i < tbleLayout.ChildCount; i++)
                        {
                            if (__prodId == "0" || __prodQty == "0" || __prodUnit == "0" || TextUtils.IsEmpty(_td1.Text) || TextUtils.IsEmpty(_td2.Text))
                            {
                                res = 1;
                            }
                            else
                            {
                                res = 0;
                            }
                        }
                        if(res == 1)
                        {
    #pragma warning disable CS0618 // Type or member is obsolete
                            Toast.MakeText(this, Html.FromHtml("<font color='red'>Please fill out all the fields!</font>"), ToastLength.Short).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                            progressDialog.Dismiss();
                            return;
                        }
                    }
                    DateTime _now = DateTime.Now.ToLocalTime();
                    var sentDate = _now.ToString();
                    var number = _recipient;
                    var smsBody = string .Join("*",prodArray.ToArray());
                    var message = _agent + "|" + _cust + "|" + smsBody + "|" + sentDate;
                    var piSent = PendingIntent.GetBroadcast(this, 0, new Intent("SMS_SENT"), 0);
                    var piDelivered = PendingIntent.GetBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
                    if ((int)Build.VERSION.SdkInt < 23)
                    {
                        _smsManager.SendTextMessage(number, null, message, piSent, piDelivered);
    #pragma warning disable CS0618 // Type or member is obsolete
                        Toast.MakeText(this, Html.FromHtml("<font color='red'>Sending orders failed!</font>"), ToastLength.Short).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                        return;
                    }
                    else
                    {
                        if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.SendSms) != (int)Permission.Granted)
                        {
                            RequestSendSMSPermission();
                        }
                        else
                        {
                            _smsManager.SendTextMessage(number, null, message, piSent, piDelivered);
                        }
                    }
                }
            }
    
            private void Unit_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
            {
                _var2 = e.Text.ToString();
            }
    
            private void Qty_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
            {
                _var1 = e.Text.ToString();
            }
    
            private void _td2_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
            {
                __prodUnit = e.Text.ToString();
            }
    
            private void _td1_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
            {
                __prodQty = e.Text.ToString();
            }
    
            private void _spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
            {
                if(prodData[e.Position].prodId.ToString() != "0")
                {
                    __prodId = prodData[e.Position].prodId.ToString();
                } 
            }
    
            private void Spinner3_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
            {
               if(recipient[e.Position].ToString() != "Select Recipient Number")
               {
                    _recipient = recipient[e.Position].ToString();
               }
               else
                {
                    _recipient = "0";
                }
            }
            //<.......................>///
            //<Remove only the generated table row>//
            private void RemoveBtn_Click(object sender, EventArgs e)
            {
                int childCount = tbleLayout.ChildCount;
                if(childCount > 3)
                {
                    tbleLayout.RemoveViewAt(childCount - 1);
                }
                else
                {
    #pragma warning disable CS0618 // Type or member is obsolete
                    Toast.MakeText(this, Html.FromHtml("<font color='red'>Sorry, you can't delete the last product fields!</font>"), ToastLength.Short).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                }
            }
            //<......................>//
            //<This block of code is not final>//
            private void Spinner2_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
            {
                if(prodData[e.Position].prodId.ToString() != "0")
                {
                    _prodId = prodData[e.Position].prodId.ToString();
                }
                else
                {
                    _prodId = "0";
                }
            }
            //<..................................>//
            //<Fetching from sqlite>//
            private void GetProdData()
            {
                prodData.Clear();
                DBAdapter db = new DBAdapter(this);
                db.openDB();
                ICursor _cur = db.GetProdData();
                while (_cur.MoveToNext())
                {
                    prodID = _cur.GetInt(0);
                    prodName = _cur.GetString(1);
                    ProdDataBinding();
                }
                db.closeDB();
            }
            //<...............>//
            //<Data binding>//
            private static List<ProdModel> prodData = new List<ProdModel>();
            private static void ProdDataBinding()
            {
                ProdModel _prodModel = new ProdModel()
                {
                    prodId = prodID.ToString(),
                    prodName = prodName.ToString()
                };
                prodData.OrderBy(i => i.prodId).ToString();
                prodData.Add(_prodModel);
                if (prodData.Count > 0)
                {
    
                    spinner2.Adapter = new ProductAdapter(prodData);
    
                }
            }
            //<....................>//
            //<Fetching from sqlite>//
            private void GetCustData()
            {
                custData.Clear();
                DBAdapter db = new DBAdapter(this);
                db.openDB();
                ICursor _cur = db.GetCustData();
                while (_cur.MoveToNext())
                {
                    custID = _cur.GetInt(0);
                    custName = _cur.GetString(1);
                    CustDataBinding();
                }
    
                db.closeDB();
            }
            //<....................>//
            //<Data binding>//
            private static List<CustModel> custData = new List<CustModel>();
            private static void CustDataBinding()
            {
                CustModel _custModel = new CustModel()
                {
                    custID = custID.ToString(),
                    custName = custName.ToString()
                };
                custData.OrderBy(i => i.custID).ToString();
                custData.Add(_custModel);
                if (custData.Count > 0)
                {
                    spinner1.Adapter = new CustomerAdapter(custData);
                }
            }
            //<....................>//
            //<Fetching from sqlite>//
            private void GetAgentData()
            {
                agentData.Clear();
                DBAdapter db = new DBAdapter(this);
                db.openDB();
                ICursor _cur = db.GetAgentData();
                while (_cur.MoveToNext())
                {
                    agentID = _cur.GetInt(0);
                    agentName = _cur.GetString(1);
                    AgentDataBinding();
                }
    
                db.closeDB();
            }
            //<....................>//
            //<Data binding>//
            private static List<AgentModel> agentData = new List<AgentModel>();
            private View layout;
    
            private static void AgentDataBinding()
            {
                AgentModel _agentModel = new AgentModel()
                {
                    agentID = agentID.ToString(),
                    agentName = agentName.ToString()
    
                };
                agentData.OrderBy(i => i.agentID).ToString();
                agentData.Add(_agentModel);
                if(agentData.Count > 0)
                {
                    spinner.Adapter = new AgentAdapter(agentData);
                }
            }
            //<....................>//
            public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
            {
                Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode,permissions,grantResults);
                base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            }
            public void RequestSendSMSPermission()
            {
                Log.Info("ToExistingCustomer", "Message permission has not been granted. Requesting permission.");
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.SendSms))
                {
                    Log.Info("ToExistingCustomer", "Display message permission rationale to provide additional context.");
                    Snackbar.Make(layout, "Message permission is needed to send SMS.",
                        Snackbar.LengthIndefinite).SetAction("Ok", new Action<View>(delegate (View obj) 
                        {
                            ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.SendSms}, REQUEST_SENDSMS);
                        })).Show();
                }
                else
                {
                    ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.SendSms}, REQUEST_SENDSMS);
                }
            }
            protected override void OnResume()
            {
                base.OnResume();
                _smsSentBroadcastReceiver = new SMSSentReceiver();
                _smsDeliveredBroadcastReceiver = new SMSDeliveredReceiver();
                RegisterReceiver(_smsSentBroadcastReceiver, new IntentFilter("SMS_SENT"));
                RegisterReceiver(_smsDeliveredBroadcastReceiver, new IntentFilter("SMS_DELIVERED"));
            }
            protected override void OnPause()
            {
                base.OnPause();
                UnregisterReceiver(_smsSentBroadcastReceiver);
                UnregisterReceiver(_smsDeliveredBroadcastReceiver);
            }
            [BroadcastReceiver]
            public class SMSSentReceiver : BroadcastReceiver
            {
                public override void OnReceive(Context context, Intent intent)
                {
                    switch ((int)ResultCode)
                    {
                        case (int)Result.Ok:
    #pragma warning disable CS0618 // Type or member is obsolete
                            Toast.MakeText(Application.Context, Html.FromHtml("<font color='green'>SMS has been sent.</font>"), ToastLength.Short).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                            myResult = "Order Sent";
                            break;
                        case (int)SmsResultError.GenericFailure:
                            Toast.MakeText(Application.Context, "Generic Failure", ToastLength.Short).Show();
                            myResult = "Order Send Failed";
                            break;
                        case (int)SmsResultError.NoService:
                            Toast.MakeText(Application.Context, "No Service", ToastLength.Short).Show();
                            myResult = "Order Send Failed";
                            break;
                        case (int)SmsResultError.NullPdu:
                            Toast.MakeText(Application.Context, "Null PDU", ToastLength.Short).Show();
                            myResult = "Order Send Failed";
                            break;
                        case (int)SmsResultError.RadioOff:
                            Toast.MakeText(Application.Context, "Radio Off", ToastLength.Short).Show();
                            myResult = "Order Send Failed";
                            break;
                        default:
                            Toast.MakeText(Application.Context, "Radio Off", ToastLength.Short).Show();
                            myResult = "Order Send Failed";
                            break;
                    }
                    progressDialog.Dismiss();
                }
            }
            [BroadcastReceiver]
            public class SMSDeliveredReceiver : BroadcastReceiver
            {
                public override void OnReceive(Context context, Intent intent)
                {
                    switch ((int)ResultCode)
                    {
                        case (int)Result.Ok:
                            Toast.MakeText(Application.Context, "SMS Delivered", ToastLength.Short).Show();
                            myResult = "Order Sent";
                            break;
                        case (int)Result.Canceled:
                            Toast.MakeText(Application.Context, "SMS not delivered", ToastLength.Short).Show();
                            myResult = "Order Send Failed";
                            break;
                        default:
                            Toast.MakeText(Application.Context, "Radio Off", ToastLength.Short).Show();
                            myResult = "Order Send Failed";
                            break;
                    }
                    progressDialog.Dismiss();
                }
            }
    
        }
    
    }
    
  • JunCainJunCain Member ✭✭✭

    UI screenshot


  • JarvanJarvan Member, Xamarin Team Xamurai
    edited March 2019

    I reproduced the issue and the code are as follows. Hope it'll be helpful.
    MainActivity.cs

    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
        public class MainActivity : AppCompatActivity
        {
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.activity_main);
    
                List<string> recipient = new List<String>();
                recipient.Add("Select Recipient Number");
                recipient.Add("+639123456789");
                recipient.Add("+639112245678");
    
                ListView listView = FindViewById<ListView>(Resource.Id.listView_);
                ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem,recipient);
                listView.SetAdapter(adapter);
    
                TableLayout tableLayout = FindViewById<TableLayout>(Resource.Id.tableLayout_);
                Button btn = FindViewById<Button>(Resource.Id.btn);
                btn.Click += delegate {
                    TextView text = new TextView(this)
                    {
                        Text = "new TableRow",
                    };
                    TableRow table_ = new TableRow(this)
                    {
    
                    };
                    table_.AddView(text);
    
                    recipient.Add(text.Text);
    
                    listView.SetAdapter(new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, recipient));
    
                    tableLayout.AddView(table_);
                };
            }
        }
    

    activity_main.axml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <Button 
            android:id="@+id/btn"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:text="Add TableRow"/>
    
        <ListView 
            android:id="@+id/listView_"
            android:layout_height="250dp"
            android:layout_width="match_parent"/>
    
        <TableLayout
            android:id="@+id/tableLayout_"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:stretchColumns="1">
            <TableRow>
                <TextView 
                    android:layout_column="1"
                    android:text="text_view1"
                    android:padding="3dip"/>
                <TextView
                    android:text="Ctrl-0"
                    android:gravity="right"
                    android:padding="3dip"/>
            </TableRow>
    
            <TableRow>
                <TextView 
                    android:layout_column="1"
                    android:text="text_view1"
                    android:padding="3dip"/>
                <TextView
                    android:text="Ctrl-S"
                    android:gravity="right"
                    android:padding="3dip"/>
            </TableRow>
        </TableLayout>
    </LinearLayout>
    
Sign In or Register to comment.