How to pass my spinner list value into my other layout..

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

I retrieve data from my database using php and sync into my xamarin android app, retrieving and synchronizing is no problem, but my problem is how to pass that list of values that I put it into my spinner in my MainActivity into my other layout, my spinner is in my MainAcitvity layout but I don't want to place that spinner into my MainActivity, I want to place that into my other layout call ToexistingCustomer...Example when start my app the button sync and send are in my MainActivity and when I clicked the sync button and when synchronizing will become successful, all the data will stored and into an array and when I clicked the button send, the ToExistingCustomer layout will open and all my retrieve data that I stored into an array will displayed inside my ToExistingCustomer layout..

MainActivity.cs

using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using MhylesApp.Synchronizer;

namespace MhylesApp
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        private Spinner spinner;
        string urlAddress = "http://_IPAddress_/php_config/config.php";
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            spinner = FindViewById<Spinner>(Resource.Id.spinner);
            //spinner.SetBackgroundResource(Resource.Drawable.EditTxtStyle);
            Button sync = FindViewById<Button>(Resource.Id.sync);
            Button sendOrder = FindViewById<Button>(Resource.Id.sendOrder);
            sendOrder.Click += SendOrder_Click;    
            sync.Click += Sync_Click;
        }

        private void SendOrder_Click(object sender, System.EventArgs e)
        {
            StartActivity(typeof(ToExistingCustomer));
        }

        private void Sync_Click(object sender, System.EventArgs e)
        {
            new Syncher(this, urlAddress, spinner).Execute();
        }
    }
}

DataParser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Org.Json;
using Exception = System.Exception;
using Object = Java.Lang.Object;
using String = System.String;

namespace MhylesApp.Synchronizer
{
    class DataParser : AsyncTask
    {
        Context c;
        private Spinner spinner;
        private String jsonData;
        JavaList<string> agent = new JavaList<string>();
#pragma warning disable CS0618 // Type or member is obsolete
        private ProgressDialog loadingProcess;
#pragma warning restore CS0618 // Type or member is obsolete
        public DataParser(Context c, Spinner spinner, string jsonData)
        {
            this.c = c;
            this.spinner = spinner;
            this.jsonData = jsonData;
        }
        protected override void OnPreExecute()
        {
            base.OnPreExecute();
#pragma warning disable CS0618 // Type or member is obsolete
            loadingProcess = new ProgressDialog(c);
#pragma warning restore CS0618 // Type or member is obsolete
            loadingProcess.SetTitle("Synchronizing");
            loadingProcess.SetMessage("Fetching Data...Please wait!");
            loadingProcess.Show();
        }
        protected override Object DoInBackground(params Object[] @params)
        {
            return this.ParseData();
        }
        protected override void OnPostExecute(Object result)
        {
            base.OnPostExecute(result);
            loadingProcess.Dismiss();
            if(Integer.ParseInt(result.ToString()) == 0)
            {
                Toast.MakeText(c, "Unable to parse data", ToastLength.Short).Show();
            }
            else
            {
                ToExistingCustomer toExistingCustomer = new ToExistingCustomer();
                ArrayAdapter<string> adapter = new ArrayAdapter<string>(c, Android.Resource.Layout.SimpleListItem1, agent);
                spinner.Adapter = adapter;

            }
        }
        private int ParseData()
        {
            try
            {
                JSONArray jsonArray = new JSONArray(jsonData);
                JSONObject jsonObj = null;

                agent.Clear();
                agent.Add("Select Recipient No.");
                for (int i = 0; i < jsonArray.Length(); i++)
                {
                    jsonObj = jsonArray.GetJSONObject(i);
                    String num = jsonObj.GetString("agent_contact");
                    agent.Add(num);
                }
                return 1;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }
            return 0;
        }
    }
}~~~~

Syncher.cs

using System;
using System.IO;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
using Java.IO;
using Java.Lang;
using Java.Net;
using Console = System.Console;
using Exception = System.Exception;
using Object = Java.Lang.Object;

namespace MhylesApp.Synchronizer
{
    class Syncher : AsyncTask
    {
        private Context c;
        private string urlAddress;
        private Spinner spinner;
#pragma warning disable CS0618 // Type or member is obsolete
        private ProgressDialog loadingProcess;
#pragma warning restore CS0618 // Type or member is obsolete
        public Syncher(Context c, string urlAddress, Spinner spinner)
        {
            this.c = c;
            this.urlAddress = urlAddress;
            this.spinner = spinner;
        }
        protected override void OnPreExecute()
        {
            base.OnPreExecute();
#pragma warning disable CS0618 // Type or member is obsolete
            loadingProcess = new ProgressDialog(c);
#pragma warning restore CS0618 // Type or member is obsolete
            loadingProcess.SetTitle("Synchronizing");
            loadingProcess.SetMessage("Fetching Data...Please wait!");
            loadingProcess.Show();
        }
        protected override Object DoInBackground(params Object[] @params)
        {
            return this.Retrieve();
        }
        protected override void OnPostExecute(Object result)
        {
            base.OnPostExecute(result);
            loadingProcess.Dismiss();
            if(result == null)
            {
                Toast.MakeText(c, "Synchronizing failed!", ToastLength.Short).Show();
            }
            else
            {
                DataParser parser = new DataParser(c, spinner, result.ToString());
                parser.Execute();
            }
        }
        //Retrieving Data
        private string Retrieve()
        {
            HttpURLConnection con = Connector.Connect(urlAddress);
            if(con == null)
            {
                return null;
            }
            try
            {
                Stream stream = new BufferedStream(con.InputStream);
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
                string line = null;
                StringBuffer response = new StringBuffer();
                while ((line = bufferedReader.ReadLine()) != null)
                {
                    response.Append(line + "\n");
                }
                bufferedReader.Close();
                stream.Close();
                return response.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
    }
}``

Connector.cs

using System;
using Java.Net;

namespace MhylesApp.Synchronizer
{
    class Connector
    {
        public static HttpURLConnection Connect(String urlAddress)
        {
            try
            {
                URL url = new URL(urlAddress);
                HttpURLConnection con = (HttpURLConnection)url.OpenConnection();

                //Properties
                con.RequestMethod = "GET";
                con.ConnectTimeout = 20000;
                con.ReadTimeout = 20000;
                con.DoInput = true;
                return con;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
    }
}

Best Answers

Answers

  • JunCainJunCain Member ✭✭✭

    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">
    
        <Spinner
            android:id="@+id/spinner"
            style="@style/edit_margin"
            android:layout_width="match_parent"
            android:dropDownSelector="@drawable/abc_ab_share_pack_mtrl_alpha"
            android:layout_height="wrap_content"/>
            <Button
                android:text="Sync"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/sync"/>
        <Button
                android:text="Send order"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/sendOrder"/>
    
    </LinearLayout>
    

    ExistingCustomer.axml

    <?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">
        <Spinner
            android:id="@+id/spinner"
            style="@style/edit_margin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
    

    ToExistingCustomer.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using MhylesApp.Synchronizer;
    
    namespace MhylesApp
    {
        [Activity(Label = "ToExistingCustomer")]
        public class ToExistingCustomer : Activity
        {
            private Spinner spinner;
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.ExistingCustomer);
    
                spinner = FindViewById<Spinner>(Resource.Id.spinner);
                spinner.SetBackgroundResource(Resource.Drawable.EditTxtStyle);
    
            }
        }
    }
    
  • JunCainJunCain Member ✭✭✭
    edited March 15

    I want to throw the data into my ToExistingCustomer.cs instead of returning the data into my MainActivity.cs

  • JunCainJunCain Member ✭✭✭

    instead of spinner, I use List in my mainactivity as a global variable?

  • jezhjezh Member, Xamarin Team Xamurai

    @JunCain

    Of course , you can try this.

  • JunCainJunCain Member ✭✭✭
    edited March 18

    Why edittext.SetHint does not working in C# if I put a string value
    ?

  • JunCainJunCain Member ✭✭✭
    edited March 18

    thank you Sir jezh..
    can I ask other question? how can I add a textinputlayout pragrammatically?
    I have an auto generated tablelayout and tablerow width edittext inside the tablerow and I want to put a textinputlayout in each edittext..

    btn.Click += (sender, e) =>
                {
                    tr = new TableRow(this);
                    _spinner = new Spinner(this);
                    _td1 = new EditText(this);
                    _td2 = new EditText(this);
                    _td1.SetHint(Resource.String.qty);
                    _td2.SetHint(Resource.String.unit);
                    TextInputLayout textInputLayout = new TextInputLayout(this);
                    textInputLayout.AddView(_td1);
                    textInputLayout.AddView(_td2);
                    _td1.SetBackgroundResource(Resource.Drawable.EditDesign);
                    _td2.SetBackgroundResource(Resource.Drawable.EditDesign);
                    _spinner.SetBackgroundResource(Resource.Drawable.EditTxtStyle);
                    ArrayAdapter<string> _adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, prodList);
                    _spinner.Adapter = _adapter;
                    tr.AddView(textInputLayout);
                    tr.AddView(_spinner);
                    tr.AddView(_td1);
                    tr.AddView(_td2);
                    tbleLayout.AddView(tr);
                };
    
  • jezhjezh Member, Xamarin Team Xamurai

    @JunCain
    Could you please post a basic demo?

  • JunCainJunCain Member ✭✭✭

    If I click the generated button my app generates another spinner(Select Product Name) and edittext(Quantity, Unit) I want to put a textinputlayout on a generated edittext in order to have an uniformity designs of the first edittext(Quantity, Unit) rows.

  • JunCainJunCain Member ✭✭✭

    case solved..

  • jezhjezh Member, Xamarin Team Xamurai

    @JunCain

    Congrats, you solved this problem so efficiently.
    Could you please sharing the solution so that others could get help from this case.

  • JunCainJunCain Member ✭✭✭

    I did not wrap my edittext a textinputlayout :blush: because if I wrap my edittext a textinputlayout it will create a space on top and that space will ruin my design :smiley:

  • JunCainJunCain Member ✭✭✭

    I have another problem how to put a height and width in my edittext and spinner programmatically? co'z when I click the generate button my design looks so ugly. I want to make it equal height and width each of my spinner and edittext in every tableRow.

  • JunCainJunCain Member ✭✭✭

    ToExistingCustomer.cs

    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Widget;
    using Java.Lang;
    using Java.Net;
    using System.IO;
    using Console = System.Console;
    using Exception = System.Exception;
    using Object = Java.Lang.Object;
    using MhylesApp.Synchronizer;
    using Java.IO;
    using System.Collections.Generic;
    using Android.Content.PM;
    using System;
    using Android.Views;
    
    namespace MhylesApp
    {
        [Activity(Label = "ToExistingCustomer", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Landscape)]
        public class ToExistingCustomer : Android.Support.V7.App.AppCompatActivity
        {
            //IList<string> agentData = new List<string>();
            IList<string> agentList = new List<string>();
            IList<string> custList = new List<string>();
            IList<string> prodList = new List<string>();
            TableLayout tbleLayout;
            TableRow tr, _tr;
            private static Spinner spinner, spinner1, spinner2, spinner3, _spinner;
            private EditText qty, unit, _td1, _td2;
            //private TextView _spinner2;
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.ExistingCustomer);
    
                qty = FindViewById<EditText>(Resource.Id.qty);
                unit = FindViewById<EditText>(Resource.Id.unit);
                tbleLayout = FindViewById<TableLayout>(Resource.Id.tbleLayout);
                tr = FindViewById<TableRow>(Resource.Id.tr);
                //tbleLayout.SetColumnStretchable(0, true);
                //tbleLayout.SetColumnStretchable(1, true);
    
                //qty.SetBackgroundResource(Resource.Drawable.EditDesign);
                //unit.SetBackgroundResource(Resource.Drawable.EditDesign);
    
    
    
    
                agentList = Intent.GetStringArrayListExtra("agentList");
                agentList.Add("Select Agent Name");
                spinner = FindViewById<Spinner>(Resource.Id.spinner);
    
                custList = Intent.GetStringArrayListExtra("custList");
                custList.Add("Select Customer Name");
                spinner1 = FindViewById<Spinner>(Resource.Id.spinner1);
    
                prodList = Intent.GetStringArrayListExtra("prodList");
                //prodList.Add("Select Product Name");
                spinner2 = FindViewById<Spinner>(Resource.Id.spinner2);
    
    
                //spinner2.SetPromptId(Resource.String.product);
                //spinner2.SetBackgroundResource(Resource.Drawable.EditDesign);
                spinner3 = FindViewById<Spinner>(Resource.Id.spinner3);
                var btn = FindViewById<Button>(Resource.Id.btn);
                var adapter3 = ArrayAdapter.CreateFromResource(this, Resource.Array.Recipient, Android.Resource.Layout.SimpleSpinnerItem);
                adapter3.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                spinner3.Adapter = adapter3;
                spinner3.SetBackgroundResource(Resource.Drawable.EditTxtStyle);
    
                ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, agentList);
                spinner.Adapter = adapter;
                ArrayAdapter<string> adapter1 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, custList);
                spinner1.Adapter = adapter1;
    
                ArrayAdapter<string> adapter2 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleDropDownItem1Line, prodList);
    
    
                adapter2.SetDropDownViewResource(Resource.Layout.productTextView);
                spinner2.SetBackgroundResource(Resource.Drawable.borderColor);
                prodList.Add("Select Product Name");
                spinner2.Adapter = adapter2;
                spinner2 = new Spinner(new ContextThemeWrapper(this, Resource.Style.edit_spinner));
    
    
                btn.Click += (sender, e) =>
                {
                    _tr = new TableRow(this);
                    _spinner = new Spinner(this);
    
                    _td1 = new EditText(this);
                    _td2 = new EditText(this);
    
    
                    //_td1.LayoutParameters = new LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
    
                    _tr = new TableRow(new ContextThemeWrapper(this, Resource.Style.tableRow));
    
    
    
    
                    //_tr.SetPadding(2, 2, 2, 2);
                    //_tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams 0dp, ))
    
    
                    //_td1.SetBackgroundResource(Resource.Drawable.EditDesign);
                    //_td2.SetBackgroundResource(Resource.Drawable.EditDesign);
                    //TextInputLayout textInputLayout = new TextInputLayout(this);
                    //TextInputLayout textInputLayout1 = new TextInputLayout(this);
                    _td1 = new EditText(new ContextThemeWrapper(this, Resource.Style.edit_margin));
                    _td1.SetBackgroundResource(Resource.Drawable.borderColor);
                    _td1.SetHint(Resource.String.qty);
    
                    _td2 = new EditText(new ContextThemeWrapper(this, Resource.Style.edit_margin));
                    _td2.SetBackgroundResource(Resource.Drawable.borderColor);
                    _td2.SetHint(Resource.String.unit);
    
                    //textInputLayout.AddView(_td1);
                    //textInputLayout11.AddView(_td2);
                    //_td1.SetBackgroundResource(Resource.Drawable.EditDesign);
                    //_td2.SetBackgroundResource(Resource.Drawable.EditDesign);
                    //_spinner.SetBackgroundResource(Resource.Drawable.EditTxtStyle);
    
    
                    //_tr.AddView(textInputLayout);
                    _spinner = new Spinner(new ContextThemeWrapper(this, Resource.Style.edit_spinner));
                    _spinner.SetBackgroundResource(Resource.Drawable.borderColor);
                    ArrayAdapter<string> _adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleDropDownItem1Line, prodList);
                    _adapter.SetDropDownViewResource(Resource.Layout.productTextView);
                    _spinner.Adapter = _adapter;
                    _tr.AddView(_spinner);
    
    
    
    
                    _tr.AddView(_td1);
    
    
                    _tr.AddView(_td2);
    
    
    
                    tbleLayout.AddView(_tr);
    
    
                };
    
    
            }
        }
    
    }
    
  • JunCainJunCain Member ✭✭✭

    ExistingCustomer.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:orientation="vertical"
        android:background="@android:color/black"
        android:textColor="#b4ebf7"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scrollbars="none"
            android:layout_weight="1">
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical">
                <Spinner
                    android:id="@+id/spinner3"
                    android:background="@drawable/EditTxtStyle"
                    android:singleLine="true"
                    style="@style/edit_margin"
                    android:padding="8dp"
                    android:popupBackground="#00826b"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <Spinner
                    android:id="@+id/spinner"
                    android:background="@drawable/EditTxtStyle"
                    android:singleLine="true"
                    style="@style/edit_margin"
                    android:popupBackground="#00826b"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <Spinner
                    android:id="@+id/spinner1"
                    android:background="@drawable/EditTxtStyle"
                    android:singleLine="true"
                    style="@style/edit_margin"
                    android:popupBackground="#00826b"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <TableLayout
                    android:id="@+id/tbleLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:stretchColumns="*"
                    android:isScrollContainer="true">
                    <TableRow
                        android:id="@+id/tr"
                        style="@style/tableRow">
                        <TextView
                            android:text="Product"
                            style="@style/edit_margin"
                            android:background="@drawable/borderColor"/>
                        <TextView
                            android:text="Product Quantity"
                            style="@style/edit_margin"
                            android:background="@drawable/borderColor"/>
                        <TextView
                            android:text="Product Unit"
                            style="@style/edit_margin"
                            android:background="@drawable/borderColor"/>
                    </TableRow>
                    <TableRow
                        android:id="@+id/tr"
                        style="@style/tableRow">
                        <Spinner
                            android:id="@+id/spinner2"/>
                        <EditText
                            android:id="@+id/qty"
                            style="@style/edit_margin"
                            android:background="@drawable/borderColor"
                            android:hint="Product Quantity"/>
                        <EditText
                            android:id="@+id/unit"
                            style="@style/edit_margin"
                            android:background="@drawable/borderColor"
                            android:hint="Product Unit"/>
                    </TableRow>
                </TableLayout>
                <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Generate"
                android:id="@+id/btn"/>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>
    

    productTextView.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_weight="1"
      android:layout_marginLeft="2dp"
      android:textSize="16sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    

    borderColor.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
      <solid android:color="@android:color/transparent" />
      <stroke android:width="2dip" android:color="#0b7eea"/>
    </shape>
    

    colors.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="colorPrimary">#2c3e50</color>
        <color name="colorPrimaryDark">#1B3147</color>
        <color name="colorAccent">#3498db</color>
       <color name="myTextColors">#0b7eea</color>
      <color name="placeholderColor">#0b7eea</color>
    </resources>
    

    spinnerPadding.xml

    <?xml version="1.0" encoding="utf-8" ?>
    <resources>
      <style name="edit_spinner">
        <item name="android:layout_marginTop">-2dp</item>
        <item name="android:layout_marginBottom">0dp</item>
        <item name="android:layout_marginLeft">0dp</item>
        <item name="android:layout_marginRight">0dp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_weight">1</item>
        <item name="android:popupBackground">#00826b</item>
        <item name="android:padding">0dp</item>
      </style>
    </resources>
    
  • JunCainJunCain Member ✭✭✭

    tableRowBackground.xml

    <?xml version="1.0" encoding="utf-8" ?>
    <resources>
      <style name="tableRow">
        <item name="android:layout_width">0dp</item>
        <item name="android:background">#000000</item>
        <item name="android:layout_height">20dp</item>
      </style>
    </resources>
    

    design.xml

    <?xml version="1.0" encoding="utf-8" ?>
    <resources>
      <style name="edit_margin">
        <item name="android:layout_margin">0dp</item>
        <item name="android:padding">5dp</item>
        <item name="android:textSize">16sp</item>
        <item name="android:textColor">#0b7eea</item>
        <item name="android:layout_weight">1</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:textColorHint">#0b7eea</item>
      </style>
    </resources>
    
  • JunCainJunCain Member ✭✭✭

    case solved

    solution:

    btn.Click += (sender, e) =>
                {
                    _tr = new TableRow(this);
                    _spinner = new Spinner(this);
    
                    _td1 = new EditText(this);
                    _td2 = new EditText(this);
    
                    //_td1.LayoutParameters = new LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
    
                    _tr = new TableRow(new ContextThemeWrapper(this, Resource.Style.tableRow));
    
    
    
    
                    //_tr.SetPadding(2, 2, 2, 2);
                    //_tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams 0dp, ))
    
    
                    //_td1.SetBackgroundResource(Resource.Drawable.EditDesign);
                    //_td2.SetBackgroundResource(Resource.Drawable.EditDesign);
                    //TextInputLayout textInputLayout = new TextInputLayout(this);
                    //TextInputLayout textInputLayout1 = new TextInputLayout(this);
                    _td1.LayoutParameters = new TableRow.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
                    _td1.Visibility = ViewStates.Visible;
                    _td1.SetBackgroundResource(Resource.Drawable.borderColor);
                    _td1.SetHint(Resource.String.qty);
    
                    _td2.LayoutParameters = new TableRow.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
                    _td2.Visibility = ViewStates.Visible;
                    //_td2 = new EditText(new ContextThemeWrapper(this, Resource.Style.edit_margin));
                    _td2.SetBackgroundResource(Resource.Drawable.borderColor);
                    _td2.SetHint(Resource.String.unit);
    
                    //textInputLayout.AddView(_td1);
                    //textInputLayout11.AddView(_td2);
                    //_td1.SetBackgroundResource(Resource.Drawable.EditDesign);
                    //_td2.SetBackgroundResource(Resource.Drawable.EditDesign);
                    //_spinner.SetBackgroundResource(Resource.Drawable.EditTxtStyle);
    
    
                    //_tr.AddView(textInputLayout);
                    _spinner = new Spinner(new ContextThemeWrapper(this, Resource.Style.edit_spinner));
                    _spinner.SetBackgroundResource(Resource.Drawable.borderColor);
                    ArrayAdapter<string> _adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleDropDownItem1Line, prodList);
                    _adapter.SetDropDownViewResource(Resource.Layout.productTextView);
                    _spinner.Adapter = _adapter;
                    _tr.AddView(_spinner);
    
    
    
    
    
    
                    //_td1.LayoutParameters = _params;
                    //ViewGroup.LayoutParams _params = _td1.getLayoutParams();
    
    
                    //_td1 = new EditText(new ContextThemeWrapper(this, Resource.Style.edit_margin));
    
                    _tr.AddView(_td1);
    
    
    
    
                    _tr.AddView(_td2);
    
    
    
                    tbleLayout.AddView(_tr);
    
    
                };
    
  • PeterkrishPeterkrish Member
    edited October 18

    Hello juncain I am trying to connect spinner in my app to my 000webhost database I used the code from you but I getting the "Synchronizing failed!" error I found that the result is null from my php but when I use the url it is showing output

  • JunCainJunCain Member ✭✭✭

    @Peterkrish here is my final code for synchronizing

    public class MainActivity {
         string url = "http://mypersonalsite.somee.com/api/agent?num=9870112";
            string url1 = "http://mypersonalsite.somee.com/api/customer?num=9870112";
            string url2 = "http://mypersonalsite.somee.com/api/product?num=9870112";
            string url3 = "http://mypersonalsite.somee.com/api/category?num=9870112";
    
        protected override void OnCreate(Bundle InstanceState) {
    
        }
         public override bool OnOptionsItemSelected(IMenuItem item)
            {
                int id = item.ItemId;
                if (id == Resource.Id.action_settings)
                {
                    //new Syncher(this, url, url1, url2, url3).Execute();
                    ConnectivityManager conMnger = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
                    NetworkInfo netInfo = conMnger.ActiveNetworkInfo;
                    if (netInfo != null && netInfo.IsConnectedOrConnecting)
                    {
                        var sync = new Intent(this, typeof(SyncSplash));
                        sync.PutExtra("MyUrl", url + "|" + url1 + "|" + url2 + "|" + url3);
                        StartActivity(sync);
                        this.Finish();
                    }
                    else
                    {
    #pragma warning disable CS0618 // Type or member is obsolete
                        Toast.MakeText(Application.Context, Html.FromHtml("<font color='#f41f1f'>You are not connected to the internet, Please to any avialable wifi connection or activate your mobile data.</font>"), ToastLength.Long).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                    }
                }
    
                return base.OnOptionsItemSelected(item);
            }
    }
    
     public class SyncSplash 
        {
            ImageView imgView;
            AnimationDrawable animationD;
            public string myStr, str1, str2, str3, str4;
            public string url, url1, url2, url3;
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.SyncSplash);
                imgView = FindViewById<ImageView>(Resource.Id.animate);
                animationD = (AnimationDrawable)imgView.Drawable;
                animationD.Start();
                myStr = Intent.GetStringExtra("MyUrl") ?? "No Data";
                string[] str = myStr.Split("|");
                for(int i = 0; i < str.Count(); i++)
                {
                    url = str[0];
                    url1 = str[1];
                    url2 = str[2];
                    url3 = str[3];
                }
                if(url != "" && url1 != "" && url2 != "" && url3 != "")
                {
                    new Syncher(this, url, url1, url2, url3).Execute();
                }
            }
        }
    
  • JunCainJunCain Member ✭✭✭
     public class Syncher : AsyncTask
        {
            private Context c;
            private string url, url1, url2, url3;
    #pragma warning disable CS0618 // Type or member is obsolete
            private ProgressDialog Progress;
    #pragma warning restore CS0618 // Type or member is obsolete
    
            public Syncher(Context c, string url, string url1, string url2, string url3)
            {
                this.c = c;
                this.url = url;
                this.url1 = url1;
                this.url2 = url2;
                this.url3 = url3;
            }
    
            protected override void OnPreExecute()
            {
                base.OnPreExecute();
    #pragma warning disable CS0618 // Type or member is obsolete
                Progress = new ProgressDialog(c);
    #pragma warning restore CS0618 // Type or member is obsolete
                //Progress.SetTitle("Synchronizing");
                Progress.SetMessage("Synchronizing..Please wait!");
                Progress.SetCancelable(false);
                Progress.Show();
            }
    
            protected override void OnPostExecute(Object result)
            {
                base.OnPostExecute(result);
                Progress.Dismiss();
                if(result == null)
                {
                    Toast.MakeText(c, "Synchronizing failed!", ToastLength.Short).Show();
                }
                else
                {
                    DataParser parser = new DataParser(c, result.ToString());
                    parser.Execute();
                }
            }
    
            protected override Object DoInBackground(params Object[] @params)
            {
                return this.Retrieve() +
                    this.Retrieve1() +
                    this.Retrieve2() +
                    this.Retrieve3();
            }
    
            private string Retrieve()
            {
                HttpURLConnection con = Connector.Connect(url);
                if (con == null)
                {
                    return null;
                }
                try
                {
                    Stream stream = new BufferedStream(con.InputStream);
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
                    string line = null;
                    StringBuffer response = new StringBuffer();
                    while ((line = bufferedReader.ReadLine()) != null)
                    {
                        response.Append(line + "\n");
                    }
                    bufferedReader.Close();
                    stream.Close();
                    return response.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return null;
            }
    
            private string Retrieve1()
            {
                HttpURLConnection con1 = Connector.Connect1(url1);
                if (con1 == null)
                {
                    return null;
                }
                try
                {
                    Stream stream1 = new BufferedStream(con1.InputStream);
                    BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(stream1));
                    string line1 = null;
                    StringBuffer response1 = new StringBuffer();
                    while ((line1 = bufferedReader1.ReadLine()) != null)
                    {
                        response1.Append(line1 + "\n");
                    }
                    bufferedReader1.Close();
                    stream1.Close();
                    return response1.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return null;
            }
    
            private string Retrieve2()
            {
                HttpURLConnection con2 = Connector.Connect2(url2);
                if (con2 == null)
                {
                    return null;
                }
                try
                {
                    Stream stream2 = new BufferedStream(con2.InputStream);
                    BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(stream2));
                    string line2 = null;
                    StringBuffer response2 = new StringBuffer();
                    while ((line2 = bufferedReader2.ReadLine()) != null)
                    {
                        response2.Append(line2 + "\n");
                    }
                    bufferedReader2.Close();
                    stream2.Close();
                    return response2.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return null;
            }
    
            private string Retrieve3()
            {
                HttpURLConnection con3 = Connector.Connect3(url3);
                if (con3 == null)
                {
                    return null;
                }
                try
                {
                    Stream stream3 = new BufferedStream(con3.InputStream);
                    BufferedReader bufferedReader3 = new BufferedReader(new InputStreamReader(stream3));
                    string line3 = null;
                    StringBuffer response3 = new StringBuffer();
                    while ((line3 = bufferedReader3.ReadLine()) != null)
                    {
                        response3.Append(line3 + "\n");
                    }
                    bufferedReader3.Close();
                    stream3.Close();
                    return response3.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return null;
            }
        }
    
  • JunCainJunCain Member ✭✭✭
    public class Connector
        {
            public static HttpURLConnection Connect(String url)
            {
                try
                {
                    URL address = new URL(url);
                    HttpURLConnection con = (HttpURLConnection)address.OpenConnection();
    
                    //Properties
                    con.RequestMethod = "GET";
                    con.ConnectTimeout = 20000;
                    con.ReadTimeout = 20000;
                    con.DoInput = true;
                    return con;
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return null;
            }
    
            public static HttpURLConnection Connect1(String url1)
            {
                try
                {
                    URL address1 = new URL(url1);
                    HttpURLConnection con1 = (HttpURLConnection)address1.OpenConnection();
    
                    //Properties
                    con1.RequestMethod = "GET";
                    con1.ConnectTimeout = 20000;
                    con1.ReadTimeout = 20000;
                    con1.DoInput = true;
                    return con1;
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return null;
            }
    
            public static HttpURLConnection Connect2(String url2)
            {
                try
                {
                    URL address2 = new URL(url2);
                    HttpURLConnection con2 = (HttpURLConnection)address2.OpenConnection();
    
                    //Properties
                    con2.RequestMethod = "GET";
                    con2.ConnectTimeout = 20000;
                    con2.ReadTimeout = 20000;
                    con2.DoInput = true;
                    return con2;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return null;
            }
    
            public static HttpURLConnection Connect3(String url3)
            {
                try
                {
                    URL address3 = new URL(url3);
                    HttpURLConnection con3 = (HttpURLConnection)address3.OpenConnection();
    
                    //Properties
                    con3.RequestMethod = "GET";
                    con3.ConnectTimeout = 20000;
                    con3.ReadTimeout = 20000;
                    con3.DoInput = true;
                    return con3;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return null;
            }
        }
    
  • PeterkrishPeterkrish Member

    @JunCain thank you so much for your reply I will go through it

  • JunCainJunCain Member ✭✭✭
    public class DataParser : AsyncTask
        {
            Context c;
            private String jsonData;
            private string list, list1, list2, list3;
    #pragma warning disable CS0618 // Type or member is obsolete
            private ProgressDialog Progress;
    #pragma warning restore CS0618 // Type or member is obsolete
    
            public DataParser(Context c, String jsonData)
            {
                this.c = c;
                this.jsonData = jsonData;
            }
    
            protected override void OnPreExecute()
            {
                base.OnPreExecute();
    #pragma warning disable CS0618 // Type or member is obsolete
                Progress = new ProgressDialog(c);
    #pragma warning restore CS0618 // Type or member is obsolete
                //Progress.SetTitle("Synchronizing");
                Progress.SetMessage("We're almost done!");
                Progress.SetCancelable(false);
                Progress.Show();
            }
    
            protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
            {
                return this.ParserData();
            }
    
            protected override void OnPostExecute(Java.Lang.Object result)
            {
                base.OnPostExecute(result);
                Progress.Dismiss();
                if (Integer.ParseInt(result.ToString()) == 0)
                {
    #pragma warning disable CS0618 // Type or member is obsolete
                    Toast.MakeText(c, Html.FromHtml("<font color='red'>Unable to parse data</font>"), ToastLength.Short).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                    c.StartActivity(typeof(MainActivity));
                }
                else
                {
    #pragma warning disable CS0618 // Type or member is obsolete
                    Toast.MakeText(c, Html.FromHtml("<font color='green'>Parsing Data successful!</font>"), ToastLength.Short).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                    c.StartActivity(typeof(MainActivity));
                }
            }
    
            private int ParserData()
            {
                try
                {
                    string[] array = jsonData.Split("\n");
                    for (int x = 0; x < array.Count(); x++)
                    {
                        list = array[0];
                        list1 = array[1];
                        list2 = array[2];
                        list3 = array[3];
                    }
    
                    JSONArray jSONArray = new JSONArray(list);
                    JSONObject jSONObject = null;
    
                    for (int i = 0; i < jSONArray.Length(); i++)
                    {
                        jSONObject = jSONArray.GetJSONObject(i);
    
                        String agentId = jSONObject.GetString("AgentId");
                        String agentName = jSONObject.GetString("AgentName");
                        DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.AddAgent(Convert.ToInt32(agentId), agentName);
                        db.closeDB();
                    }
    
                    JSONArray jSONArray1 = new JSONArray(list1);
                    JSONObject jSONObject1 = null;
    
                    for (int q = 0; q < jSONArray1.Length(); q++)
                    {
                        jSONObject1 = jSONArray1.GetJSONObject(q);
    
                        String custId = jSONObject1.GetString("CustId");
                        String custName = jSONObject1.GetString("CustName");
                        DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.AddCustomer(Convert.ToInt32(custId), custName);
                        db.closeDB();
                    }
    
                    JSONArray jSONArray2 = new JSONArray(list2);
                    JSONObject jSONObject2 = null;
    
                    for (int z = 0; z < jSONArray2.Length(); z++)
                    {
                        jSONObject2 = jSONArray2.GetJSONObject(z);
    
                        String prodId = jSONObject2.GetString("ProductId");
                        String prodName = jSONObject2.GetString("ProdName");
                        DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.AddProduct(Convert.ToInt32(prodId), prodName);
                        db.closeDB();
                    }
    
                    JSONArray jSONArray3 = new JSONArray(list3);
                    JSONObject jSONObject3 = null;
    
                    for (int n = 0; n < jSONArray3.Length(); n++)
                    {
                        jSONObject3 = jSONArray3.GetJSONObject(n);
    
                        String catId = jSONObject3.GetString("CatId");
                        String catName = jSONObject3.GetString("CatName");
                        DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.AddProdCat(Convert.ToInt32(catId), catName);
                        db.closeDB();
                    }
                    return 1;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                return 0;
            }
        }
    
Sign In or Register to comment.