Android Xamarin SQLite

public class Person
{
     [PrimaryKey, AutoIncrement]
     public int ID { get; set; }

     public string FirstName { get; set; }

     public string LastName { get; set; }

     public override string ToString()
     {
        return string.Format("[Person: ID={0}, FirstName={1}, LastName={2}]", ID, FirstName, LastName);
     }
}
string dbPath = Path.Combine (
        Environment.GetFolderPath (Environment.SpecialFolder.Personal),
        "database.db3");
using SQLite;
var db = new SQLiteConnection (dbPath);
db.CreateTable<Stock> ();
db.Insert (newStock); // after creating the newStock object
var stock = db.Get<Stock>(5); // primary key id of 5
var stockList = db.Table<Stock>();

References :
https://developer.xamarin.com/recipes/android/data/databases/sqlite/
https://developer.xamarin.com/guides/cross-platform/application_fundamentals/data/part_2_configuration/
https://developer.xamarin.com/guides/cross-platform/application_fundamentals/data/part_3_using_sqlite_orm/

Android Menus

Defining a Menu in XML

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"
          android:icon="@drawable/ic_new_game"
          android:title="@string/new_game"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/help"
          android:icon="@drawable/ic_help"
          android:title="@string/help" />
</menu>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/file"
          android:title="@string/file" >
        <!-- "file" submenu -->
        <menu>
            <item android:id="@+id/create_new"
                  android:title="@string/create_new" />
            <item android:id="@+id/open"
                  android:title="@string/open" />
        </menu>
    </item>
</menu>

Creating an Options Menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

Handling click events

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.new_game:
            newGame();
            return true;
        case R.id.help:
            showHelp();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Changing menu items at runtime

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method.

References :
https://developer.android.com/guide/topics/ui/menus.html#options-menu
https://developer.android.com/guide/topics/resources/menu-resource.html
http://stackoverflow.com/questions/15492791/how-do-i-show-overflow-menu-items-to-action-bar-in-android
http://www.techotopia.com/index.php/Creating_and_Managing_Overflow_Menus_on_Android

Change the android actionbar title and icon

This is very simple to accomplish

If you want to change it in code, call:

setTitle("My new title");
getActionBar().setIcon(R.drawable.my_icon);

And set the values to whatever you please.

Or, in the Android manifest XML file:

<activity android:name=".MyActivity" 
       android:icon="@drawable/my_icon" 
       android:label="My new title" />

To enable the back button in your app use:

 getActionBar().setHomeButtonEnabled(true);
 getActionBar().setDisplayHomeAsUpEnabled(true);

The code should all be placed in your onCreate so that the label/icon changing is transparent to the user, but in reality it can be called anywhere during the activity’s lifecycle.

References :
http://stackoverflow.com/questions/14483393/how-do-i-change-the-android-actionbar-title-and-icon

ActionBar with Custom View Example in Android

custom_actionbar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@drawable/black_pattern" >

    <TextView
        android:id="@+id/title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textAllCaps="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#fff"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="8dp"
        android:src="@drawable/ic_launcher" />

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="8dp"
        android:background="@null"
        android:src="@android:drawable/ic_menu_rotate" />

</RelativeLayout>

Activity Class (MainActivity.java)

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayShowHomeEnabled(false);
		mActionBar.setDisplayShowTitleEnabled(false);
		LayoutInflater mInflater = LayoutInflater.from(this);

		View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
		TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);
		mTitleTextView.setText("My Own Title");

		ImageButton imageButton = (ImageButton) mCustomView
				.findViewById(R.id.imageButton);
		imageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				Toast.makeText(getApplicationContext(), "Refresh Clicked!",
						Toast.LENGTH_LONG).show();
			}
		});

		mActionBar.setCustomView(mCustomView);
		mActionBar.setDisplayShowCustomEnabled(true);
	}

}

References :
http://stacktips.com/tutorials/android/actionbar-with-custom-view-example-in-android

Show a Dialog using DialogFragment in Xamarin Android

Let us first define the layout for your fragment. In this example, I have used two TextViews and Button. My layout looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">
    <TextView
        android:text="Lorem ipsum"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit...."
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:layout_marginTop="10dp" />
    <Button
        android:text="Close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/CloseButton"
        android:layout_marginTop="10dp" />
</LinearLayout>

Now let us inflate the layout from OnCreateView() method. My DialogFragment class looks as follows:

public class DialogFragment1 : DialogFragment
	{
		public static DialogFragment1 NewInstance(Bundle bundle){
			DialogFragment1 fragment = new DialogFragment1 ();
			fragment.Arguments = bundle;
			return fragment;
		}

		public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			// Use this to return your custom view for this Fragment
			View view =  inflater.Inflate(Resource.Layout.DialogFragment1Layout, container, false);
			Button button = view.FindViewById<Button> (Resource.Id.CloseButton);
			button.Click += delegate {
				Dismiss();
				Toast.MakeText(Activity ,"Dialog fragment dismissed!" , ToastLength.Short).Show();
			};

			return view;
		}
	}

We are pretty much done!. Add the following code snippet in your Activity to instantiate and display the dialog:

FragmentTransaction ft = FragmentManager.BeginTransaction();
//Remove fragment else it will crash as it is already added to backstack
Fragment prev = FragmentManager.FindFragmentByTag("dialog");
if (prev != null) {
	ft.Remove(prev);
}

ft.AddToBackStack(null);

// Create and show the dialog.
DialogFragment1 newFragment = DialogFragment1.NewInstance(null);

//Add fragment
newFragment.Show(ft, "dialog");

References :
http://javatechig.com/xamarin/alertdialog-and-dialogfragment-example-in-xamarin-android

Show a Dialog using AlertDialog in Xamarin Android

//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder (this);
alert.SetTitle ("Confirm delete");
alert.SetMessage ("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.");
alert.SetPositiveButton ("Delete", (senderAlert, args) => {
	Toast.MakeText(this ,"Deleted!" , ToastLength.Short).Show();
});

alert.SetNegativeButton ("Cancel", (senderAlert, args) => {
	Toast.MakeText(this ,"Cancelled!" , ToastLength.Short).Show();
});

Dialog dialog = alert.Create();
dialog.Show();

References :
http://javatechig.com/xamarin/alertdialog-and-dialogfragment-example-in-xamarin-android

Communicate over TCP Socket and Serialize data with json format in C#

Client :

Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            socket.Connect("127.0.0.1",9011);

            Console.WriteLine("connected...");

            Person person=new Person(){Name = "Mahmood"};

            string jsonData = JsonConvert.SerializeObject(person);
            byte[] dataBytes = Encoding.Default.GetBytes(jsonData);

            socket.Send(dataBytes);

            Console.WriteLine("sent...");

            byte[] buffer=new byte[1024*4];
            int readBytes = socket.Receive(buffer);
            MemoryStream memoryStream = new MemoryStream();

            while (readBytes>0)
            {
                memoryStream.Write(buffer, 0, readBytes);

                if (socket.Available > 0)
                {
                    readBytes = socket.Receive(buffer);   
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine("read...");

            byte[] totalBytes = memoryStream.ToArray();

            memoryStream.Close();

            string readData = Encoding.Default.GetString(totalBytes);

            Greeting response = JsonConvert.DeserializeObject<Greeting>(readData);

            Console.WriteLine(response.Msg);

            Console.ReadKey();

Server :

            Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint=new IPEndPoint(IPAddress.Any, 9011);

            socket.Bind(endPoint);
            socket.Listen(5);

            while (true)
            {
                Console.WriteLine("waiting for new connection...");

                Socket newSocket = socket.Accept();

                MemoryStream memoryStream = new MemoryStream();

                Console.WriteLine("new connection...");

                byte[] buffer=new byte[1024];

                int readBytes = newSocket.Receive(buffer);

                while (readBytes>0)
                {
                    memoryStream.Write(buffer,0,readBytes);

                    if (socket.Available > 0)
                    {
                        readBytes = newSocket.Receive(buffer);    
                    }
                    else
                    {
                        break;
                    }
                }

                Console.WriteLine("data received...");

                byte[] totalBytes = memoryStream.ToArray();

                memoryStream.Close();

                string readData = Encoding.Default.GetString(totalBytes);

                Person p= JsonConvert.DeserializeObject<Person>(readData);

                Greeting g = SayHello(p);

                string dataToSend = JsonConvert.SerializeObject(g);

                byte[] dataToSendBytes = Encoding.Default.GetBytes(dataToSend);

                newSocket.Send(dataToSendBytes);

                newSocket.Close();

                Console.WriteLine("data sent...");
            }

Communicate over TCP Socket and Serialize data with binary format in C#

Client :

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect("127.0.0.1", 9011);

            Console.WriteLine("connected...");

            BinaryFormatter formatter=new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();
            Person person = new Person() { Name = "Mahmood" };

            formatter.Serialize(memoryStream,person);

            byte[] dataBytes = memoryStream.ToArray();
            socket.Send(dataBytes);

            Console.WriteLine("sent...");

            memoryStream = new MemoryStream();
            byte[] buffer = new byte[1024 * 4];
            int readBytes = socket.Receive(buffer);
            
            while (readBytes > 0)
            {
                memoryStream.Write(buffer, 0, readBytes);

                if (socket.Available>0)
                {
                    readBytes = socket.Receive(buffer);
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine("read...");
            formatter=new BinaryFormatter();

            // set position to 0 or create a new stream
            memoryStream.Position = 0;
            Greeting response = (Greeting) formatter.Deserialize(memoryStream);

            Console.WriteLine(response.Msg);

            memoryStream.Close();
            socket.Close();

            Console.ReadKey();

Server :

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, 9011);

            socket.Bind(endPoint);
            socket.Listen(5);

            while (true)
            {
                Console.WriteLine("waiting for new connection...");

                Socket newSocket = socket.Accept();

                Console.WriteLine("new connection...");

                byte[] buffer = new byte[1024];

                int readBytes = newSocket.Receive(buffer);
                MemoryStream memoryStream = new MemoryStream();

                while (readBytes > 0)
                {
                    memoryStream.Write(buffer, 0, readBytes);

                    if (socket.Available>0)
                    {
                        readBytes = newSocket.Receive(buffer);
                    }
                    else
                    {
                        break;
                    }
                }

                Console.WriteLine("data received...");

                BinaryFormatter formatter=new BinaryFormatter();
                memoryStream.Position = 0;
                Person p = (Person) formatter.Deserialize(memoryStream);

                memoryStream.Close();

                Greeting g = SayHello(p);

                formatter=new BinaryFormatter();
                memoryStream=new MemoryStream();

                formatter.Serialize(memoryStream,g);

                newSocket.Send(memoryStream.ToArray());

                memoryStream.Close();
                newSocket.Close();

                Console.WriteLine("data sent...");

Android Exception : Only the original thread that created a view hierarchy can touch its views

 private void startingUp() {
    Thread timer = new Thread() { //new thread         
        public void run() {
            Boolean b = true;
            try {
                do {
                    counter++;
                    title();
                    sleep(1000);

                    runOnUiThread(new Runnable() {  
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                        title.clearComposingText();
                    }
                });


                }
                while (b == true);
            } catch (IntruptedException e) {
                e.printStackTrace();
            }
            finally {
            }
        };
    };
    timer.start();
}

References :
http://stackoverflow.com/questions/14978052/only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-views-on-a