Changes

Jump to: navigation, search

MAP524/DPS924 Lecture 6

1,160 bytes added, 15:56, 4 August 2015
Using a pre-built DB file
Often the easiest way to create an empty database, insert test data, and test your app's usage of SQLite is the command-line tool sqlite3. On Linux it should be installed by default, on other platforms you can download and install it yourself.
<presource lang="bash"># Create the databasesqlite3 employee.db</source> <source lang="sql">
-- Now you're inside the sqlite shell, not bash. Press Ctrl+D on an empty line to quit.
-- Create a table:
.databases
-- Quit
.quit</presource>
== Test data ==
** filename is names.txt
* Open database
<presource lang="bash">sqlite3 employee.db</presource>
* Set your deliminator
<presource lang="sql">.separator ","</presource>
* Import your data
<presource lang="sql">.import names.txt names</presource>
* Display your data
<presource lang="sql">select * from names;</presource>
* Quit
<presource lang="sql">.quit</presource>
== Using a pre-built DB file ==
If you want your app to come with some pre-built data in the database then it's probably easiest to follow the example above to create the file, add it to your resources, and copy it into the correct place the first time your app starts. For example:
<presource lang="java">try
{
String destPath = "/data/data/" + context.getPackageName() + "/databases/";
catch (IOException e) { e.printStackTrace(); }
dbOpenHelper = new DatabaseOpenHelper(context); /** * This function comes from the database example in the book. I've no idea * why it's necessary, does Android really not have a function that does this? */public void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException{ byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) outputStream.write(buffer, 0, length); inputStream.close(); outputStream.close();}</presource>
Make sure this code runs when your app starts up and don't forget to put your db file in the assets folder.
</source>
<ol start="8"><li>You should now be able to run your DB app.</li></ol>
 
== Questoid SQLite Browser ==
 
You can download the [https://github.com/TKlerx/android-sqlite-browser-for-eclipse/releases Questoid SQLite Browser] plugin for Android Device Monitor to be able to view your SQLite database directly from the device.
 
Copy the file to your [YourAndroidSdkDirectory]/tools/lib/monitor-x86_64/plugins/AndroidSQLiteBrowser_1.0.1.jar directory and restart the Android Device Monitor.
 
Then you can find your database file and click the "Open File in SQLite browser" button:
 
[[Image:QuestoidSQLitemanager.png|600px| ]]

Navigation menu