Retrieve Image from SQLITE DB and open it in imageView using JFXbutton - database

I'm trying to create desktop App (scenebuilder) and I want to retrieve path of Image from DATABASE (SQLITE) and Attach it to button to open it in ImageView but I'm facing a problem while doing that.
Note: I'm trying to learn Java
My code
#FXML
private ImageView imageView;
#FXML
void btn10 (ActionEvent event) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sogeclair.sqlite");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "SELECT * FROM image WHERE rowid = 1" ;
System.out.println(sql);
ResultSet rs = stmt.executeQuery( sql );
while ( rs.next() ) {
String path=rs.getString("imaging");
imageView.setImage(new Image(path));
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
and I got this in result
Opened database successfully
SELECT * FROM image WHERE rowid = 1
java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
Deleting directory C:\Users\Lenovo\Documents\NetBeansProjects\sogece\dist\run538077077
jfxsa-run:
BUILD SUCCESSFUL (total time: 10 seconds)
and MyDatabase
All comments are welcome :D help me please :D

This is code from a program I wrote that retrieves an image blob from sqlite. You can download and run the program from here. It's running, but it's an incomplete program.
In your code, once you get the image using ideas from my code then just use that image to set your ImageView.
String sqlTCNote = "SELECT * FROM Company;";
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:contactFX.db");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(sqlTCNote))
{
while(rset.next())
{
Company c1 = new Company();
c1.setName(rset.getString("company_name"));
c1.setShortName(rset.getString("short_name"));
c1.setStreet(rset.getString("street"));
c1.setCity(rset.getString("city"));
c1.setState(rset.getString("state"));
c1.setZip(rset.getString("zip"));
c1.setPhoneNumber(rset.getString("phone_number"));
c1.setTollFreeNumber(rset.getString("toll_free_number"));
c1.setEmailAddress(rset.getString("email_address"));
c1.setMissionStatement(rset.getString("mission_statement"));
c1.setPersonalNote(rset.getString("personal_note"));
c1.setWebSiteAddress(rset.getString("website_address"));
//This is the part you are interested in!
InputStream input = rset.getBinaryStream("image");
InputStreamReader inputReader = new InputStreamReader(input);
if(inputReader.ready())
{
File tempFile = new File("tempFile.jpg");
FileOutputStream fos = new FileOutputStream(tempFile);
byte[] buffer = new byte[1024];
while(input.read(buffer) > 0){
fos.write(buffer);
}
Image image = new Image(tempFile.toURI().toURL().toString());
c1.setImage(image);
}
for(int i = 0; i < 10; i++)
{
c1.addEmployee(new Employee());
}
companyData.add(c1);
}
}
catch(SQLException ex)
{
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}

Related

Retrieve data return "" in ResultSet. SQL SERVER + ANDROID STUDIO

urlImage always show "", not error and not null
#Override
protected String doInBackground(String... strings) {
try
{
Connection conn = connPO.CONN(); //Connection Object
if (conn == null)
{
}
else {
// Change below query according to your own database.
String query = "select * from config";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null)
{
try {
urlImage = rs.getString("url"); //--here I try get data
} catch (Exception ex) {
ex.printStackTrace();
}
msg = "TEST = "+urlImage;
} else {
msg = "No Data found!";
}
}
} catch (Exception e)
{
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
}
return msg;
}
E/MSG===>: TEST =
urlImage = rs.getString("url") //-- why this are "" ?
propertiy url there is in database with value.
You need to call rs.next() before trying to get data from the ResultSet. The first call will move the result set cursor to the first row.
From Java Se:
boolean next()
throws SQLException
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

Why Npgsql sometimes not responding?

I using Npgsql 3.2.2
I connect to database of Web server:
<add key="CONNECTION_STRING_WEBSERVER" value="Server=abctest.com;Port=5432;UserId=postgres;Password=postgres;Database=testdatabase;CommandTimeout=300;" />
My query to get data:
Dim sql="Select * from table1;"
my function:
private DataTable getData(string tableName)
{
DataSet ds = null;
DataTable tbl = null;
try
{
if (m_ConnectionExecute == null)
{
m_ConnectionExecute = new NpgsqlConnection(m_connString_web);
}
if (m_ConnectionExecute.State != ConnectionState.Open)
{
m_ConnectionExecute.Open();
}
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
NpgsqlCommand command = null;
try
{
command = CreateCommand(m_Parameters);
command.CommandText = m_commText;
command.Connection = m_ConnectionExecute;
adapter.SelectCommand = command;
ds = new DataSet();
adapter.Fill(ds, "Table1");
tbl = ds.Tables[0];
tbl.TableName = tableName;
ds.Tables.Clear();
}
catch (SqlException ex)
{
ds = null;
}
finally
{
if ( m_ConnectionExecute != null && m_ConnectionExecute.State != ConnectionState.Closed)
{
m_ConnectionExecute.Close();
}
}
}
catch (Exception e)
{
ds = null;
tbl = null;
}
return tbl;
}
I using Timer : 5s will call function getData.
But sometimes, function getData not respond and my program can't continue next process.
The problem only occur when Timer run some days and database put on a web server.
Notes: I have 5 Timer run auto access database.
what is the cause? or limit of postgresql?
Why Npgsql sometimes not responding?

display bytes from database as image in imageview in javafx

please I have been stuck on how to convert my stored images from my
database and display it as an image in imageview in javafx.
All the
previously asked questions have not helped me.
I'm using objectdb as my database
I also used fxml to build my GUI
for (Person p : person) {
name.setText(p.getName());
gender.setText(p.getGender());
byte[] byteArray = p.getImage();
image.setImage(new Image(new ByteArrayInputStream(byteArray)));
}
I'll show a detailed step on saving to the database using a file chooser and writing an image to a file in a directory(folder) on your hard drive, and also displaying it to imageview in fmxl GUI.
The following below are triggered during a button event or initialized
from the controller
FileChooser choose = new FileChooser();
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
choose.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
File file = choose.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
byte[] b;
try (ByteArrayOutputStream out = new ByteArrayOutputStream(262144)) {
ImageIO.write(bufferedImage, "jpg", out);
out.flush();
b = out.toByteArray();
}
EntityService service = new EntityService();
Person p = new Person();
p.setId(UUID.randomUUID().toString());
p.setImage(b);
service.putPerson(p);
} catch (IOException e) {
e.printStackTrace();
}
Person p = service.getPerson();
byte[] byteArray = p.getImage();
ByteArrayInputStream in = new ByteArrayInputStream(byteArray);
BufferedImage read = ImageIO.read(in);
image.setImage(SwingFXUtils.toFXImage(read, null));
String output = "C:\\java\\images\\1.jpg";
try (FileOutputStream fos = new FileOutputStream(output)) {
fos.write(byteArray);
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex);
} catch (IOException ioe) {
System.out.println("IOException : " + ioe);
}

JDBC -- database failure

I have the following methods that are encountering some sort of failure with my database. No error is being written to my console, so I'm confused. I'm using JDBC and Google AppEngine. Can anyone help me, please? Thanks.
public List<Bulletin> getApprovedBulletins() {
List<Bulletin> bulletins = new ArrayList<Bulletin>();
try {
Connection connection = getConnection();
Statement statement = connection.createStatement();
statement.executeQuery("select * from bulletins where approved = true");
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
Bulletin bulletin = new Bulletin();
bulletin.setId(resultSet.getInt("id"));
bulletin.setDate(resultSet.getDate("bulletin_date"));
bulletin.setName(resultSet.getString("name"));
bulletin.setSubject(resultSet.getString("subject"));
bulletin.setNote(resultSet.getString("bulletin"));
bulletins.add(bulletin);
}
resultSet.close();
connection.close();
return bulletins;
}
catch (Exception e) {
System.out.println(e.toString());
}
return null;
}
private Connection getConnection() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/cpc";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
return null;
}
return conn;
}
If you're using eclipse check the markers tab for errors. Note that the driver must be in the application server folder as well in order to work. Not sure why you don't get any errors in the console though...
Problem solved. I found a place to print out a message to my console, and it turns out I needed to add the following to appengine-web.xml, which I have done.
<sessions-enabled>true</sessions-enabled>

How do I backup a database file to the SD card on Android?

I'd like to add a feature to my Android app that automatically backs up the SQLite database to the SD card.
What's the best way to go about this? Are any examples or tutorials available?
This code works for me!
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//{package name}//databases//{database name}";
String backupDBPath = "{database name}";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
}
Does anyone know if this will work on non-root phones? I have only tried it on a rooted G1.
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+ packageName +"//databases//"+dbList[0];
String backupDBPath = dbList[0];
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
That works as opposed to the above examples in which the "/" are "\" wasted 20 minutes of my life figuring that out, but I really should have seen that sooner. The Toast will tell you where the file has been place or tell you what's wrong when it doesn't work.
SQLite databases are completely self-contained files and are portable — you can just copy the entire file straight to the SD card.
Though first I'd check whether an SD card is installed in the device, and what its path is (using Environment.getExternalStorageDirectory()).
I answered a question similar to this with a method you can place in your SQLiteOpenHelper. It is as simple as copying the db file from some kind of external storage, to the internal application storage. There is also some extra code that opens and reads the db file to make sure it is in the proper state for Android to make database calls to it.
public static void BackupDatabase() throws IOException
{
boolean success =true;
File file = null;
file = new File(Environment.getExternalStorageDirectory() +"/M.O.L.S_Backup");
if (file.exists())
{
success =true;
}
else
{
success = file.mkdir();
}
if (success)
{
String inFileName = "/data/data/com.sygic.sdk.demo/databases/MOLS_DB.s3db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/M.O.L.S_Backup/MOLS_DB.s3db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
fis.close();
}
}
You have to give the permission android.permission.WRITE_EXTERNAL_STORAGE in your application. It works fine on unrooted devices.
I don't know what happens if the phone is rooted or not but you should write your files to:
/Android/data/{package_name}/files/
This will work whether it's rooted or not.
You find your Database Name in the Database Adapter if you are new into this.
Note that you can do this for SharedPreferences too but keep in mind to change your Context.MODE_PRIVATE to Context.MODE_MULTI_PROCESS.
SharedPreferences_name should look like this = ExportSP("temp.xml");
String currentPathForSharedPreferences = "/data/"+ context.getPackageName() +"/shared_prefs/"+ SharedPreferences_name;
For export
exportDB("MyDbName");
private void exportDB(String db_name){
File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "Your Backup Folder"+
File.separator );
boolean success = true;
if (!sd.exists()) {
success = sd.mkdir();
}
if (success) {
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
String backupDBPath = db_name;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
} catch(IOException e) {
e.printStackTrace();
}
}}
For import
importDB("MyDbName");
private void importDB(String db_name){
File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "Your Backup Folder"+
File.separator );
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String backupDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
String currentDBPath = db_name;
File currentDB = new File(sd, currentDBPath);
File backupDB = new File(data, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
} catch(IOException e) {
e.printStackTrace();
}
}
#skeniver's code works for me. I just want to add the following:
Use:
String currentDbPath = getApplicationContext().getDatabasePath("{database name}");
It will give you your database path. It is better to use that instead of hardcoding the path, like:
String currentDbPath = "//data//{package name}//databases//{database name}";
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+getPackageName()+"//databases//"+DATABASE_NAME+"";
String backupDBPath = "backup.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}

Resources