Good Day I am completely new to coding. I am building an app which uses a combobox besides other library items. The problem I am facing is that while attempting to populate combobox items from a Mysql Db the item values get duplicated each time the drop down is clicked.
How I can keep this from happening ? I do understand that my approach itself could be erroneous.
#FXML
public void getStation() {
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
comboBoxStation.getItems().add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
Ok so I moved the function to the initialize() method in the controller and created an Observabale list called station
private ObservableList<String> stationsList = FXCollections.observableArrayList();
#Override
public void initialize(URL url, ResourceBundle rb) {
//
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
stationsList.add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
and then left only this line in the original function....seems to be working.
#FXML
private void getStation() {
comboBoxStation.setItems(stationsList);
}
Related
I want to to print my row red when book is out of stock but i am getting error like that every time i try new idea to manage that:
"com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Data source rejected establishment of connection, message from
server: "Too many connections"
Even if i try to close all connections in same loop...
So here we go:
private boolean checkIfOutOfStock(BookDetail book) throws SQLException{
String query = "select * from tbl_loan where book_id = " + book.getId() + " ";
dc = new DbConnection();
conn = dc.connect();
PreparedStatement checkPst = conn.prepareStatement(query);
ResultSet checkRs = checkPst.executeQuery(query);
if(checkRs.next()){
checkRs.close();
checkPst.close();
return true;
} else
{
checkRs.close();
checkPst.close();
return false;
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
dc = new DbConnection();
conn = dc.connect();
selectionModel = editTabPane.getSelectionModel();
editTableBooks.setRowFactory(tv -> new TableRow<BookDetail>() {
#Override
public void updateItem(BookDetail item, boolean empty) {
super.updateItem(item, empty) ;
if (item == null) {
setStyle("");
} else
try {
if (checkIfOutOfStock(item)) {
setStyle("-fx-background-color: tomato;");
} else {
setStyle("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
It works fine until i slide up and down table few times... its like everytime i slide table im opening new connection. Any idea how to solve it?
Hey do you mean something like that?
editTableBooks.setRowFactory(tv -> new TableRow<BookDetail>() {
#Override
public void updateItem(BookDetail item, boolean empty) {
super.updateItem(item, empty) ;
Platform.runLater(new Runnable() {
#Override
public void run() {
if (item == null) {
setStyle("");
} else
try {
if (checkIfOutOfStock(item)) {
setStyle("-fx-background-color: tomato;");
} else {
setStyle("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
});
It doesn't change anything or i just didn't get it :P
I have tried a lot but not able to populate all values in the data base into my combo box table cell.
Controller.java
public class controller {
GetConnection gc = new GetConnection();
PreparedStatement pst;
ResultSet rs;
Statement st;
private ObservableList<Users> datas = FXCollections.observableArrayList();
public controller() {
}
#FXML
private TableView<Users> table;
#FXML
private TableColumn<Users, String> c1;
#FXML
private void editable() {
List<String> names = new ArrayList<String>();
try {
ObservableList<Users> datas = FXCollections.observableArrayList();
String sql = "select * from itemsadd";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("itemcode");
names.add(name);
System.out.println("probs" + names);
}
ResultSet rs2 = gc.getConnection().createStatement()
.executeQuery("SELECT * FROM itemsadd WHERE itemcode=1001");
while (rs2.next()) {
datas.add(new Users(rs2.getString("itemcode")));
}
for (String name : names) {
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(name));
//not getting full items here
System.out.println("hell3" + name);// am getting full items here
}
table.setItems(null);
table.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class Users {
private StringProperty Itemc;
private Users(String Itemc) {
this.Itemc = new SimpleStringProperty(Itemc);
}
public String getItemc() {
return Itemc.get();
}
public void setItemc(String Itemc) {
this.Itemc.set(Itemc);
}
public StringProperty ItemcProperty() {
return Itemc;
}
}
}
table.fxml
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication47.controller">
<children>
<TableView fx:id="table" editable="true" layoutX="136.0" layoutY="58.0" onKeyPressed="#editable" prefHeight="200.0" prefWidth="335.0">
<columns>
<TableColumn fx:id="c1" prefWidth="333.0" text="Name" />
</columns>
</TableView>
</children>
</AnchorPane>
Main.java loader
public class Tableveiw extends Application {
private Stage primaryStage;
private AnchorPane pane;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
showPerson();
}
public void showPerson() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Tableveiw.class.getResource("table.fxml"));
pane = (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
Database Connection
public class GetConnection {
public Connection getConnection() throws Exception {
Connection con = null;
try {
System.out.println("MySQL Connect Example.");
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
// Accessing driver from the jar file
Class.forName(driver).newInstance();
// Creating a veriable for Connection Called conn
con = DriverManager.getConnection(url + dbName, "root", "");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String arg[]) {
GetConnection con = new GetConnection();
System.out.println("Connection" + con);
}
}
My problem with the code is that am not getting the full items in the database record to my c1 combobox table cell.Am only getting the last items of the database record in my comboboxtablecell.I have created array but still not helping .Why am not able to populate whole items in database into my combobox tablecell .Please help me with neccessary changes in the code.
This is Just basic functionality . when you duble click on cell combobox will visible then you can select value.to see direct Combobox you have write own TableCell class see this you ll understand. I hope this will help you. any ?s post a comment
private void editable() {
try {
ObservableList<String> names = FXCollections.observableArrayList();
ObservableList<Users> datas = FXCollections.observableArrayList();
String sql = "select * from itemsadd";
pst = gc.getConnection().prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("itemcode");
names.add(name);
System.out.println("probs" + names);
}
ResultSet rs2 = gc.getConnection().createStatement()
.executeQuery("SELECT * FROM itemsadd WHERE itemcode=1001");
while (rs2.next()) {
datas.add(new Users(rs2.getString("itemcode")));
}
c1.setCellValueFactory(new PropertyValueFactory("Itemc"));
c1.setCellFactory(ComboBoxTableCell.forTableColumn(name));
table.setEditable(true);
table.getItems().clear();
table.setItems(datas);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
I have finally overcome my issue with a NPE in my code whilst learning FX/FXML. I now however have a different problem, a window opens with my TableView however there is no content in the table at all. As you cann I have printed out the JobList to make sure there is content being returned, and this returns three jobs (the correct amount). Am I missing something that binds the table to the returned list?
Here is the code;
public class SecondInterface implements Initializable {
private JobDataAccessor jAccessor;
private String aQuery = "SELECT * FROM progdb.adamJobs";
private Parent layout;
private Connection connection;
#FXML
TableView<Job> tView;
public void newI(Connection connection) throws Exception {
Stage primaryStage;
primaryStage = MainApp.primaryStage;
this.connection = connection;
System.out.println(connection);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Test1.fxml"));
fxmlLoader.setController(this);
try {
layout = (Parent) fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
primaryStage.getScene().setRoot(layout);
}
public Parent getLayout() {
return layout;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
jAccessor = new JobDataAccessor();
try {
System.out.println("This connection: " + connection);
System.out.println("This query: " + aQuery);
List<Job> jList = jAccessor.getJobList(connection, aQuery);
for (Job j : jList) {
System.out.println(j);
}
tView.getItems().addAll(jAccessor.getJobList(connection, aQuery));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
currently I want to send my GPS latitude and longitude to MYSQL by use of JDBC.
To retrieve GPS lat, long I've used the code below and I have GPS tracker code in GPSTracker class. This would toast Latitude and Longitude by any time pressing the button.
public class MainActivity extends Activity {
Button btnShowLocation;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//testDB();
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
// txtv = (TextView) findViewById(R.id.txtv);
// btnShowLocation.setOnClickListener(this);
// txtv.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
// txtv = getText().getApplicationContext(this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
}
}
To send JDBC data to MYSQL, I've used the code below which can only send the values that I giving to it in parenthesis:
public class MainActivity extends Activity {
static final String USER = "root";
static final String PASS = "root";
GPSTracker gps;
double tmplat = 0;
double tmplong = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appDB();
}
public void appDB() {
// TextView tv = (TextView) this.findViewById(R.id.txtv);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
//connection to data base.
Connection con = DriverManager.getConnection("jdbc:mysql://192.168.1.6:3306/k_sql1", USER, PASS);
//create a statement
// String result = "Database connection successfull !\n";
Statement statement = con.createStatement();
// execute sql query
String sql = ("INSERT INTO `gps-data2`(`ID`,`Latitude`,`Longitude`) VALUES (1,123.45678, 345.678901);");
// String sql = (" CREATE TABLE IF NOT EXISTS GPS_data ( ID int, Latitude Double, Longitude Double ); INSERT INTO GPS_data (`ID`,`Latitude`,`Longitude`) VALUES (1,1234.5678,56789.123456); ");
statement.executeUpdate(sql);
// System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
enter code here
Please tell me how to combine these 2 systems and send GPS data (lat, lng) to mysql by use of JDBC method. I know it maybe better to use PHP but for this project I want it by use of JDBC. Appreciate if can give me a simple applicable solution.
This is the answer what I was looking for to retrieve GPS parameters programmatically and send it to database directly by use of onClickListener.
static final String USER = "root";
static final String PASS = "root";
String sql = null;
GPSTracker gps;
double tmplat = 0;
double tmplong = 0;
Button btnShowLocation;
double latitude;
double longitude;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
appDB();
} else {
gps.showSettingsAlert();
}
}
});
}
protected void appDB() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/k_sql1", USER, PASS);
String result = "Database connection successfull !\n";
Statement statement = con.createStatement();
String sql = ("INSERT INTO `gps-data2`(`Latitude`,`Longitude`) VALUES (" + latitude + ", " + longitude + ");");
statement.executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
f
I have problem when trying to fetch the data from database and display in database. I get from user input and store as a search variable. This is how I set up my table:
//I get the user input to perform search
#FXML
public void searchResident(ActionEvent event){
String search=getTb_search().getText();
if(search.equals("")){
Dialogs.showErrorDialog(null, "Please enter something", "Blank fields detected", "");
}else{
setUpSearchTable(search);
}
}
//How I set up my table
public void setUpSearchTable(String search) {
TableColumn rmNameCol = new TableColumn("Name");
rmNameCol.setVisible(true);
rmNameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<SearchNeedyResidentController, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<SearchNeedyResidentController, String> p) {
return p.getValue().searchNameProperty();
}
});
TableColumn rmNricCol = new TableColumn("NRIC");
rmNricCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_nric"));
rmNricCol.setMinWidth(150);
TableColumn rmPhNoCol = new TableColumn("Phone Number");
rmPhNoCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController,String>("search_phNo"));
rmPhNoCol.setMinWidth(350);
TableColumn rmIncomeCol = new TableColumn("Income($)");
rmIncomeCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_income"));
rmIncomeCol.setMinWidth(100);
ResidentManagement.entity.NeedyResidentEntity searchValue= new ResidentManagement.entity.NeedyResidentEntity();
//viewProduct.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table_search.setEditable(false);
table_search.getColumns().addAll(rmNricCol, rmNameCol, rmIncomeCol, rmPhNoCol);
table_search.getItems().setAll(searchValue.searchResident(search));
}
}
//How I populate the table data
public List<SearchNeedyResidentController> searchResident(String search){
List ll = new LinkedList();
try {
DBController db = new DBController();
db.getConnection();
String sql = "SELECT * FROM rm_needyresident WHERE name LIKE '" + search + "%'";
ResultSet rs = null;
// Call readRequest to get the result
rs = db.readRequest(sql);
while (rs.next()) {
String nric=rs.getString("nric");
String name = rs.getString("name");
double income = rs.getDouble("familyIncome");
String incomeStr = new DecimalFormat("##.00").format(income);
String phNo = rs.getString("phNo");
SearchNeedyResidentController row = new SearchNeedyResidentController();
row.setSearchNric(nric);
row.setSearchName(name);
row.setSearchIncome(incomeStr);
row.setSearchPhNo(phNo);
ll.add(row);
}
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Error SQL!!!");
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
return ll;
}
}
When search button is on click, the table column is displayed. However, it's just show a blank table even though there's matching result. I debug already and I think the error is at the retrieving data in the searchResident method. It's not retriving the data from database. Anybody know what's wrong?
Thanks in advance.
try dis one...
#FXML private void SearchButton()
{
Connection c ;
datamem = FXCollections.observableArrayList();
try
{
c = Dao.getCon();
String SQL =SELECT * FROM `Member`;
ResultSet rs = c.createStatement().executeQuery(SQL);
if(table.getColumns().isEmpty())
{
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++)
{
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
table.getColumns().addAll(col);
}//for
}//if
while(rs.next())
{
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++)
{
row.add(rs.getString(i));
}// for
datamem.add(row);
}//while
table.setItems(datamem);
}//try
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Problem in Search Button "+e);
}
}//else
}//else
} //search method