I have some trouble with installing a database with Ti.Database.install(). Here's what I'm doing:
Open new default alloy project
Add some code to controllers/index.js so the file looks like this
var db = Ti.Database.install('/testimusDB.sqlite', 'testimusDB');
var rs = db.execute('SELECT * FROM testimusTable');
db.close();
while (rs.isValidRow())
{
var name = rs.fieldByName('name');
var age = rs.fieldByName('age');
alert(name + ' is ' + age + 'years old');
rs.next();
}
rs.close();
$.index.open();
create a DB with FF Plugin SQLite Manager called testimusDB.sqlite
and copy it to the REsources Folder of the Project
Start the App via Titanium Studio on a Samsung S3
What I get is
Runtime Error: LOCATION: [101,19] ti:/invoker.js
MESSAGE: Uncaught Error: Resources/testimusDB.sqlite SOURCE: return
delegate.apply(invoker._thisObj_,args);
People with the same problem solved it by reducing the size of the DB (mine is 64 KB) or by using absolute path (I tried absolute-/relative- path and sqlite-/db-/sql- suffix). Any ideas how to solve this problem?
Okay I got it: You can't use install() when you're using alloy! (If anybody knows an official source for this information please let me know). You need to use models to sync the database. This guy and this guide helped me a lot.
Thanks for the answers.
Close connection to db at the end of operation:
rs.close();
db.close();
Size of the database doesn't matter. I'm using much bigger one: >10MB.
Related
I am new to Unity and SQLite.
I am doing an Android app, that should work offline. It is the first time I use Unity and SQLite.
I am just trying to connect to my SQLite database file, TrilhoVerde.db. I created it using SQLiteAdministrator. I created a database but is empty. I would create the necessary tables in the C# file (because of the foreign keys). This is the code I have:
private IDbConnection connection;
private IDbCommand command;
private IDataReader reader;
// Start is called before the first frame update
void Start()
{
Connection();
}
private void Connection()
{
string dbFile = "URI=File:"+ Application.dataPath +"/Plugins/TrilhoVerde.db:";
connection = (IDbConnection) new SqliteConnection(dbFile);
connection.Open();
command = connection.CreateCommand();
string createTable = "select * from Avatar;";
command.CommandText = createTable;
reader = command.ExecuteReader();
}
But when I run it in Unity, I got this error:
SqliteSyntaxException: unable to open database file
Mono.Data.SqliteClient.SqliteCommand.GetNextStatement (System.IntPtr pzStart, System.IntPtr& pzTail, System.IntPtr& pStmt) (at <9f65d62b5efa4334801a8fece4acee8a>:0)
Mono.Data.SqliteClient.SqliteCommand.ExecuteReader (System.Data.CommandBehavior behavior, System.Boolean want_results, System.Int32& rows_affected) (at <9f65d62b5efa4334801a8fece4acee8a>:0)
Mono.Data.SqliteClient.SqliteCommand.ExecuteNonQuery () (at <9f65d62b5efa4334801a8fece4acee8a>:0)
carrega.Connection () (at Assets/scipts/carrega.cs:30)
carrega.Start () (at Assets/scipts/carrega.cs:17)
I was using the tutorials in these videos:
https://www.youtube.com/watch?v=QtDtBvAyzOQ
https://www.youtube.com/watch?v=CtDSQkLdlZg
I think I did all the steps. I know that there are a lot of questions related to this matter, but so far none if them solved my problem. If something is missing to understand what I did and what is wrong, please tell me.
Does anyone know what I am doing wrong.
And I'm sorry if this is something really simple, but, like I said, I am new to Unity and SQLite.
UPDATE
I created a new database file using another program and I commented the command part of the code. It now does not threw any error. Reversing that comment, error again.
The problem is in this specific line:
reader = command.ExecuteReader();
I also added the tables in database file, not in C#. Stil don't know what the problem is.
I am really sorry to de ones that lost time on this, and I am embarrassed too. The name of the database file was wrong. I was supposed to TrilhoVerde.db, but I had TrilhoVerde.bd: in the script.
I'm building an app with the Entity Framework on Xamarin that lets me compare some data. But when I start my "fetchdata" function, I receive the Error:
System.Data.SqlClient.SqlException (0x80131904): Snix_Connect (provider: SNI_PN7, error: 35 - SNI_ERROR_35)Snix_Connect (provider: SNI_PN7, error: 35 - SNI_ERROR_35)
I see many posts about Xamarin / Android & that it is not possible to get a connection to a SQL Server. Is there any way to fetch data from a SQL Server with .NET Core on Xamarin?
This is the string I put into SQL_Class folder with Sql_Common.cs
Fill up the brace brackets with actual parameters (removing the brace brakets too).
public static string SQL_connection_string = #"data source={server_address};initial catalog={database_name};user id={user_id};password={password};Connect Timeout={seconds}";
Then I access whenever I need it from any xamarin code just like we use in our asp.net c#
This works for me on my app without any issues.
using (SqlConnection Sql_Connection = new SqlConnection(Sql_Common.saralEHR_connection_string))
But as #Jason mentioned in his first reply, I too would get once again check the security part. I fexperienced before publishing Package to Google Play, they encrypt the App files with Hash Key Code and then only it gets upload to server
Yes it is possible (HuurrAYY!):
Im new in .net core, c# and so on and for me it was a hell of a work to get it working..
So here for the other noobs who are seeking for Help:
GuideĀ“s i used:
Building Android Apps with Entity Framework
https://medium.com/#yostane/data-persistence-in-xamarin-using-entity-framework-core-e3a58bdee9d1
https://blog.xamarin.com/building-android-apps-entity-framework/
Scaffolding
https://cmatskas.com/scaffolding-dbcontext-and-models-with-entityframework-core-2-0-and-the-cli/
How i did it:
Build your normal Xamarin app.
create new .net solution like in the tutorials (DONT WRITE YOUR Entity Framework CLASSES)
create a third solution what has to be a .net core console application
Scaffold your DB in your CONSOLE application move all created classes & folders in your "xamarin .net" solution & change the namespaces
Ready to Go!
Side Node: NuGets you need in every solution:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
[EDIT: NuGets you need in every solution]
I am doing this way (working snippet):
string connectionString = #"data source={server};initial catalog={database};user id={user};password={password};Connect Timeout=10";
string databaseTable = "{table name}";
string selectQuery = String.Format("SELECT count(*) as Orders FROM {0}", databaseTable);
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
//open connection
connection.Open();
SqlCommand command = new SqlCommand(selectQuery, connection);
command.Connection = connection;
command.CommandText = selectQuery;
var result = command.ExecuteScalar().ToString();
//check if there is result
if(result != null)
{
OrdersLabel.Text = result;
}
}
}
catch (Exception ex)
{
OrdersLabel.Text = ex.Message;
}
It is working fine, but API call more elegant.
I hope it helps.
For some reason, when I restart my PhoneGap app - it looses the localStorage vales that were stored before! I'm saving them in the normal way:
localStorage.setItem("foo","value");
This stores it just fine. However, when you restart the app (or leave the device off for a random amount of time), it seems to randomly loose the data. I've found a heck of a lot of posts about this - but no definative answer on how to get it to be persistent in a PhoneGap Build WebView app,
Any suggestions are much welcomed!
This seems to be quite a common problem with WebView apps:
Android 2.3.6 + Phonegap + localStorage
Android - Making Webview DomStorage persistant after app closed
I can't find a solution that works with PhoneGap Build apps though
An actual example I'm using, is:
var current_id = parseInt(currentId) + 1;
localStorage.setItem("entry_"+current_id,save_string);
localStorage.setItem("entryId",current_id);
..and then to extract it (not that this is important, as the problem is with the data going missing, and not with accessing it)
for (var i = 0; i < localStorage.length; i++){
if (localStorage.key(i).match("entry_")) {
outputString += "\n" + localStorage.getItem(localStorage.key(i));
}
}
I'm wondering if maybe upgrading from PhoneGap Build cli-5.2.0 to cli-6.0.0 may help. I will do this, and give it a whirl.
I guess another option, would be to use a SQL database to locally store the device (its just a bit trickier to setup, and means re-writing my code)
UPDATE: Not the ideal solution - but I have now moved the app over to use WebSQL for the app. It was a bit tricky to get the hang of (never used it before) - but seems to do the job, and shouldn't loose the data :)
EDIT
i tried it like this and it worked:
var current_id = parseInt(currentId) + 1;
localStorage.setItem("entry_"+current_id,save_string);
localStorage.setItem("entryId",current_id);
/*
//this is for checking, what is stored in localStorage
console.log("length: " + localStorage.length);
for(var i = 0; i < localStorage.length; i++) {
console.log(localStorage.key(i));
}
*/
var myEntryIdFromStorage = localStorage.getItem("entryId");
var myItem = localStorage.getItem("entry_" + myEntryIdFromStorage);
Old answer for clarification
How do you get your localstorage?
normally you should store items like you did:
var permanentStorage = window.localstorage;
permanentStorage.setItem("foo", "bar");
and get them back by initializing the permanentStorage the same way and:
//assuming you have permanentStorage in the same script file
//or else you have to initialize it again:
//var permanentStorage = window.localstorage;
var myItem = permanentStorage.getItem("foo");
console.log("myItem: " + myItem);
The method store item uses two parameters: the identifier and the data itself. Please check, that the identifier with which you store your data is the same as the one, with which you get it back.
Do you get any errors? Is the return (stored in my example in myItem) null or undefined or just an empty string? Does this fail in the browser or on the device?
You could clarify your question by providing more code or error messages!
cordova 3.0, lite4cordova Cordova-SQLitePlugin, installed all test OK. Working.
Building a new version of a previously released App for iOS and Android, where data.sqlite is the name of the db.
I learned from documentation that .db is the name extension with lite4cordova but need to open and connect with that data.sqlite db.
I try some blind rename data.sqlite to data.db and so on just to see if there is connection, but no luck.
var db = window.sqlitePlugin.openDatabase({name: "data"}); // not OK
var db = window.sqlitePlugin.openDatabase({name: "data.db"}); // not OK
var db = window.sqlitePlugin.openDatabase({name: "/www/data.db"}); // not OK
var db = window.sqlitePlugin.openDatabase({name: "/www/data.sqlite"}); // not OK
xcode console while looking for "food" table
2014-03-04 17:03:40.372 MyAPI2[81436:70b] Good news: SQLite is thread safe!
2014-03-04 17:03:40.373 MyAPI2[81436:70b] DB opened: data
2014-03-04 17:03:40.374 MyAPI2[81436:70b] Error: no such table: food code: 5
is there a way to specify a path to data.sqlite ?
I accidentally deleted my contacts and i don't have a backup for that now i got the contacts2.db and i am trying to covert the .db to .vcf. Now i am using Ruby to convert the file and here is what i did
gem install sqlite3
gem install vpim
path to contacts2-to-vcard.rb/contacts2-to-vcard.rb > contacts.vcf
i always says 'Access Denied.' And i set the folder to full control but whenever i run that command it change to read only, by the way i am using windows 8. Any help? Or is there a alternate why to convert .db to .vcf? TIA
Yank it out of the DB (this is all in Ruby):
require 'sqlite3'
path_to_contactsdb_file = "/SAMPLE/PATH/TO/contacts2.db"
db = SQLite3::Database.new path_to_contactsdb_file
raw_contacts = db.execute("select _id,display_name from raw_contacts")
contacts = {}
raw_contacts.each do |x|
contacts[x[1]] = {}
contacts[x[1]]['rcid'] = x[0]
contacts[x[1]]['nums'] = db.execute("select normalized_number from phone_lookup where raw_contact_id=" + x[0].to_s)
end
Pull it to CSV:
output_filepath = "/SAMPLE/EXAMPLE/FILEPATH"
csv = ""
contacts.each do |k,v|
csv += '"' + k + '",'
v['nums'].each do |num|
csv += '"' + num[0] + '",'
end
csv += "\n"
end
File.open(output_filepath,"w") {|file| file.write(csv) }
Then you can use a CSV import app, do it through Google contacts import through CSV, etc.. You can send me a fruit basket.
If it MUST be in a VCF format, then just change the output syntax of the CSV. Look up a sample VCF file, I couldn't be bothered.
I've been trying to use Dustin van Schouwen's code to do this task. I wanted to thank him for it, first of all, and then mention a few details I needed to add/change to make it work for me:
This line:
db = SQLite3::Database.new path_to_contactsdb_file
I changed to:
db = SQLite3::Database.new ("contacts2.db")
As when using the previous one, even though it doesn't give an error, it doesn't seem to actually connect to the database (I think it creates an empty one).
The other change I needed to do was at this other line:
csv += '"' + k + '",
If "k" is nil, the code will fail, so I introduced an if (ternary syntax) to solve it, and it worked fine:
csv += '"' + (k == nil ? "" : k) + '",'
A bit late for OP sorry. I can't give tips on ruby anyway.
But I stumbled here when searching a solution for my own needs.
I finally came up with a python solution:
https://gitlab.com/Arnaudv6/contacts2.db-2-vcard
based on previous works documented on above page.
Please refer to "todo" section at beginning of the script
for details on what is not implemented to date.