Use putExtra() and getExtra() for exchanging data between intents in Android Xamarin

Put Extra

Intent updateIntent = new Intent(this, typeof(UpdateActivity));
updateIntent.PutExtra("Version", update.LatestVersion);
updateIntent.PutExtra("Url", update.Url);
updateIntent.PutExtra("Length", length);
StartActivity(updateIntent);

GetExtra

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

			SetContentView(Resource.Layout.Update);


		    if (Intent.Extras != null)
		    {
                var version = Intent.Extras.GetString("Version");
                var url = Intent.Extras.GetString("Url");
                var length = Intent.Extras.GetLong("Length");
            }

		}

DownloadManager in Xamarin Android

Download Manager is a System Service that optimises the handling of long-running downloads in the background.

var download =(DownloadManager) GetSystemService(Context.DownloadService);
Android.Net.Uri uri=Android.Net.Uri.Parse(update.Url);
DownloadManager.Request request=new DownloadManager.Request(uri);
var fileName = System.IO.Path.GetFileName(update.Url);
request.SetTitle("Fan Coil").SetDescription(fileName);
request.SetVisibleInDownloadsUi(true);
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
download.Enqueue(request);
//request.SetAllowedNetworkTypes(DownloadNetwork.Mobile | DownloadNetwork.Wifi);

References :
http://101apps.co.za/articles/using-the-downloadmanager-to-manage-your-downloads.html
http://stackoverflow.com/questions/13349806/why-does-the-download-completed-notification-disappear-on-gingerbread-devices

Embed SQLite database file as Asset in Xamarin Android

At a glance:

1 – Add Sqlite.cs to your project.
2 – Add your database file as an Asset.
3 – Set your database file to build as an AndroidAsset.
4 – Manually copy the database file out of your apk to another directory.
5 – Open a database connetion using Sqlite.SqliteConnection.
6 – Operate on the database using Sqlite.

1. Add Sqlite.cs to your project.

2. Add DB as asset.
sqlite01

3. Set DB to build as AndroidAsset.
sqlite02

4. Manually copy DB out of your APK.

string dbName = "db.sqlite";
string dbPath = Path.Combine (Android.OS.Environment.ExternalStorageDirectory.ToString (), dbName);
// Check if your DB has already been extracted.
if (!File.Exists(dbPath))
{
    using (BinaryReader br = new BinaryReader(Assets.Open(dbName)))
    {
        using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
        {
            byte[] buffer = new byte[2048];
            int len = 0;
            while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
            {
                bw.Write (buffer, 0, len);
            }
        }
    }
}

5. Open DB Connection.

using (var conn = new SQLite.SQLiteConnection(dbPath))
{
        // Do stuff here...
}

6. Operate on DB.

References :
http://stackoverflow.com/questions/18715613/use-a-local-database-in-xamarin

Create a Database with ADO.NET in Xamarin Android

First we need WriteExternalStorage Permission

Add a reference to System.Data and to Mono.Data.SQLite

// with Android.Graphics & Android.Environment
var docsFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var pathToDatabase = System.IO.Path.Combine(docsFolder, "db_adonet.db");
SqliteConnection.CreateFile(pathToDatabase);

// without Android.Graphics & Android.Environment
using System.IO;

var docsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var pathToDatabase = Path.Combine(docsFolder, "db_adonet.db");
SqliteConnection.CreateFile(pathToDatabase);
// with try / catch
try
{
    var docsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var pathToDatabase = Path.Combine(docsFolder, "db_adonet.db");
    SqliteConnection.CreateFile(pathToDatabase);
}
catch (IOException ex)
{
    var reason = string.Format("The database failed to create - reason {0}", ex.Message);
    Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}

// using File.Exists
if (!File.Exists(pathToDatabase))
{
    var reason = string.Format("The database failed to create - reason {0}", ex.Message);
    Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
// create a connection string for the database
var connectionString = string.Format("Data Source={0};Version=3;", pathToDatabase);
            try
{
    using (var conn = new SqliteConnection((connectionString)))
    {
        await conn.OpenAsync();
        using (var command = conn.CreateCommand())
        {
            command.CommandText = "CREATE TABLE People (PersonID INTEGER PRIMARY KEY AUTOINCREMENT, FirstName ntext, LastName ntext)";
            command.CommandType = CommandType.Text;
            await command.ExecuteNonQueryAsync();
        }
    }
}
catch (Exception ex)
{
    var reason = string.Format("Failed to insert into the database - reason = {0}", ex.Message);
    Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}

References :
https://developer.xamarin.com/recipes/android/data/databases/adonet/

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