.sql file in eclipse, show it as a table? - java

In my app I want a small database (.sql), with data about energy (kCal) in food.
The problem is, I have a bit expertise with SQL, but I don't really get my database into my app. Do I have to make a new .java file? Or I've read somewhere else, in my assets? I think the database isn't on a server, just within the app. The project I already have, is an about about food, overweight and BMI. Now I want to add a database about the amount of kCal in food.
I do not really know what I have to say more here. Hopefully you understand what I'm trying to do. I've read ALL related questions here on Stackoverflow, but still didn't got an answer.
If you can help me, you would be my hero! :)
Thank you all in advance,
Jacob

Android's built-in on-device DBMS is not mysql, but SQLite. You can find an excellent tutorial on setting it up and integrating it into your app here.

Create the SQLite database file with whatever data you want in it on your PC. Then create an assets folder in your project root in Eclipse (same level as src/, bin/, libs/, res/, etc.). Put your SQLite file in there. Then write some code to copy that asset file into the correct location on the device. Following is the code I currently use for that. I wrote it a while back when I was a beginner so there is probably a better way, but this works.
try {
InputStream is = getActivity().getApplicationContext().getAssets().open("sourceDatabaseFile.db");
OutputStream os = new FileOutputStream(getActivity().getApplicationContext().getDatabasePath("destinationDatabaseFile.db"));
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
Another way would be to create the database using some Android code, and then have a (giant) class containing all the SQL statements to insert the data into the database.

Related

Delete file after staring connection using FileInputStream

I have a temporary file which I want to send the client from the controller in the Play Framework. Can I delete the file after opening a connection using FileInputStream? For example can I do something like this -
File file = getFile();
InputStream is = new FileInputStream(file);
file.delete();
renderBinary(is, "name.txt");
What if file is a large file? If I delete the file, will subsequent reads() on InputStream give an error? I have tried with files of around 1MB I don't get an error.
Sorry if this is a very naive question, but I could not find anything related to this and I am pretty new to Java
I just encountered this exact same scenario in some code I was asked to work on. The programmer was creating a temp file, getting an input stream on it, deleting the temp file and then calling renderBinary. It seems to work fine even for very large files, even into the gigabytes.
I was surprised by this and am still looking for some documentation that indicates why this works.
UPDATE: We did finally encounter a file that caused this thing to bomb. I think it was over 3 Gb. At that point, it became necessary to NOT delete the file while the rendering was in process. I actually ended up using the Amazon Queue service to queue up messages for these files. The messages are then retrieved by a scheduled deletion job. Works out nicely, even with clustered servers on a load balancer.
It seems counter-intuitive that the FileInputStream can still read after the file is removed.
DiskLruCache, a popular library in the Android world originating from the libcore of the Android platform, even relies on this "feature", as follows:
// Open all streams eagerly to guarantee that we see a single published
// snapshot. If we opened streams lazily then the streams could come
// from different edits.
InputStream[] ins = new InputStream[valueCount];
try {
for (int i = 0; i < valueCount; i++) {
ins[i] = new FileInputStream(entry.getCleanFile(i));
}
} catch (FileNotFoundException e) {
....
As #EJP pointed out in his comment on a similar question, "That's how Unix and Linux behave. Deleting a file is really deleting its name from the directory: the inode and the data persist while any processes have it open."
But I don't think it is a good idea to rely on it.

Creating a .txt file from scratch

I'm working on a microcontroller and I'm trying to write some data from some sensors into a .txt file on the SDcard and later on place the sd card in a card reader and read the data on the PC.
Does anyone know how to write a .txt file from scratch for a FAT32 file system? I don't have any predefined code/methods/functions to call, I'll need to create the code from nothin.
It's not a question for a specific programming language, that is why I tagged more than one. I can later on convert the code from C or Java to my programming language of choice. But I can't seem to find such low level methods/functions in any type of language :)
Any ideas?
FatFs is quite good, and highly portable. It has support for FAT12, FAT16 and FAT32, long filenames, seeking, reading and writing (most of these things can be switched on and off to change the memory footprint).
If you're really tight on memory there's also Petit FatFs, but it doesn't have write support by default and adding it would take some work.
After mounting the drive you'd simply open a file to create it. For example:
FATFS fatFs;
FIL newFile;
// The drive number may differ
if (f_mount(0, &fatFs) != FR_OK) {
// Something went wrong
}
if (f_open(&newFile, "/test.txt", FA_WRITE | FA_OPEN_ALWAYS) != FR_OK) {
// Something went wrong
}
If you really need to create the file using only your own code you'll have to traverse the FAT, looking for empty space and then creating new LFN entries (where you store the filename) and DIRENTs (which specify the clusters on the disk that will hold the file data).I can't see any reason for doing this except if this is some kind of homework / lab exercise. In any case you should do some reading about the FAT structure first and return with some more specific questions once you've got started.
In JAVA you can do like this
Writer output = null;
String text = "This is test message";
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written");

Creating and reading a one time created file

I want to store a list of strings in a file.
I need to create it just one time, and after that i will read and write on it programmaticlly.
My question is where in the file system should i create the file (manually) so that it will best for reading and writing ?
Thanks.
You can create your file in your app's directory so no one can access it but your app
getApplicationContext().getFilesDir().getAbsolutePath();
or on sd card
File externalStorage = Environment.getExternalStorageDirectory();
if you want others to access it and, maybe, if your file is very big
If you intent to create your file manually then I think SD card is the only option unless you have a rooted phone or working with the emulator.
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
//SDcard is there
File f=new File("/sdcard/YOURFILE.txt");
if (!f.exists())
{
//File created only for first time
f.createNewFile();
//create inputstream and write it to your file
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
System.out.println("\nData Written");
}
else { // read/ write SECOND TIME }
}
It really depends.
The problem with creating the file on the SDCard is that a special permission is required in order to access it. If the app is only for yourself, that's cool. If you want to distribute it through Google MarketPlay (or whatever it is called these days), please know that some people (myself included) tend to look at the permissions and ask "why would an app doing X require permission to do Y?", and sometimes not install the app because of it.
If the manual part is done by the app's user, by all means, store it on the sdcard. It's the only place a standard, none-root user even has access to.
Generally speaking, however, a better place to store data is in /data/data/packagename. See Android's data storage for more details.
Shachar
Add file in assets folder, then it will be clearly after new install

import external db into app and use it in android

Im new to android development. Now im trying to use sqlite db.
I created a database sqlite file using sqlite manager.
I imported it to the project by /data/data/packagename/dbname, it works fine in emulator , but if I took release in device the app crashes,I didnt know what happens and why it happens. Any Suggestions for it?
You cannot use a External DB in that manner. When you import it into your project it doesn't mean it is available in all devices from there after(Assuming you used DDMS for this). It means that DB is available to that particular emulator only. Follow the below link to find out how to add a External DB to your Application..
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
private void StoreDatabase() {
File DbFile=new File("data/data/packagename/DBName.sqlite");
if(DbFile.exists())
{
System.out.println("file already exist ,No need to Create");
}
else
{
try
{
DbFile.createNewFile();
System.out.println("File Created successfully");
InputStream is = this.getAssets().open("DBName.sqlite");
FileOutputStream fos = new FileOutputStream(DbFile);
byte[] buffer = new byte[1024];
int length=0;
while ((length = is.read(buffer))>0)
{
fos.write(buffer, 0, length);
}
System.out.println("File succesfully placed on sdcard");
//Close the streams
fos.flush();
fos.close();
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
View this link, this will be very helpful if you are using your own database in Android.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
in this tutorial you have to put your database in assets folder of your project and the database will automatically transferred to database folder of you device.
See https://github.com/jgilfelt/android-sqlite-asset-helper for a helper lib to take care of this.
(I haven't used this library personally but I came across it yesterday while searching for something else. It appears to do what you need, though).

Using a button to export sqlite db to an excel-readable file (perhaps csv)?

I adapted this tutorial (http://www.screaming-penguin.com/node/7749) to an Android app I've built to allow for a button press to export the current database to the user's sdcard. It works flawlessly.
But I'm afraid that users of my app would be unfamiliar with the db file, and I'm looking for a way to convert that to a more user-friendly format. I came across this thread (http://groups.google.com/group/android-beginners/browse_thread/thread/4e53ebca14daecfc), which recommends "querying data from the database and writing the data into a csv file."
I was hoping someone could point me in the right direction to begin figuring out how to do this. I'm finding it hard to track down more information about the specific method.
Or does it make more sense to just explain in a short "about" how to read and access .db files?
Thanks
EDIT: I also have a question about the sqlite export process, which I think I'll just ask here rather than create a new question. Is there a way to modify the code below so that each export would receive either a string representation of the date or just a single numeral appended to it? Right now if you export a second time, it automatically overwrites the old file. Thanks.
protected Boolean doInBackground(final String... args) {
File dbFile = new File(Environment.getDataDirectory() +
"/data/com.example.example/databases/data");
File exportDir = new File(Environment.getExternalStorageDirectory(), "exampledata");
if (exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
this.copyFile(dbFile, file);
return true;
} catch(IOException e) {
Log.e(MyApplication.APP_NAME, e.getMessage(), e);
return false;
}
}
I was hoping someone could point me in the right direction to begin figuring out how to do this.
To read in the data, use rawQuery().
To write the data, use Java I/O. There are also open source CSV libraries for Java that may work on Android.
Is there a way to modify the code below so that each export would receive either a string representation of the date or just a single numeral appended to it?
Use string concatenation to add whatever you want to the filename.
Also, please get rid of:
File dbFile = new File(Environment.getDataDirectory() +
"/data/com.example.example/databases/data");
and replace it with:
File dbFile=getDatabasePath("data");

Categories