Home > front end >  Can I create a cross-platform app with Xamarin using a MySQL database?
Can I create a cross-platform app with Xamarin using a MySQL database?

Time:03-27

I need to create an online store type app for iOS and android. I want to use MySQL for the database and I think Xamarin is the best option to develop the app. Is this possible? Can I connect to a MySQL database using Xamarin?

I've only ever made apps with Android Studio (Java) and Firebase databases, so I'm still new and learning.

I would appreciate any tips or advice, too! Thanks!

CodePudding user response:

Thanks to the Xamarin.MySQL.Data plugin we can make a connection to a MySQL database from our Xamarin.Android application.

Important: Before we start, remember that as any application can be decompiled and hackers can get the data from your connection, take your precautions or use it at your own risk.

1. Download and install the Xamarin.MySQL.Data plugin.

To do this we go to the NuGet package manager, which is located in Tools -> NuGet Package Manager and Manage NuGet packages for the solution...

enter image description here

enter image description here

In the window that opens, we change to Browse, there we will look for 'Xamarin.MySQL.Data' and we install it in our project (We accept the license).

enter image description here

Now if we check in the dependencies of our project, we will see that the .dll is already there.

enter image description here

2. Make the connection to the MySQL database.

For this example I am going to create a method called TryConnection that receives the username and password of the database user that will allow me to establish a connection to my database.

using System;
using Android.Content;
using Android.Widget;
using MySql.Data.MySqlClient;
 
namespace MySQL_Xamarin
{
 public class Conexion
 {
 /// <summary>
 /// Prueba la conexión a la base de datos utilizando las credenciales correspondientes
 /// </summary>
 /// <param name="context"></param>
 /// <param name="Usuario"></param>
 /// <param name="Contrasenia"></param>
 /// <returns></returns>
 public bool TryConnection(Context context, string Usuario,string Contrasenia)
 {
 MySqlConnectionStringBuilder Builder = new MySqlConnectionStringBuilder();
 Builder.Port = 3306;
                        //Al ser una BD Online debes usar la ip de tu servidor y no localhost
 Builder.Server = "tu.servidor.mysql"; 
 Builder.Database = "tu_base_de_datos";
 Builder.UserID = Usuario; //Es el usuario de la base de datos
 Builder.Password = Contrasenia; //La contraseña del usuario
 try
 {
 MySqlConnection ms = new MySqlConnection(Builder.ToString());
 ms.Open(); //Debes agregar la referencia System.Data
 return true;
 }
 catch (Exception ex)
 {
 Toast.MakeText(context,ex.ToString(), ToastLength.Long).Show(); //Muestra un Toast con el error (Puede ser muy largo)
 return false;
 }
 }
 }
}

Remember that you cannot use 'localhost' as server unless you configure your PC to be a MySQL server, in my case I will use the scrapywar.com server.

3. Check the database connection

For that I have this layout that admits a user and a password that are the credentials to make the connection to the database.

In the MainActivity we are going to assign the elements of the Layout to objects of the same type and we are going to give an action to the button, the result is the following one.

//Declaración de los componentes.
Button access;
EditText User, Password;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
 //Se asignan los controles del Layout a una varaible del mismo tipo
 access = FindViewById<Button>(Resource.Id.btn_entrar);
 User = FindViewById<EditText>(Resource.Id.et_user);
 Password = FindViewById<EditText>(Resource.Id.et_password);
 
 //La accion de presionar el boton
 access.Click  = delegate {
 //Se crea una instancia de la clase Conexion
 Conexion con = new Conexion();
 //Se prueba la conexion pasando los datos de los EditText que son usuario y contraseña
 if (con.TryConnection(this,User.Text,Password.Text)){
 Toast.MakeText(this, "Conexion Exitosa!", ToastLength.Long).Show();
 }
 else{
 Toast.MakeText(this, "Error!", ToastLength.Long).Show();
 }
 };
 }

4. Implement in a simulator or device

If you have the official Android emulator or any other you can directly implement the application, if you want to generate an APK visit my post: 'How to generate an apk in Xamarin.Android'.

I implemented it on my device and as we can see when entering the correct username and password I get a 'successful connection' message otherwise it will give error.

URL : https://scrapywar.com/conectar-aplicacion-xamarin-android-a-bd-mysql-online/

Note : The page is in Spanish because it is my native language but I have translated it.

CodePudding user response:

Yes, you can make app by Xamarin and connect the MySQL database

  • Related