Tag Archives: xamarin

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/

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

Xamarin.Android Intellisense not working in Visual Studio

You can get those files from the above links, Just download it and those files move it manually to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Xml\Schemas or simply just add these schemas within Visual Studio.

https://github.com/atsushieno/monodroid-schema-gen/blob/master/android-layout-xml.xsd
https://github.com/atsushieno/monodroid-schema-gen/blob/master/schemas.android.com.apk.res.android.xsd

References :

http://stackoverflow.com/questions/17245308/xamarin-android-intellisense-not-working-in-visual-studio-2010
https://forums.xamarin.com/discussion/60962/enable-intellisense-for-axml-missing-android-layout-xml-xsd-schemas-android-com-apk-res-androiod