Java Jtable connect and get data from MsSql Server - java

I am new at java swing because of that in my project i couldn't connect and get data from Microsoft sql server to Jtable.
But in this time I have just done it but I still interesting that if I don't use code, if I want to use that without code what should I do? In 'Netbeans', if you click table contents there is a way for import data to form. that is the point what I couldn't.
I tried to use this button(import data to form) and I showed my sqlserver.jar and I couldn't.

I think is that what you want:
http://fahdshariff.blogspot.com.br/2010/02/display-any-resultset-in-jtable.html
But in java, you will not get without some code.

I ran into a similar problem and the code below helped so I could retrieve the desired data. Edit the code so it will get the information you want it to retrieve.
private class RemoveBookings implements ActionListener {
String bookingID;
#Override
public void actionPerformed(ActionEvent ae) {
if (theMainViewDisplay.bookingData.getSelectedRow() != -1) {
final DefaultTableModel model = (DefaultTableModel) theMainViewDisplay.bookingData.getModel();
// Get stored varible
int index = theMainViewDisplay.bookingData.getSelectedRow();
System.out.println(index);
theMainViewDisplay.bookingID = model.getValueAt(index, 0).toString();
theMainViewDisplay.pickUpLocation = model.getValueAt(index, 2).toString();
theMainViewDisplay.dropOffLocation = model.getValueAt(index, 3).toString();
System.out.println(theMainViewDisplay.bookingID);
// Remove booking from database
model.removeRow(theMainViewDisplay.bookingData.getSelectedRow());
theBackendModel.thePowList.remove(bookingID);
}
}
}

Related

Can I store data in SQlite database from Strings I've written inside the code?

I have an app that it stores data inside a database and shows them in a recyclerview. my recyclerview should contain images. I want the image URL's to be stored in the database. but I don't want to get the URL's from the user. I want to write the URL myself and inside the code and then insert them in the database. Is there a way to store data in database from inside the code and not from any edit text ?
Not sure that I understood you right but if you need to write strings hardcoded in code just make any class with only this strings as constants and write them into database on every open of application. But this is bad practice. You can just use it from that class. Something like YourConstantsClass.yourConstant;
I wrote the code like this:
public void insertwall(ModelWallpaper modelWallpaper) {
ContentValues c = new ContentValues();
c.put(Colwall_Url,modelWallpaper.getImageURL());
try {
this.getWritableDatabase().insert(TABLE_NAME, null, c);
} catch (Exception e) {
e.printStackTrace();
}
}
and in mainActivity:
wallpaperHelper = new WallpaperHelper(this) ;
wallpaperHelper.open();
ModelWallpaper modelWallpaper = new ModelWallpaper();
modelWallpaper.setImageURL("https://tpc.googlesyndication.com/pagead/imgad?id=CICAgKDb4cfN9wEQARgBMgjiJeT4IZ5nOw");
wallpaperHelper.insertwall(modelWallpaper);
wallpaperHelper.close();

Open Office Extension getting the Value of a Textfield from the settingspage

I am currently working on an Open Office Extension and I have some troubles at one point.
I have made a settingspage in the OpenOffice Writer Tab with 3 Textfields.
I now want to get the Text the user entered into this fields.
I tried this:
XControl textfield2 = _xControlCont.getControl("TextField2");
XTextComponent username = (XTextComponent) UnoRuntime.queryInterface(XTextComponent.class, textfield2);
passwd = password.getText();
I am getting a Nullpointer exception right at the beginning and I think that the Problem is that with this code i cant get the value of the Textfield when the Optionspage is not open.
I am running kinda the same code in a seperate class where I test if all entered values are correct and if you can connect to our server.
I tried to get the Code from there with a getter method but this didn´t work too.
here is an example:
#Override
public void actionPerformed(ActionEvent actionEvent) {
boolean testConnection = false;
XControl label = _xControlCont.getControl("Label4");
XFixedText xLabel = (XFixedText) UnoRuntime.queryInterface(XFixedText.class, label);
XControl textfield2 = _xControlCont.getControl("TextField2");
XTextComponent username = (XTextComponent) UnoRuntime.queryInterface(XTextComponent.class, textfield2);
user = username.getText();}
and then outside of this method i am using the getter.
This is the Exception I am getting:
Exception in thread "Thread-15" java.lang.NullPointerException
at org.openoffice.demo.DocumentUpload.run(DocumentUpload.java:56)
I hope that one of you can help me.
Apparently _xControlCont is null. Be sure that the code always creates the object before it is used.
There is an example of using an XControlContainer at https://wiki.openoffice.org/wiki/API/Samples/Groovy/Office/RuntimeDialog.
EDIT:
Do not access a text field when the page is not open. Instead, save the text field's string to a variable when the page is open. Then read the saved string later.
Depending on the code, the string could also be saved to persistent storage such as user field variables or a data file, or returned as an argument from a dialog window. For example:
optionsDialog.doExecute()
results = optionsDialog.getResults()

Using ELKI with Mongodb

Using test cases I was able to see how ELKI can be used directly from Java but now I want to read my data from MongoDB and then use ELKI to cluster geographic (long, lat) data.
I can only cluster data from a CSV file using ELKI. Is it possible to connect de.lmu.ifi.dbs.elki.database.Database with MongoDB? I can see from the java debugger that there is a databaseconnection field in de.lmu.ifi.dbs.elki.database.Database.
I query MongoDB creating POJO for each row and now I want to cluster these objects using ELKI.
It is possible to read data from MongoDB and write it in a CSV file then use ELKI to read that CSV file but I would like to know if there is a simpler solution.
---------FINDINGS_1:
From ELKI - Use List<String> of objects to populate the Database I found that I need to implement de.lmu.ifi.dbs.elki.datasource.DatabaseConnection and specifically override the loadData() method which returns an instance of MultiObjectsBundle.
So I think I should wrap a list of POJO with MultiObjectsBundle. Now i'm looking at the MultiObjectsBundle and it looks like the data should be held in columns. Why columns datatype is List> shouldnt it be List? just a list of items you want to cluster?
I'm a little confused. How is ELKI going to know that it should look at the long and lat for POJO? Where do I tell ELKI to do this? Using de.lmu.ifi.dbs.elki.data.type.SimpleTypeInformation?
---------FINDINGS_2:
I have tried to use ArrayAdapterDatabaseConnection and I have tried implementing DatabaseConnection. Sorry I need thing in very simple terms for me to understand.
This is my code for clustering:
int minPts=3;
double eps=0.08;
double[][] data1 = {{-0.197574246, 51.49960695}, {-0.084605692, 51.52128377}, {-0.120973687, 51.53005939}, {-0.156876, 51.49313},
{-0.144228881, 51.51811784}, {-0.1680743, 51.53430039}, {-0.170134484,51.52834133}, { -0.096440751, 51.5073853},
{-0.092754157, 51.50597426}, {-0.122502346, 51.52395143}, {-0.136039674, 51.51991453}, {-0.123616824, 51.52994371},
{-0.127854211, 51.51772703}, {-0.125979294, 51.52635795}, {-0.109006325, 51.5216612}, {-0.12221963, 51.51477076}, {-0.131161087, 51.52505093} };
// ArrayAdapterDatabaseConnection dbcon = new ArrayAdapterDatabaseConnection(data1);
DatabaseConnection dbcon = new MyDBConnection();
ListParameterization params = new ListParameterization();
params.addParameter(de.lmu.ifi.dbs.elki.algorithm.clustering.DBSCAN.Parameterizer.MINPTS_ID, minPts);
params.addParameter(de.lmu.ifi.dbs.elki.algorithm.clustering.DBSCAN.Parameterizer.EPSILON_ID, eps);
params.addParameter(DBSCAN.DISTANCE_FUNCTION_ID, EuclideanDistanceFunction.class);
params.addParameter(AbstractDatabase.Parameterizer.DATABASE_CONNECTION_ID, dbcon);
params.addParameter(AbstractDatabase.Parameterizer.INDEX_ID,
RStarTreeFactory.class);
params.addParameter(RStarTreeFactory.Parameterizer.BULK_SPLIT_ID,
SortTileRecursiveBulkSplit.class);
params.addParameter(AbstractPageFileFactory.Parameterizer.PAGE_SIZE_ID, 1000);
Database db = ClassGenericsUtil.parameterizeOrAbort(StaticArrayDatabase.class, params);
db.initialize();
GeneralizedDBSCAN dbscan = ClassGenericsUtil.parameterizeOrAbort(GeneralizedDBSCAN.class, params);
Relation<DoubleVector> rel = db.getRelation(TypeUtil.DOUBLE_VECTOR_FIELD);
Relation<ExternalID> relID = db.getRelation(TypeUtil.EXTERNALID);
DBIDRange ids = (DBIDRange) rel.getDBIDs();
Clustering<Model> result = dbscan.run(db);
int i =0;
for(Cluster<Model> clu : result.getAllClusters()) {
System.out.println("#" + i + ": " + clu.getNameAutomatic());
System.out.println("Size: " + clu.size());
System.out.print("Objects: ");
for(DBIDIter it = clu.getIDs().iter(); it.valid(); it.advance()) {
DoubleVector v = rel.get(it);
ExternalID exID = relID.get(it);
System.out.print("DoubleVec: ["+v+"]");
System.out.print("ExID: ["+exID+"]");
final int offset = ids.getOffset(it);
System.out.print(" " + offset);
}
System.out.println();
++i;
}
The ArrayAdapterDatabaseConnection produces two clusters, I just had to play around with the value of epsilon, when I set epsilon=0.008 dbscan started creating clusters. When i set epsilon=0.04 all the items were in 1 cluster.
I have also tried to implement DatabaseConnection:
#Override
public MultipleObjectsBundle loadData() {
MultipleObjectsBundle bundle = new MultipleObjectsBundle();
List<Station> stations = getStations();
List<DoubleVector> vecs = new ArrayList<DoubleVector>();
List<ExternalID> ids = new ArrayList<ExternalID>();
for (Station s : stations){
String strID = Integer.toString(s.getId());
ExternalID i = new ExternalID(strID);
ids.add(i);
double[] st = {s.getLongitude(), s.getLatitude()};
DoubleVector dv = new DoubleVector(st);
vecs.add(dv);
}
SimpleTypeInformation<DoubleVector> type = new VectorFieldTypeInformation<>(DoubleVector.FACTORY, 2, 2, DoubleVector.FACTORY.getDefaultSerializer());
bundle.appendColumn(type, vecs);
bundle.appendColumn(TypeUtil.EXTERNALID, ids);
return bundle;
}
These long/lat are associated with an ID and I need to link them back to this ID to the values. Is the only way to go that using the ID offset (in the code above)? I have tried to add ExternalID column but I don't know how to retrieve the ExternalID for a particular NumberVector?
Also after seeing Using ELKI's Distance Function I tried to use Elki's longLatDistance but it doesn't work and I could not find any examples to implement it.
The interface for data sources is called DatabaseConnection.
JavaDoc of DatabaseConnection
You can implement a MongoDB-based interface to get the data.
It is not complicated interface, it has a single method.

TypeMismatchException when creating a google visualization datatable with Date type column

Ok, so after trying really hard for some days i am still not able to make this work.
This is the problem: I have a JSP which hosts a Google chart that is going to be constructed from data that is going to be sent through a Servlet. I'm using the Google Visualization Java libraries to implement this servlet.
Then i have this helper function that, taking some data stored in a list of objects, constructs a datatable. Following is the class that implements said function:
public class DataTableGenerator {
public static DataTable generateDatatable(List<AccesoUrl> accesos) {
DataTable data = new DataTable();
ArrayList<ColumnDescription> cd = new ArrayList<>();
cd.add(new ColumnDescription("fecha", ValueType.DATE, "Fecha"));
cd.add(new ColumnDescription("navegador", ValueType.TEXT, "Navegador"));
cd.add(new ColumnDescription("ip", ValueType.TEXT, "IP"));
cd.add(new ColumnDescription("os", ValueType.TEXT, "Sistema Operativo"));
data.addColumns(cd);
try {
for(AccesoUrl acceso : accesos) {
GregorianCalendar calendario = new GregorianCalendar();
calendario.setTimeZone(TimeZone.getTimeZone("GMT"));
data.addRowFromValues(calendario, acceso.getNavegador(), acceso.getIp(), acceso.getSistemaoperativo());
}
} catch (TypeMismatchException e) {
System.out.println(e);
}
return data;
}
}
Now, this piece of code should work, but instead i am getting this exception on my web server:
com.google.visualization.datasource.base.TypeMismatchException: Value type mismatch.
at com.google.visualization.datasource.datatable.value.ValueType.createValue(Unknown Source)
at com.google.visualization.datasource.datatable.DataTable.addRowFromValues(Unknown Source)
I'm at wit's end now. I have tried every variation i could find on Google so that my JSP displays this data on a Google Table type of chart. I have tried sending a date as a string, a date as a string formatted as a javascript date (i.e "Date(2015,4,4)" or "new Date(2015,4,4)"). I have tried using the DateValue object that comes with the java visualization library to construct the date as well (i.e new DateValue(2015,4,4)). I have also tried passing a Java Date as well. Nothing works, everything throws a TypeMismatchException.
I am sure it's the date that's giving me trouble because as soon as i remove the date column from the datatable everything runs fine with no exception and i can get my data displayed on the Google chart table.
So can anybody please tell me what exactly do i have to do in my Java code to be able to construct a datatable with a date cell?
Even I faced same issue. But it seems addRowFromValues() doesn't support DateValue(). I siwtched to addRow(TableRow). Didnt see any error's.
You can use something like below,
Sample Code:
DataTable data = new DataTable();
ArrayList<ColumnDescription> cd = new ArrayList<ColumnDescription>();
cd.add(new ColumnDescription("date", ValueType.DATE, "Executed Date"));
cd.add(new ColumnDescription("value", ValueType.NUMBER, "Duration "));
data.addColumns(cd);
TableRow tr = new TableRow();
tr.addCell(new DateValue(2015,7,7));
data.addRow(tr);

Android rename SQLite Database

Is it possible to rename a database already created in android?
On my apps update I would like to rename the old database and install a new then compare some values and finally delete the old.
I am doing the creation from an sqlite file in the assets folder. This is why I cannot rename all the tables and insert the new ones.
Clarification:
The old database will contain only one table that I need to compare values from against the new (from the update) database.
Both databases have been copied over from an sqlite file in the assets folder.
Once I have compared a values from the old database to new I will delete the old and use the new in its place with the values I compared.
What i was thinking of doing was rename the old create the new in its place and do everything above.
Just rename the File. Make sure the database is closed first!
Call this in your activity class:
private void renameDatabase()
{
File databaseFile = getDatabasePath("yourdb.whatever");
File oldDatabaseFile = new File(databaseFile.getParentFile(), "yourdb_old.whatever");
databaseFile.renameTo(oldDatabaseFile);
}
Response to clarification. Rename the old db (as above), copy the new one from the assets folder, open both databases and do your compare. Then delete the old file.
Lord Flash is right, you should delete the old db and copy the new one…
Assuming you use a SQLiteOpenHelper, you could use a createDatabaseIfRequired(); method in getReadableDatabase() and getWritableDatabase()
private boolean checkOldDatabase() {
Log.d(Constants.LOGTAG, "OperationDbHelper.checkDatabase");
File f = new File(DB_PATH + OLD_DB_NAME);
return f.exists();
}
public void createDatabaseIfRequired() throws IOException, SQLiteException {
if (!checkOldDatabase()) {
// do db comparison / delete old db / copy new db
}
}
It's not possible to rename a sql table directly.
But you may copy it creating a new and deleting the old one.
Thanks to Kevin Galligan's answer, I was able to create a function in my Kotlin Android app that I can use whenever it might ever be necessary, to rename the database files.
If you're using Java, you'll need to change the syntax a bit but the code should hopefully be somewhat self-explanatory.
val x: String = "Hello"
//in Kotlin would be
String x = "Hello";
//in Java, for example.
Anyway, here's my code, feel free to ask questions if you have any:
private fun checkAndRenameDatabase(oldName: String, newName: String) {
val oldDatabaseFile: File = getDatabasePath(oldName)
val oldDatabaseJournal: File = getDatabasePath("${oldName}-journal")
// Can use this to check files beforehand, using breakpoints
//val files = oldDatabaseFile.parentFile.listFiles()
if(oldDatabaseFile.exists() || oldDatabaseJournal.exists()) {
db.close() // Ensure existing database is closed
val newDatabaseFile: File = getDatabasePath(newName)
val newDatabaseJournal: File = getDatabasePath("${newName}-journal")
if(oldDatabaseFile.exists()) {
if(newDatabaseFile.exists()) {
newDatabaseFile.delete()
}
oldDatabaseFile.renameTo(newDatabaseFile)
}
if(oldDatabaseJournal.exists()) {
if(newDatabaseJournal.exists()) {
newDatabaseJournal.delete()
}
oldDatabaseJournal.renameTo(newDatabaseJournal)
}
// Use with breakpoints to ensure files are now in order
//val newFiles = oldDatabaseFile.parentFile.listFiles()
// Re-open database with new name
db = SQLiteDBHelper(applicationContext, newName)
}
}

Categories