MySQL javafx search like - mysql

I'm losing my mind over this. Maybe its something very simple that I miss. But I can't seem to get it work. I received help from other users and edited my code. But really can't get it to work.
This is my table in my database
+----------------+-----------------------+---------------------+
| colID | colTitle | colKeywords |
+----------------+-----------------------+---------------------+
| 1 | Jumanji | comedy adventure |
| 2 | Moana | adventure animation |
| 3 | Shawshank Redemption | drama tearjerker |
| 4 | Avengers | action |
+----------------+-----------------------+---------------------+
+-----------------------------+ +---------+
Search: | adventure and action movies | |button GO|
+-----------------------------+ +---------+
What I want to do is if I type "adventure and action movies" in the textfield, and after I hit the button go, the result in the tableview should be:
Jumanji
Moana
Avengers
My updated code:
public class UserMainPageController implements Initializable {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
#FXML
private TableView table_title;
#FXML
private TableColumn titleCol;
#FXML
private TextField txt_search;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
private void logOut(ActionEvent event) throws IOException{
Main.showUserLogin();
}
#FXML
private void goSearch(ActionEvent event) throws IOException, SQLException{
try{
conn = SqlConnection.ConnectDB();
String criteria = txt_search.getText();
if (criteria.trim().length() == 0) { return; }
String[] arryCriterion = criteria.split(" ");
List<String> results = new ArrayList<>();
for (int i = 0; i < arryCriterion.length; i++) {
List<String> text = populateField(arryCriterion[i], conn);
results.addAll(text);
}
ObservableList<String> observableList = FXCollections.observableList(results);
table_title.setItems(observableList);
}finally{
conn.close();
}
}
private List<String> populateField(String s, Connection conn) throws SQLException{
List<String> myList = new ArrayList<>();
String sql = "SELECT * FROM table_entry WHERE colTitle LIKE ? ";
pst=conn.prepareStatement(sql);
pst.setString(1, "%" + s + "%");
rs = pst.executeQuery();
while (rs.next()) {
myList.add(rs.getString("colTitle"));
}
return myList;
}
}
If I press the search button, nothing seems to appear in the tableview

Basically, my approach is similar to what #James_D is suggesting. First get all the data from the Database. Then filter the data using Java.
In my Database, I use Unicode Character INFORMATION SEPARATOR THREE (U+001D) between each keyword. Example: comedy↔adventure. I do this so that I can get each keyword using String.split().
In the app, I use a FilteredList to filter the TableView. If a DB(Database) entry contains at least one of the keywords, That entry will be shown. !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor); handles this.
Also, I have created a Tag class. This helps me keep up with things. These Tags look terrible, but you can beautify them using ideas from here.
Code:
Main:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Application;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private final TableView<Movie> table = new TableView<>();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setWidth(450);
stage.setHeight(550);
TableColumn colID = new TableColumn("ID");
colID.setMinWidth(100);
colID.setCellValueFactory(new PropertyValueFactory<>("colID"));
TableColumn colTitle = new TableColumn("Title");
colTitle.setMinWidth(100);
colTitle.setCellValueFactory(new PropertyValueFactory<>("colTitle"));
TableColumn colKeywords = new TableColumn("Keywords");
colKeywords.setMinWidth(200);
colKeywords.setCellValueFactory(new PropertyValueFactory<>("colKeywords"));
DBHandler dbhandler = new DBHandler();
FilteredList<Movie> filteredList = new FilteredList(dbhandler.getDBMovies());
table.setItems(filteredList);
table.getColumns().addAll(colID, colTitle, colKeywords);
FlowPane flowPane = new FlowPane();
TextField searchField = new TextField();
searchField.setOnAction(event -> {
List<String> searchingFor = new ArrayList();
Tag tempTag = new Tag(searchField.getText());
tempTag.getCloseButton().setOnAction((actionEvent) -> {
flowPane.getChildren().remove(tempTag);
if(flowPane.getChildren().isEmpty())
{
filteredList.setPredicate(null);
}
else{
filteredList.setPredicate((t) -> {
return !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor);
});
}
});
flowPane.getChildren().add(tempTag);
for(Node node : flowPane.getChildren())
{
searchingFor.add(((Tag)node).getText());
}
filteredList.setPredicate((t) -> {
return !Collections.disjoint(Movie.KeywordsStringToList(t.getColKeywords()), searchingFor);
});
searchField.clear();
});
HBox hbox = new HBox(searchField, flowPane);
final VBox vbox = new VBox(table, hbox);
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
}
Movie Class:
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* #author Sedrick
*/
public class Movie {
private static final String INFORMATION_SEPARATOR_THREE = "\u001D";
private final IntegerProperty colID = new SimpleIntegerProperty();
private final StringProperty colTitle = new SimpleStringProperty();
private final StringProperty colKeywords = new SimpleStringProperty();
public Movie(int colID, String colTitle, String colKeywords)
{
this.colID.set(colID);
this.colTitle.set(colTitle);
this.colKeywords.set(colKeywords);
}
public void setColID(int colID)
{
this.colID.set(colID);
}
public int getColID()
{
return this.colID.get();
}
public void setColTitle(String colTitle)
{
this.colTitle.set(colTitle);
}
public String getColTitle()
{
return this.colTitle.get();
}
public void setColID(String colKeywords)
{
this.colKeywords.set(colKeywords);
}
public String getColKeywords()
{
return this.colKeywords.get();
}
//Utility Methods
//Converts a String of keywords to a list<String> of keywords
public static List<String> KeywordsStringToList(String keywords)
{
String[] keywordsArray = keywords.split(INFORMATION_SEPARATOR_THREE);
List<String> keywordsList = new ArrayList();
for(String entry : keywordsArray)
{
keywordsList.add(entry);
}
return keywordsList;
}
//Convert a List<String> of keywords to a String of keywords
public static String keywordsListToString(List<String> keywords)
{
return String.join(INFORMATION_SEPARATOR_THREE, keywords);
}
}
Database Handler Class: This example uses an SQLite DB
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* #author Sedrick
*/
public class DBHandler {
Connection connection;
public DBHandler()
{
try
{
connection = DriverManager.getConnection("jdbc:sqlite:movie.db");
System.out.println("connected to db!");
} catch (SQLException ex)
{
Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ObservableList<Movie> getDBMovies()
{
String query = "SELECT * FROM MovieInfo";
ObservableList<Movie> movies = FXCollections.observableArrayList();
try(Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(query))
{
while(result.next())
{
Movie movie = new Movie(result.getInt("id"), result.getString("title"), result.getString("keywords"));
movies.add(movie);
}
}
catch (SQLException ex) {
Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return movies;
}
}
Tag Class:
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
/**
*
* #author Sedrick
*/
final public class Tag extends HBox{
final private Label keyword;
final private Button closeButton;
public Tag(String keyword) {
this.keyword = new Label(keyword);
closeButton = new Button("x");
this.getChildren().addAll(this.keyword, closeButton);
}
public String getText()
{
return keyword.getText();
}
Button getCloseButton()
{
return closeButton;
}
}
Full Code including DB on GitHub

Related

Database is overwriting. Last entry from json is written in database and all other entry is overwritten. Showing only last Entry of Json File

PlayerService
this is srvice class of my boot app.
package io.anuj.springbootquickstart.topic;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class PlayerService {
#Autowired
private PlayerRespository playerRespository;
// private List<Topic> topics = new ArrayList<> (Arrays.asList(
// new Topic("Spring","Spring Framework","SpringFramework Description"),
// new Topic("Core","Core Framework","CoreFramework Description"),
// new Topic("JavaScript","JavaScript Framework","JavaScript Description")));
public List<Player> getAllPlayer(){
List<Player> player = new ArrayList();
playerRespository.findAll()
.forEach(player::add); //lambda expressions
return player;
}
public Player getPlayer(Long id){
//return topics.stream().filter(t -> t.getId().equals(id).findFirst().get());
return playerRespository.findOne(id);
}
public void addPlayer(Player player) {
playerRespository.save(player);
}
public void updatePlayer(Long id, Player player) {
playerRespository.save(player);
}
public void deletePlayer(Long id) {
//topics.removeIf(t -> t.getId().equals(id));
playerRespository.delete(id);
}
}
PLayerRepository
this is player repository of my app.
package io.anuj.springbootquickstart.topic;
import org.springframework.data.repository.CrudRepository;
public interface PlayerRespository extends CrudRepository <Player, Long>{
//crud repository-logic of any entity class
//getallTopic()
//gettopic(string id)
//update topic(topic t)
//deletetopic(string id)
}
PLayerController
this is player controller
package io.anuj.springbootquickstart.topic;
import java.io.FileReader;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
//wherever rest controller is written it will give json as output send back as a HTTP response
public class PlayerController {
#Autowired
private PlayerService playerService;
//get request by default
#RequestMapping("/player")
public List<Player> getallPlayer(){
return playerService.getAllPlayer();
}
//get request
#RequestMapping("/player/{id}")
public Player getPlayer(#PathVariable Long id){
return playerService.getPlayer(id);
}
//
#RequestMapping(method=RequestMethod.GET, value= "/getplayer")
public void addAllPlayer(){
Player player = new Player();
JSONParser parser = new JSONParser();
try {
Object ob = parser.parse(new FileReader("/home/bridgeit/Desktop/P.D-anuj/Json/newPlayerInfo.json"));
JSONObject object = (JSONObject) ob;
JSONArray data = (JSONArray) object.get("Playersinfo");
for (int i = 0; i < data.size(); i++)
{
JSONObject itemObj = (JSONObject) data.get(i);
Object nameObj = itemObj.get("player_name");
String playerName = (String) nameObj;
player.setPlayer_name(playerName);
Object imgObject = itemObj.get("player_img_url");
String playerPic = (String) imgObject;
player.setPlayer_img_url(playerPic);
Object roleObj = itemObj.get("player_role");
String roleName = (String) roleObj;
player.setPlayer_role(roleName);
Object battingStyleObj = itemObj.get("player_batting_style");
String battingStyleName = (String) battingStyleObj;
player.setPlayer_batting_style(battingStyleName);
Object bowlingObj = itemObj.get("player_bowling_style");
String bowlingName = (String) bowlingObj;
player.setPlayer_bowling_style(bowlingName);
Object nationalityObj = itemObj.get("player_nationality");
String nationalityName = (String) nationalityObj;
player.setPlayer_nationality(nationalityName);
Object dobObj = itemObj.get("player_dob");
String dobName = (String) dobObj;
player.setPlayer_dob(dobName);
Object teamIdObj = itemObj.get("team_id");
String teamIdName = (String) teamIdObj;
player.setTeam_id(teamIdName);
playerService.addPlayer(player);
}
} catch (Exception e) {
System.out.println(e);
}
}
/*#RequestMapping(method=RequestMethod.PUT, value= "/player/{id}")
public void updatePlayer(#RequestBody Player player,#PathVariable String id){
playerService.updatePlayer(id,player);
}
#RequestMapping(method=RequestMethod.DELETE, value= "/player/{id}")
public void deletePlayer(#PathVariable String id){
playerService.deletePlayer(id);
}*/
}
this is POJO class
Player.java
package io.anuj.springbootquickstart.topic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
#Entity
/*#Table(name = "Player")*/
public class Player {
/*#Id
#GenericGenerator(name = "gene", strategy = "increment")
#GeneratedValue(generator = "gene")
#Column(name = "id")
private Long id;*/
#Id
#GenericGenerator(name = "gene", strategy = "increment")
#GeneratedValue(generator = "gene")
private long id;
private String team_id;
/*#Column(name = "name")*/
private String player_name;
/*#Column(name = "display_picture")*/
private String player_img_url;
/*#Column(name = "role")*/
private String player_role;
public Player(long id, String team_id, String player_name, String player_img_url, String player_role,
String player_batting_style, String player_bowling_style, String player_nationality, String player_dob) {
super();
this.id = id;
this.team_id = team_id;
this.player_name = player_name;
this.player_img_url = player_img_url;
this.player_role = player_role;
this.player_batting_style = player_batting_style;
this.player_bowling_style = player_bowling_style;
this.player_nationality = player_nationality;
this.player_dob = player_dob;
}
/* #Column(name = "batting_style")*/
private String player_batting_style;
/*#Column(name = "bowling_style")*/
private String player_bowling_style;
/*#Column(name = "nationality")*/
private String player_nationality;
/*#Column(name = "dob")*/
private String player_dob;
/*#Column(name = "teamId")*/
public Player(){
}
public String getTeam_id() {
return team_id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setTeam_id(String team_id) {
this.team_id = team_id;
}
public String getPlayer_name() {
return player_name;
}
public void setPlayer_name(String player_name) {
this.player_name = player_name;
}
public String getPlayer_img_url() {
return player_img_url;
}
public void setPlayer_img_url(String player_img_url) {
this.player_img_url = player_img_url;
}
public String getPlayer_role() {
return player_role;
}
public void setPlayer_role(String player_role) {
this.player_role = player_role;
}
public String getPlayer_batting_style() {
return player_batting_style;
}
public void setPlayer_batting_style(String player_batting_style) {
this.player_batting_style = player_batting_style;
}
public String getPlayer_bowling_style() {
return player_bowling_style;
}
public void setPlayer_bowling_style(String player_bowling_style) {
this.player_bowling_style = player_bowling_style;
}
public String getPlayer_nationality() {
return player_nationality;
}
public void setPlayer_nationality(String player_nationality) {
this.player_nationality = player_nationality;
}
public String getPlayer_dob() {
return player_dob;
}
public void setPlayer_dob(String player_dob) {
this.player_dob = player_dob;
}
/*public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}*/
/*public Player(Long id, String team_id, String player_name, String player_img_url, String player_role,
String player_batting_style, String player_bowling_style, String player_nationality, String player_dob) {
super();
this.id = id;
this.team_id = team_id;
this.player_name = player_name;
this.player_img_url = player_img_url;
this.player_role = player_role;
this.player_batting_style = player_batting_style;
this.player_bowling_style = player_bowling_style;
this.player_nationality = player_nationality;
this.player_dob = player_dob;
}
*/
}
When i execute from json file it shows only last entry of json file. JSON file contains around 150 players but in databse is shows only last entry of the player. i think all the data is getting overwritten. Only last entry is shown of that json file in database. That is last player. Only one player which is last in json is there in database.
It's a little difficult to tell because you have a lot of commented out code that makes things harder to follow, but I think it is because of where you are creating the Player in your controller. Since you're doing this:
Player player = new Player()
outside of the loop, and Java is pass by value of reference, after the first time you addPlayer, you're just updating the same player with new data each time. You could confirm this if you simply debug your code and see if player has an ID after the first save call.
You'd probably want to do this to fix it:
for (int i = 0; i < data.size(); i++) {
Player player = new Player();
// rest of your code here
}

URLEncoder to search with multiple words

Below is library app. In its current state, the app is only able to search for single words. Searches like "Harry Potter" yield no result. I was told to use an URLEncoder but I tried and even that didn't work. Below are my java files.'
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Books>>, SearchView.OnQueryTextListener {
LoaderManager loaderManager;
String mQuery;
SearchView mSearchView;
MenuItem mMenuSearchItem;
private static final String LOG_TAG = MainActivity.class.getName();
private static final String GOOGLE_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?maxResults=40&q=";
private String url = GOOGLE_REQUEST_URL + "android";
private static final int BOOK_LOADER_ID = 1;
private BookAdapter adapter;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView bookListView = (ListView) findViewById(R.id.list);
adapter = new BookAdapter(this, new ArrayList<Books>());
bookListView.setAdapter(adapter);
loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Books currentBook = adapter.getItem(position);
Uri bookUri = Uri.parse(currentBook.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
startActivity(websiteIntent);
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
#Override
public boolean onQueryTextSubmit(String query) {
if(isOnline()){
url = GOOGLE_REQUEST_URL + query;
loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
}else{
Toast.makeText(this, "No Internet Connection Found!", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mQuery = newText;
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
mMenuSearchItem = menu.findItem(R.id.menu_search);
mSearchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
if (mSearchView != null) {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean queryTextFocused) {
if (!queryTextFocused) {
if (TextUtils.isEmpty(mQuery))
adapter.clear();
}
}
});
}
return true;
}
#Override
public Loader<List<Books>> onCreateLoader(int i, Bundle bundle) {
return new BookLoader(this, url);
}
#Override
public void onLoadFinished(Loader<List<Books>> loader, List<Books> books) {
adapter.clear();
if (books != null && !books.isEmpty()) {
adapter.addAll(books);
}
}
#Override
public void onLoaderReset(Loader<List<Books>> loader) {
adapter.clear();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
BookUtils.java
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public final class BookUtils {
private static final String LOG_TAG = BookUtils.class.getSimpleName();
private BookUtils() {}
public static List<Books> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {jsonResponse = makeHttpRequest(url);}
catch (IOException e) {Log.e(LOG_TAG, "Problem making the HTTP request.", e);}
List<Books> books = extractFeatureFromJson(jsonResponse);
return books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {url = new URL(stringUrl);}
catch (MalformedURLException e) {Log.e(LOG_TAG, "Problem building the URL ", e);}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {return jsonResponse;}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());}
}
catch (IOException e) {Log.e(LOG_TAG, "Problem retrieving the book JSON results.", e);}
finally {
if (urlConnection != null) {urlConnection.disconnect();}
if (inputStream != null) {inputStream.close();}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Books> extractFeatureFromJson(String bookJSON) {
if (TextUtils.isEmpty(bookJSON)) {return null;}
List<Books> books = new ArrayList<>();
try {
JSONObject jsonResponse = new JSONObject(bookJSON);
JSONArray booksArray = jsonResponse.getJSONArray("items");
for (int i = 0; i < booksArray.length(); i++) {
JSONObject currentBook = booksArray.getJSONObject(i);
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
JSONArray authorsArray = volumeInfo.getJSONArray("authors");
String title = "", publisher = "", publishedDate = "", language = "", pageCount = "", printType = "", maturityRating = "", authors = "";
if(volumeInfo.has("title")){
language = volumeInfo.getString("language");
}
for (int j = 0; j < authorsArray.length(); j++) {
if (volumeInfo.has("authors")){
authors = authorsArray.getString(j);
}
}
if(volumeInfo.has("publisher")){
publisher = volumeInfo.getString("publisher");
}
if(volumeInfo.has("publishedDate")){
publishedDate = volumeInfo.getString("publishedDate");
}
if(volumeInfo.has("language")){
language = volumeInfo.getString("language");
}
if(volumeInfo.has("pageCount")){
pageCount = volumeInfo.getString("pageCount");
}
if(volumeInfo.has("printType")){
printType = volumeInfo.getString("printType");
}
if(volumeInfo.has("maturityRating")){
maturityRating = volumeInfo.getString("maturityRating");
}
Books book = new Books(title, authors, publisher, publishedDate, language, pageCount, printType, maturityRating);
books.add(book);
}
}
catch (JSONException e) {Log.e("QueryUtils", "Problem parsing the book JSON results", e);}
return books;
}
}
Books.java
public class Books {
private String mTitle;
private String mAuthors;
private String mPublisher;
private String mPublishingDate;
private String mLanguage;
private String mCount;
private String mPrintType;
private String mMaturityRating;
private String mURL;
public Books(String title, String authors, String publisher, String publishingDate, String language, String count, String printType, String maturityRating) {
mTitle = title;
mAuthors = authors;
mPublisher = publisher;
mPublishingDate = publishingDate;
mLanguage = language;
mCount = count;
mPrintType = printType;
mMaturityRating = maturityRating;
}
public String getTitle() {return mTitle;}
public String getAuthors(){return mAuthors;}
public String getPublisher(){return mPublisher;}
public String getPublishedDate(){return mPublishingDate;}
public String getLanguage(){return mLanguage;}
public String getCount(){return mCount;}
public String getPrintType(){return mPrintType;}
public String getMaturityRating(){return mMaturityRating;}
public String getUrl() {return mURL;}
}
BookLoader.java
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
public class BookLoader extends AsyncTaskLoader<List<Books>> {
private static final String LOG_TAG = BookLoader.class.getName();
private String mUrl;
public BookLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {forceLoad();}
#Override
public List<Books> loadInBackground() {
if (mUrl == null) {return null;}
List<Books> books = BookUtils.fetchBookData(mUrl);
return books;
}
}
BookAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Books> {
public BookAdapter(Context context, List<Books> books) {
super(context, 0, books);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {listItemView = LayoutInflater.from(getContext()).inflate(R.layout.book_list_item, parent, false);}
Books currentBook = getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.book_title);
title.setText(currentBook.getTitle());
TextView authors = (TextView) listItemView.findViewById(R.id.book_author);
authors.setText(currentBook.getAuthors());
TextView publisher = (TextView) listItemView.findViewById(R.id.book_publisher);
publisher.setText(currentBook.getPublisher());
TextView publishingDate = (TextView) listItemView.findViewById(R.id.book_publishing_date);
publishingDate.setText(currentBook.getPublishedDate());
TextView language = (TextView) listItemView.findViewById(R.id.book_language);
language.setText(currentBook.getLanguage());
TextView pageCount = (TextView) listItemView.findViewById(R.id.book_page_count);
pageCount.setText(currentBook.getCount());
TextView printType = (TextView) listItemView.findViewById(R.id.book_print_type);
printType.setText(currentBook.getPrintType());
TextView maturityRating = (TextView) listItemView.findViewById(R.id.book_maturity_rating);
maturityRating.setText(currentBook.getMaturityRating());
return listItemView;
}
}
On my onQueryTextSubmit method, I tried replacing url = GOOGLE_REQUEST_URL + query; with:
Uri.Builder uriBuilder = Uri.parse(GOOGLE_REQUEST_URL).buildUpon().appendQueryParameter("q", query);
url = uriBuilder.toString();
But it didn't work.

My tableview is displaying blank rows [duplicate]

This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 7 years ago.
I am new to JavaFX and I have been trying to implement this code for displaying data from MySQL database in a TableView. The problem is that when I run the code I get blank rows and I don't know why.
Here is my code for the class:
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
public class FXMLPatientsMasterController implements Initializable {
/*
mysql connection variables
*/
Connection conn=null;
PreparedStatement pat=null;
ResultSet rs=null;
private ObservableList<PatientDetails> patients;
#FXML
private TableView Table_Patients;
#FXML
private TableColumn patientID;
#FXML
private TableColumn Name;
#FXML
private TableColumn Surname;
#FXML
private TableColumn pnationalID;
#FXML
private TableColumn psex;
#FXML
private TableColumn pDOB;
// Some code here
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
conn = PMS263MySqlConnection.ConnectDB();
try {
patients = FXCollections.observableArrayList();
rs = conn.createStatement().executeQuery("select * from patients");
while (rs.next()) {
patients.add(new PatientDetails(rs.getInt("PatientId"),
rs.getString("fName"), rs.getString("Surname"), rs.getString("National_ID"), rs.getString("Sex"), rs.getString("DOB")));
}
patientID.setCellValueFactory(new PropertyValueFactory("PatientId"));
Name.setCellValueFactory(new PropertyValueFactory("fName"));
Surname.setCellValueFactory(new PropertyValueFactory("Surname"));
pnationalID.setCellValueFactory(new PropertyValueFactory("National_ID"));
psex.setCellValueFactory(new PropertyValueFactory("Sex"));
pDOB.setCellValueFactory(new PropertyValueFactory("DOB"));
Table_Patients.setItems(null);
Table_Patients.setItems(patients);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class PatientDetails {
private final SimpleIntegerProperty Patientid;
private final StringProperty Pname;
private final StringProperty Psurname;
private final StringProperty Pnationalid;
private final StringProperty Psex;
private final StringProperty Pdob;
private PatientDetails(int patientid, String pname, String psurname, String pnationalid, String psex, String pdob) {
this.Patientid = new SimpleIntegerProperty(patientid);
this.Pname = new SimpleStringProperty(pname);
this.Psurname = new SimpleStringProperty(psurname);
this.Pnationalid = new SimpleStringProperty(pnationalid);
this.Psex= new SimpleStringProperty(psex);
this.Pdob = new SimpleStringProperty(pdob);
}
public SimpleIntegerProperty patientidProperty() {
return Patientid ;
}
public StringProperty pnameProperty() {
return Pname;
}
public StringProperty psurnameProperty() {
return Psurname;
}
public StringProperty pnationalidProperty() {
return Pnationalid;
}
public StringProperty psexPsexProperty() {
return Psex;
}
public StringProperty pdobProperty() {
return Pdob;
}
}
}
Assuming your database query works, you the property names wrong:
If the property "getter" is named myNameProperty() you need to use new PropertyValueFactory("myName").
Either the property "getters" need to be renamed or the strings used with the value factories:
patientID.setCellValueFactory(new PropertyValueFactory("patientId"));
Name.setCellValueFactory(new PropertyValueFactory("pname"));
Surname.setCellValueFactory(new PropertyValueFactory("psurname"));
pnationalID.setCellValueFactory(new PropertyValueFactory("pnationalid"));
psex.setCellValueFactory(new PropertyValueFactory("psex"));
pDOB.setCellValueFactory(new PropertyValueFactory("pdob"));
...
public SimpleIntegerProperty patientIdProperty() {
return Patientid;
}
public StringProperty pnameProperty() {
return Pname;
}
public StringProperty psurnameProperty() {
return Psurname;
}
public StringProperty pnationalidProperty() {
return Pnationalid;
}
public StringProperty psexProperty() {
return Psex;
}
public StringProperty pdobProperty() {
return Pdob;
}

How to create new records directly in javafx TableView?

I am using JDBC and MySQL.
I can create Text Fields and have their contents entered as records in a MySQL table (and then populate the corresponding javafx TableView).
I would like to know if it is possible for the user to directly add new records to the TableView by clicking on TableView cells.
Would it be a good practice to do so? The TableView shows details of sale invoice like item name, quantity sold, rate etc.
I posted this example a while ago, but I can't find it now.
One way to do this is to put a "blank" item at the end of the table's list of items. Register a listener so that if the user edits that value a new blank item is added at the end.
Here's an example (it also has some editing features that are different to the default).
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TableViewSingleClickEditTest extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
table.setEditable(true);
TableColumn<Person, String> firstNameCol = createCol("First Name", Person::firstNameProperty, 150);
TableColumn<Person, String> lastNameCol = createCol("Last Name", Person::lastNameProperty, 150);
TableColumn<Person, String> emailCol = createCol("Email", Person::emailProperty, 200);
TableColumn<Person, Void> indexCol = new TableColumn<>("");
indexCol.setCellFactory(col -> {
TableCell<Person, Void> cell = new TableCell<>();
cell.textProperty().bind(Bindings.createStringBinding(() -> {
if (cell.getIndex() >= 0 && cell.getIndex() < table.getItems().size() - 1) {
return Integer.toString(cell.getIndex() + 1);
} else if (cell.getIndex() == table.getItems().size() - 1) {
return "*" ;
} else return "" ;
}, cell.indexProperty(), table.getItems()));
return cell ;
});
indexCol.setPrefWidth(32);
table.getItems().addAll(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com")
);
ChangeListener<String> lastPersonTextListener = new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> obs, String oldText, String newText) {
if (oldText.isEmpty() && ! newText.isEmpty()) {
Person lastPerson = table.getItems().get(table.getItems().size() - 1);
lastPerson.firstNameProperty().removeListener(this);
lastPerson.lastNameProperty().removeListener(this);
lastPerson.emailProperty().removeListener(this);
Person newBlankPerson = new Person("", "", "");
newBlankPerson.firstNameProperty().addListener(this);
newBlankPerson.lastNameProperty().addListener(this);
newBlankPerson.emailProperty().addListener(this);
table.getItems().add(newBlankPerson);
}
}
};
Person blankPerson = new Person("", "", "");
blankPerson.firstNameProperty().addListener(lastPersonTextListener);
blankPerson.lastNameProperty().addListener(lastPersonTextListener);
blankPerson.emailProperty().addListener(lastPersonTextListener);
table.getItems().add(blankPerson);
table.getColumns().add(indexCol);
table.getColumns().add(firstNameCol);
table.getColumns().add(lastNameCol);
table.getColumns().add(emailCol);
VBox root = new VBox(15, table);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
private TableColumn<Person, String> createCol(String title,
Function<Person, ObservableValue<String>> mapper, double size) {
TableColumn<Person, String> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> mapper.apply(cellData.getValue()));
Callback<TableColumn<Person, String>, TableCell<Person, String>> defaultCellFactory
= TextFieldTableCell.forTableColumn();
col.setCellFactory(column -> {
TableCell<Person, String> cell = defaultCellFactory.call(column);
cell.setOnMouseClicked(e -> {
if (! cell.isEditing() && ! cell.isEmpty()) {
cell.getTableView().edit(cell.getIndex(), column);
}
});
return cell ;
});
col.setPrefWidth(size);
return col ;
}
public class Person {
private final StringProperty firstName = new SimpleStringProperty(this, "firstName");
private final StringProperty lastName = new SimpleStringProperty(this, "lastName");
private final StringProperty email = new SimpleStringProperty(this, "email");
public Person(String firstName, String lastName, String email) {
this.firstName.set(firstName);
this.lastName.set(lastName);
this.email.set(email);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final java.lang.String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final java.lang.String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final java.lang.String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final java.lang.String lastName) {
this.lastNameProperty().set(lastName);
}
public final StringProperty emailProperty() {
return this.email;
}
public final java.lang.String getEmail() {
return this.emailProperty().get();
}
public final void setEmail(final java.lang.String email) {
this.emailProperty().set(email);
}
}
public static void main(String[] args) {
launch(args);
}
}

dump csv file into db causing error connection closed

package com.test.mysql;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.test.mysql.FileReaderer;
public class automateImport {
/**
* #param args
* #throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException {
/* Class.forName("com.mysql.jdbc.Driver");
try {
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
FileReaderer fr = null;
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
System.out.println("f1"+fl.getPath());
if (fl.canRead()){
System.out.println("f2"+fl.getPath());
fr = new FileReaderer(fl);
break;
}
else{
System.out.println("Error:Directory does not exists");
}
}
}
}
package com.test.mysql;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileReaderer {
private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
private final File txtFolder;
Connection con = null;
Statement stmt = null;
public FileReaderer(File txtFolder) {
this.txtFolder = txtFolder;
readFiles();
}
public List<Person> readFiles() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final List<Person> people = new LinkedList<>();
System.out.println("txt folder"+txtFolder.getPath());
for (final File txtFile : txtFolder.listFiles()) {
if (txtFilter.accept(txtFile)) {
System.out.println("txt Files " +txtFile.getName());
people.addAll(readFile(txtFile));
}
}
System.out.println("File Final List==>"+people);
insertData(con,stmt,people);
return people;
}
private List<Person> readFile(File txtFile) {
try (final Scanner scanner = new Scanner(txtFile)) {
/* scanner.useDelimiter(lineBreakPattern);
final Person person = new Person();
while (scanner.hasNext()) {
final String line = scanner.next();
final Matcher matcher = linePattern.matcher(line);
if (matcher.matches()) {
switch (matcher.group(1).toUpperCase()) {
case "ID":
person.setId(Integer.parseInt(matcher.group(2)));
break;
case "NAME":
person.setName(matcher.group(2));
break;
default:
throw new IOException("Illegal line '" + matcher.group() + "'.");
}
}
}*/
BufferedReader br = new BufferedReader(new FileReader(txtFile));
String currentLine = br.readLine();
List<Person> processPersonList = new ArrayList<Person>();
while (currentLine != null) {
String[] tokens = currentLine.split(",");
Person finalPerson = new Person();
finalPerson.setFirstName(tokens[0]);
finalPerson.setLastName(tokens[1]);
finalPerson.setSIN(tokens[2]);
currentLine = br.readLine();
processPersonList.add(finalPerson);
}
System.out.println("final list==>"+processPersonList);
br.close();
return processPersonList;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void insertData(Connection con,Statement stmt,List<Person> pp){
System.out.print("\nInserting records into table...");
try{
for(Person pr:pp){
System.out.println("First Name " +pr.getFirstName()+" Second Name " +pr.getLastName()+"SIN Name " +pr.getSIN());
String sql = "INSERT INTO employee(first_name, last_name,sin) values (?,?,?)" ;
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString (1, pr.getFirstName());
preparedStmt.setString (2, pr.getLastName());
preparedStmt.setString (3, pr.getSIN());
preparedStmt.execute();
}
System.out.println(" SUCCESS!\n");
con.close();
} catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
package com.test.mysql;
public class Person {
private String firstName;
private String lastName;
private String SIN;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSIN() {
return SIN;
}
public void setSIN(String sIN) {
SIN = sIN;
}
//
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
}
package com.test.readfile;
import java.util.Date;
public class Employee {
private long id;
private String firstName;
private String lastName;
private Double salary;
private String sin;
private Date dob;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public String getSin() {
return sin;
}
public void setSin(String sin) {
this.sin = sin;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
package com.test.readfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileReaderer {
private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
private final File txtFolder;
Connection con = null;
Statement stmt = null;
public FileReaderer(File txtFolder) {
this.txtFolder = txtFolder;
readFiles();
}
public List<Employee> readFiles() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "ptlusrapp$246");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final List<Employee> people = new LinkedList<>();
System.out.println("txt folder"+txtFolder.getPath());
for (final File txtFile : txtFolder.listFiles()) {
if (txtFilter.accept(txtFile)) {
System.out.println("txt Files " +txtFile.getName());
people.addAll(readFile(txtFile));
}
}
System.out.println("File Final List==>"+people);
insertData(con,stmt,people);
return people;
}
private List<Employee> readFile(File txtFile) {
try (final Scanner scanner = new Scanner(txtFile)) {
/* scanner.useDelimiter(lineBreakPattern);
final Employee Employee = new Employee();
while (scanner.hasNext()) {
final String line = scanner.next();
final Matcher matcher = linePattern.matcher(line);
if (matcher.matches()) {
switch (matcher.group(1).toUpperCase()) {
case "ID":
Employee.setId(Integer.parseInt(matcher.group(2)));
break;
case "NAME":
Employee.setName(matcher.group(2));
break;
default:
throw new IOException("Illegal line '" + matcher.group() + "'.");
}
}
}*/
BufferedReader br = new BufferedReader(new FileReader(txtFile));
String currentLine = br.readLine();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date convertedDate = null;
String splitterString="\\s";
List<Employee> processEmployeeList = new ArrayList<Employee>();
while (currentLine != null) {
if(currentLine.indexOf(",")>-1)
splitterString = ",";
else
splitterString = "\\|";
String[] tokens = currentLine.split(splitterString);
Employee finalEmployee = new Employee();
finalEmployee.setId(Long.parseLong(tokens[0]));
finalEmployee.setFirstName(tokens[1]);
finalEmployee.setLastName(tokens[2]);
finalEmployee.setSalary(Double.parseDouble(tokens[3]));
finalEmployee.setSin(tokens[4]);
try {
convertedDate = formatter.parse(tokens[5]);
finalEmployee.setDob(convertedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// finalEmployee.setDob(convertedDate);
currentLine = br.readLine();
processEmployeeList.add(finalEmployee);
}
System.out.println("final list==>"+processEmployeeList);
br.close();
return processEmployeeList;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void insertData(Connection con,Statement stmt,List<Employee> pp){
System.out.print("\nInserting records into table...");
try{
for(Employee pr:pp){
System.out.println("First Name " +pr.getFirstName()+" Second Name " +pr.getLastName()+"SIN Name " +pr.getSin() +"DOB: "+pr.getDob());
//String sql = "INSERT INTO employee(first_name, last_name,sin) values (?,?,?)" ;
String sql = "INSERT INTO employee(id,first_name,last_name,salary,sin,dob) values (?,?,?,?,?,?)" ;
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setLong(1,pr.getId());
preparedStmt.setString (2, pr.getFirstName());
preparedStmt.setString (3, pr.getLastName());
preparedStmt.setDouble(4, pr.getSalary());
preparedStmt.setString (5, pr.getSin());
java.sql.Date sqlDate = new java.sql.Date(pr.getDob().getTime());
preparedStmt.setDate(6, sqlDate);
preparedStmt.execute();
}
System.out.println(" SUCCESS!\n");
con.close();
} catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
package com.test.readfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AutomateImport {
/**
* #param args
* #throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException {
/* Class.forName("com.mysql.jdbc.Driver");
try {
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
FileReaderer fr = null;
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
System.out.println("f1"+fl.getPath());
if (fl.canRead()){
System.out.println("f2"+fl.getPath());
fr = new FileReaderer(fl);
break;
}
else{
System.out.println("Error:Directory does not exists");
}
}
}
}