Recently I complete a project about face recognition using JavaCV. it save faces to computer directory but i want to save those faces to RDBMs like SQLite, MySQL would be welcome.
Code for save image to computer directory
private String createPictureFilePathName(File dir) {
File file = new File(dir.getPath() + "/image-0.png");
int counter = 1;
while (file.exists()) {
file = new File(dir.getPath() + "/image-" + counter + ".png");
counter++;
}
return file.getPath();
}
private static JFileChooser initPictureDirChooser() {
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setCurrentDirectory(new File(System.getProperty("user.home")).getAbsoluteFile());
return chooser;
}
Any leads to make this possible to save images to database?
Get the input stream of the file and save it into db as a blob using preparedstatement.
Example Code :
public boolean saveFile(File file) throws Exception{
boolean completed = false;
ConnectionManager conn = new ConnectionManager();
try {
PreparedStatement statement = conn.getConnection().prepareStatement("QUERY_TO_INSERT_FILE");
statement.setBlob(1, file.getInputStream());
statement.execute();
conn.commit();
completed = true;
} catch (SQLException e) {
conn.rollbackQuietly();
e.printStackTrace();
throw e;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
conn.close();
}
return completed;
}
Related
I have a camera that I am grabbing values pixel-wise and I'd like to write them to a text file. The newest updates for Android 12 requires me to use storage access framework, but the problem is that it isn't dynamic and I need to keep choosing files directory. So, this approach it succesfully creates my files but when writting to it, I need to specifically select the dir it'll save to, which isn't feasible to me, as the temperature is grabbed for every frame and every pixel. My temperature values are in the temperature1 array, I'd like to know how can I add consistently add the values of temperature1 to a text file?
EDIT: I tried doing the following to create a text file using getExternalFilesDir():
private String filename = "myFile.txt";
private String filepath = "myFileDir";
public void onClick(final View view) {
switch (view.getId()){
case R.id.camera_button:
synchronized (mSync) {
if (isTemp) {
tempTureing();
fileContent = "Hello, I am a saved text inside a text file!";
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filepath), filename);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Log.e("TAG", "file: "+myExternalFile);
}
isTemp = false;
//Log.e(TAG, "isCorrect:" + mUVCCamera.isCorrect());
} else {
stopTemp();
isTemp = true;
}
}
break;
I can actually go all the way to the path /storage/emulated/0/Android/data/com.MyApp.app/files/myFileDir/ but strangely there is no such file as myFile.txt inside this directory, how come??
Working Solution:
public void WriteToFile(String fileName, String content){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File newDir = new File(path + "/" + fileName);
try{
if (!newDir.exists()) {
newDir.mkdir();
}
FileOutputStream writer = new FileOutputStream(new File(path, filename));
writer.write(content.getBytes());
writer.close();
Log.e("TAG", "Wrote to file: "+fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
I am developing an Android application that produces results and I am saving this results in a CSV file. After that I want to close the app, open it again, get other results and write them at the end of the same existing CSV file. Right now every time it ovverrides the previous results.
This is my class to save the results in a CSV file:
public class SaveCSV {
private File file;
private RandomAccessFile randomAccessFile;
public SaveCSV(){
this.file = getPath("RisultatiTest.csv");
try {
this.randomAccessFile = new RandomAccessFile(file, "rwd");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void salvaRisultati (int[] array) {
try {
file.createNewFile();
String s = "";
for (int i = 0; i < array.length; i++) {
s = s + array[i] + ",";
}
randomAccessFile.writeBytes(s);
randomAccessFile.writeBytes("\n");
} catch (IOException e) {
throw new RuntimeException("Unable to create File " + e);
}
}
public static File getPath(String fileName){
return new File(Environment.getExternalStorageDirectory(), fileName);
}
}
I am new for android, Im downloading image from URL and set in listView. Its working some mobile and not creating file/directory in some mobile.
Its throw error like:
java.io.FileNotFoundException: /storage/emulated/0/.tam/veg.png: open failed: ENOENT (No such file or directory)
I don't know why its throw error like this some mobile. I want to create directory all type of mobile. Please anyone help me.
Here my code:
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), ".tam");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.tam/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static File checkifImageExists(String imagename) {
File file = ImageStorage.getImage("/" + imagename);
if (file.exists()) {
return file;
} else {
return null;
}
}
public static String getImageName(String value){
String getName[] = value.split("/");
return getName[4];
}
}
Below path not in all mobile:
/storage/emulated/0/
Thanks in advance!!
Maybe u should check if there's external storage in the mobile before u use this path
public String getDir(Context context) {
String checkPath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
checkPath = Environment.getExternalStorageDirectory().getPath();
} else {
checkPath = context.getCacheDir().getPath();
}
return checkPath;
}
i need to retrieve data from sqlite .and retrieved data should be displayed in a gridfieldmanager layout.i have done the below code please help me how to display data from database over the myscreen.
SQLManager screen
public class SQLManager {
static String snapsdata;
private static String DB_NAME = "employee_details.db3";
private Database _db;
public SQLManager() throws Exception {
// Determine if an SDCard is present
boolean sdCardPresent = false;
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if (root.equalsIgnoreCase("sdcard/")) {
sdCardPresent = true;
}
}
if (!sdCardPresent) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("This application requires an SD card to be
present.");
System.exit(0);
}
});
} else {
String dbLocation = "/SDCard/databases/sample/";
// Create URI
URI uri = URI.create(dbLocation + DB_NAME);
// Open or create a plain text database. This will create the
// directory and file defined by the URI (if they do not already
// exist).
Database db = DatabaseFactory.openOrCreate(uri,
new DatabaseSecurityOptions(false));
// Close the database in case it is blank and we need to write to
// the file
db.close();
//Dialog.alert("db");
// Open a connection to the database file
FileConnection fileConnection = (FileConnection) Connector
.open("file://" + dbLocation + DB_NAME);
// If the file is blank, copy the pre-defined database from this
// module to the SDCard.
if (fileConnection.exists() && fileConnection.fileSize() == 0) {
readAndWriteDatabaseFile(fileConnection);
//Dialog.alert("db1");
}
// Open the database
db = DatabaseFactory.open(uri);
_db = db;
}
}
/**
* Copies the pre-defined database from this module to the location
* specified by the fileConnection argument.
*
* #param fileConnection
* File connection to the database location
*/
public void readAndWriteDatabaseFile(FileConnection fileConnection)
throws IOException {
OutputStream outputStream = null;
InputStream inputStream = null;
// Open an input stream to the pre-defined encrypted database bundled
// within this module.
inputStream = getClass().getResourceAsStream("/" + DB_NAME);
//Dialog.alert("db" + inputStream);
// Open an output stream to the newly created file
outputStream = (OutputStream) fileConnection.openOutputStream();
// Read data from the input stream and write the data to the
// output stream.
byte[] data = new byte[1024 * 5];
int length = 0;
while (-1 != (length = inputStream.read(data))) {
outputStream.write(data, 0, length);
}
// Close the connections
if (fileConnection != null) {
fileConnection.close();
}
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
/**
* Constructs a new SQLManager object
*
* #param db
* Database to manage
*/
public SQLManager(Database db) {
_db = db;
}
/**
* Closes the database
*/
void closeDB() {
try {
_db.close();
} catch (DatabaseException dbe) {
}
}
public void SaveEmployeeInformation(int employeeid, String employee_name,
String position, int salary){
//return productinfo;
Statement st;
try {
st = _db.createStatement("INSERT INTO
employee_details(employee_id,employee_name,position,salary) VALUES (?, ?,
?, ?)");
try
{
st.prepare();
Object[] bindParams = {new Integer(employeeid), new
String(employee_name), new String(position), new Integer(salary)};
long rowID = st.executeInsert(bindParams);
// Dialog.alert("ro "+rowID);
}
finally
{
st.close();
closeDB();
}
} catch (DatabaseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Vector getEmployeeInformation(){
Vector productinfo = new Vector();
try {
Statement statement = null;
// Read in all records from the Category table
statement = _db
.createStatement("select MAX(employee_id) as
employeeReportId from employee_details");
// ProjectImagesID Project_id,ImagePath,ImageDescription
statement.prepare();
// statement.setCursorBufferSize(10);
Cursor cursor = statement.getCursor();
Employeelist productdatas;
Row row;
// Iterate through the result set. For each row, create a new
// Category object and add it to the hash table.
while (cursor.next()) {
row = cursor.getRow();
productdatas = new Employeelist(row.getInteger(0));
productinfo.addElement(productdatas);
}
// Dialog.alert(""+productinfo.size());
statement.close();
cursor.close();
} catch (DatabaseException dbe) {
Dialog.alert("SD PRODUCTINFP " + dbe.toString());
} catch (DataTypeException e) {
Dialog.alert("PRODUCTINFP " + e.toString());
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeDB();
}
return productinfo;
}
}
myscreen screen
public final class MyScreen extends MainScreen
{
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
// int reportid = 0;
try {
SQLManager emp = new SQLManager();
emp.SaveEmployeeInformation(7,"farah","developer", 4000);
emp.getEmployeeInformation();
} catch (Exception e)
{// TODO Auto-generated catch block
e.printStackTrace();
}
int row = 5;
GridFieldManager dfm = new GridFieldManager(row,3, 0);
add(dfm);
}
}
First try to acheive the successul set up and retreiving of data from SQlite Db. .Then with retrieved data,try to use it in grid field Manager.
Please write exact problem in code which helps us to solvethe problem.
I'm working with Android and I'm trying to use a database I already have. I'd like to put it on the SD card. I have the database file in my project's assets folder. How can I make it on the SD card or external storage of whatever device the app is installed on?
//Step1 : Checked accessiblity on sd card
public boolean doesSDCardAccessible(){
try {
return(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}
//Step2 : create directory on SD Card
//APP_DIR : your PackageName
public void createAndInitAppDir(){
try {
if(doesSDCardAccessible()){
AppDir = new File(Environment.getExternalStorageDirectory(),APP_DIR+"/");
if(!AppDir.exists()){
AppDir.mkdirs();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//Step 3 : Create Database on sdcard
//APP_DIR : your PackageName
//DATABASE_VERSION : give Database Vesrion
//DATABASE_NAME : your Databsename Name
public void initDB()
{
try {
//Using SQLiteHelper Class Created Database
sqliteHelper = new SQLiteHelper(Application.this,AppDir.getAbsolutePath()+"/"+DATABASE_NAME,
null, DATABASE_VERSION);
//OR use following
//Creating db here. or db will be created at runtime whenever writable db is opened.
db = SQLiteDatabase.openOrCreateDatabase(AppDir.getAbsolutePath()+"/"+DATABASE_NAME, null);*/
db= sqliteHelper.getWritableDatabase();
db.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
In reference to this answer, you can find the directory of the SD card in Android 4.0+ by trying both of the following (only one should work per device):
new File("/mnt/external_sd/");
or
new File("/mnt/extSdCard/");
On Android <4.0, you can use
Environment.getExternalStorageDirectory();
You can create your SQLite database there. Additionally, if you can't find it, you can iterate over all directories in /mnt/ (note: the sdcard will always be accessible via /mnt/).
Go throuh this link
OR try following
InputStream myInput;
try {
AssetManager assetManager = getAssets();
myInput = assetManager.open("mydatabase.db");
File directory = new File("/sdcard/some_folder");
if (!directory.exists()) {
directory.mkdirs();
}
OutputStream myOutput = new FileOutputStream(directory
.getPath() + "/DatabaseSample.backup");
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The database is like any other flat file. Just copy it to your SD card.
public boolean backup()
{
File sdcard = Environment.getExternalStorageDirectory();
File data = new File("/data/data/com.mydomain.myappname/databases/");
if (sdcard.canWrite())
{
File input = new File(data, DB_NAME);
File output = new File(sdcard, "android/data/com.mydomain.myappname/databases/");
if(!output.exists())
{
if(output.mkdirs())
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
output.createNewFile();
result = true;
}
else
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
result = true;
}
if(input.exists() && result)
{
FileInputStream source;
FileOutputStream destination;
try
{
source = new FileInputStream(input);
try
{
destination = new FileOutputStream(output);
byte[] buffer = new byte[1024];
int length;
while((length = source.read(buffer)) > 0)
{
destination.write(buffer, 0, length);
}
source.close();
destination.flush();
destination.close();
result = true;
}
catch(Exception e)
{
result = false;
destination = null;
}
}
catch(Exception e)
{
result = false;
source = null;
}
}
else
{
result = false;
}
}
else
{
result = false;
}
}
catch(Exception e)
{
result = false;
}
return result;
}