0
votes

I am making an android application using xamarin and sqlite. I am trying to connect table user of database testdb.sqlite on button add but on debugging the application on my tablet I am getting this error:

SQLite.SQLiteException: Could not open database file: /storage/emulated/0/testdb.sqlite/testdb.sqlite (CannotOpen)

My code is:

button_add.Click += delegate
{
    ring dbName = "testdb.sqlite";

    ///  Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    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);
                }
            }
        }
    }

    editemail.Text = "I love coding"; 
    // db.createdatabase();

    //folder_loc.Text = folder;
    using (var connection = new SQLiteConnection(System.IO.Path.Combine(dbPath, dbName)))
    {
        //  connection.CreateTable<person>();

        //string query = "select * from test";
        // connection.Query <test> (query);


        var query = connection.Table<user>();

        foreach (var stock in query)
        {
            Console.WriteLine("Stock: " + stock.name);
            editname.Text = stock.name;
        }
    }
};

user declaration:

public class user
{
    public int id { get; set; }

    //public string email { get; set; }

    public string name { get; set; }

    //public string gender { get; set; }
}
1

1 Answers

2
votes

Well, you defined the name twice in your code, once here:

string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName);

and then when you want to open it, you use dbPath and dbName, either delete dbName reference in:

    string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName);

or in:

(var connection = new SQLiteConnection(System.IO.Path.Combine(dbPath, dbName)))

and it should work ;)