mercredi 27 mai 2015

How to set data from Sqlite to a TextView in C#?

I want to assign the already give value in database to a contact form which I created. In the starting I used a registration form to store the data in database now from that table I need to take two values name and email and give it in the Texview of the Contact form here are the codes used.

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 Android.Database.Sqlite;
using System.IO;

namespace Application
{
    class Database
    {
    //SQLiteDatabase object for database handling
    private SQLiteDatabase sqldb;
    //String for Query handling
    private string sqldb_query;
    //String for Message handling
    private string sqldb_message;
    //Bool to check for database availability
    private bool sqldb_available;
    //Zero argument constructor, initializes a new instance of Database class
    public Database()
    {
        sqldb_message = "";
        sqldb_available = false;
    }
    //One argument constructor, initializes a new instance of Database class with database name parameter
    public Database(string sqldb_name)
    {
        try
        {
            sqldb_message = "";
            sqldb_available = false;
            CreateDatabase(sqldb_name);
        }
        catch (SQLiteException ex) 
        {
            sqldb_message = ex.Message;
        }
    }
    //Gets or sets value depending on database availability
    public bool DatabaseAvailable
    {
        get{ return sqldb_available; }
        set{ sqldb_available = value; }
    }
    //Gets or sets the value for message handling
    public string Message
    {
        get{ return sqldb_message; }
        set{ sqldb_message = value; }
    }
    //Creates a new database which name is given by the parameter
    public void CreateDatabase(string sqldb_name)
    {
        try
        {
            sqldb_message = "";
            string sqldb_location = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string sqldb_path = Path.Combine(sqldb_location, sqldb_name);
            bool sqldb_exists = File.Exists(sqldb_path);
            if(!sqldb_exists)
            {

                sqldb = SQLiteDatabase.OpenOrCreateDatabase(sqldb_path,null);
                sqldb_query = "CREATE TABLE IF NOT EXISTS MyTable (_id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, Email VARCHAR, Age INT, City VARCHAR);";

                sqldb.ExecSQL(sqldb_query);
                sqldb_message = "Database: " + sqldb_name + " created";
            }
            else
            {
                sqldb = SQLiteDatabase.OpenDatabase(sqldb_path, null, DatabaseOpenFlags.OpenReadwrite);
                sqldb_message = "Database: " + sqldb_name + " opened";
            }
            sqldb_available=true;
        }
        catch(SQLiteException ex) 
        {
            sqldb_message = ex.Message;
        }


    }

    public void AddRecord(string sName, string sEmail, int iAge, string sCity)
    {
        try
        {

            sqldb_query = "INSERT INTO MyTable (Name, Email, Age, City) VALUES ('" + sName + "','" + sEmail + "','" + iAge + "','" + sCity + "');";

            sqldb.ExecSQL(sqldb_query);
            sqldb_message = "Record saved";
        }
        catch(SQLiteException ex) 
        {
            sqldb_message = ex.Message;
        }
     }
    }
}

This is the Database Class and below is Registration page,

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 System.Text.RegularExpressions;

namespace Application
{
    [Activity (Label = "Registration", Theme = "@android:style/Theme.DeviceDefault.Light.NoActionBar")]         
public class Registration : Activity
{
    bool IsValidEmail(string email)
    {
        try {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch {
            return false;
        }
    }

    Database sqldb;
    EditText txtName, txtAge, txtEmail, txtCity;

    Button imgAdd;
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        SetContentView (Resource.Layout.Registration);

        //Gets ImageButton object instances
        imgAdd = FindViewById<Button> (Resource.Id.imgAdd);

        //Gets EditText object instances
        txtAge = FindViewById<EditText> (Resource.Id.txtAge);
        txtEmail = FindViewById<EditText> (Resource.Id.txtEmail);
        txtName = FindViewById<EditText> (Resource.Id.txtName);
        txtCity = FindViewById<EditText> (Resource.Id.txtCity);

        imgAdd.Click += delegate {
            string pattern = null;
            pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";

            if (txtName.Text == "" || txtEmail.Text == "" || txtAge.Text == "" || txtCity.Text == "") {
                Toast toast1 = Toast.MakeText(this, "Fill Up All Fields", ToastLength.Long);
                toast1.Show();
            }

            else if (Regex.IsMatch(txtEmail.Text, pattern))
            {
                Toast toast = Toast.MakeText(this, "Registration Sucessful", ToastLength.Long);
                toast.Show();

                sqldb = new Database("details_db");

                sqldb.AddRecord (txtName.Text, txtEmail.Text, int.Parse (txtAge.Text), txtCity.Text);

                txtName.Text = txtAge.Text = txtEmail.Text = txtCity.Text = "";

                StartActivity(typeof(MainActivity));
                Finish();
            }
            else 
            {
                Toast toast4 = Toast.MakeText(this, "Enter Proper Information", ToastLength.Long);
                toast4.Show();
            }

        };
    }
}
}

The Name and Email Field should be displayed here,

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 System.Net.Mail;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Net;
using Android.Net;
using System.IO;

namespace Application
{
[Activity (Label = "CotactForm")]           
public class CotactForm : Activity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.ContactForm);
        const string sqldb_name = "details_db";

        EditText name = FindViewById<EditText> (Resource.Id.name);
        EditText email = FindViewById<EditText> (Resource.Id.email);
        EditText editText1 = FindViewById<EditText> (Resource.Id.edittext1);
        EditText editText2 = FindViewById<EditText> (Resource.Id.edittext2);
        Button button = FindViewById<Button> (Resource.Id.myButton);

        string sqldb_location = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        string sqldb_path = Path.Combine(sqldb_location, sqldb_name);
        bool sqldb_exists = File.Exists(sqldb_path);
        if (sqldb_exists) {

            string[] from = new string[] {"Name","Email"};
            int[] to = new int[] {

                Resource.Id.name,
                Resource.Id.email,
            };
        }





        button.Click +=delegate(object sender, EventArgs e) {

            var connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
            var activeConnection = connectivityManager.ActiveNetworkInfo;
            if ((activeConnection != null)  && activeConnection.IsConnected)
            {
                try
                {
                    MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                    mail.From = new MailAddress("user0@gmail.com");
                    mail.To.Add("user1@gmail");
                    mail.Subject = "User Query:\t" + editText1.Text;
                    mail.Body = "Name:\t" + name.Text + "\r\nEmail:\t" + email.Text + "\r\nQuestion:\t" + editText1.Text + "\r\nDescription of the Question:\t" + editText2.Text;

                    SmtpServer.Port = 587;
                    SmtpServer.Credentials = new System.Net.NetworkCredential("user@gmail.com", "pass");
                    SmtpServer.EnableSsl = true;

                    SmtpServer.Send(mail);
                }
                catch (Exception ex)
                {
                    Toast toast = Toast.MakeText(this, "Sending Mail Failed", ToastLength.Short);
                    toast.Show();
                }
            }
            else
            {
                Toast toast = Toast.MakeText(this, "No Internet Connection", ToastLength.Short);
                toast.Show();
            }
        };
    }
}

}

Aucun commentaire:

Enregistrer un commentaire