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");
}
}
}
}
Related
I have a database "workschedule" and a table "employee". But when I try to display data from this table, I can see only the last record from the table
ObservableList<Variable> employeeObList = FXCollections.observableArrayList();
columnId.setCellValueFactory(new PropertyValueFactory<Variable, Integer>("id"));
columnName.setCellValueFactory(new PropertyValueFactory<Variable, String>("name"));
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM workchedule.employees;");
try {
while (rs.next()) {
employeeObList.add(new Variable(rs.getInt("id"), rs.getString("name")));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
finally {
rs.close();
conn.close();
}
employeeTableView.setItems(employeeObList);
#FXML private TableView<Variable> employeeTableView;
#FXML private TableColumn<Variable, Integer> columnId;
#FXML private TableColumn<Variable, String> columnName;
Variable - a class where I save variables with getters and setters
Image from MySQL
Image from a scene
So using jdbc I always do it like this:
Connector responsible for connecting to the DB:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connector {
public Connection con = null;
final String URL = "jdbc:mysql://localhost:3306/dbname";
final String USERNAME = "username";
// Not so safe but easy
final String PASSWORD = "1234";
/*
* Adds DB Connection
*/
public void add() {
try {
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException se) {
se.printStackTrace();
}
}
}
Then I use a DAO to get the data from the database:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import application.controller.Connector;
public class Dao{
Connector c = new Connector();
public ArrayList<Model> selectAllData() {
ArrayList<Model> list = new ArrayList<>();
try {
c.add();
PreparedStatementstmt = c.con.prepareStatement("SELECT id FROM db.table");
ResultSet result = stmt.executeQuery(
);
while (result.next()) {
Model model= new Model();
//here set all the attributes
model.setId(result.getInt("id"));
list.add(model);
}
} catch (SQLException se) {
se.printStackTrace();
} finally {
if (c.con != null) {
try {
c.con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
return list;
}
Then in the JavaFX Controller I can just call the DAO function.
#FXML
public void initialize() {
initTable();
}
/*
* Sets up the table and maps the values
*/
#SuppressWarnings("unchecked")
private void initTable() {
idCol.setCellValueFactory(new PropertyValueFactory<Model, Integer>("id"));
loadTableData();
}
/*
* Loads all the data into table
*/
private void loadTableData() {
models = dao.selectAllData();
data = FXCollections.observableArrayList(models);
table.setItems(data);
}
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
This is the Database connection java file which will connect to mysql local databse
package com.example.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
public Connection getConnection() throws Exception
{
Connection connection = null;
try
{
String connectionURL = "jdbc:mysql://localhost:3306/test1";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL,
"root", "root");
}
catch (Exception e)
{
e.printStackTrace();
}
return connection;
}
}
This is the web service file for getting and adding up the candidates using com.perpule/hello/plain to get simple hello message & /getCandidate to get all list of candidates
package com.example.webservice;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import org.apache.http.HttpServerConnection;
import com.example.dao.Candidate;
import com.example.model.CandidateManager;
import com.google.gson.Gson;
#Path("/hello")
public class SayHello {
ArrayList<Candidate> candidateArr= new ArrayList<Candidate>();
#Context
UriInfo uriInfo;
#Context
Request request;
#GET
#Path("/plain")
#Produces(MediaType.TEXT_PLAIN)
public String sayHelloPlain()
{
return "hello ";
}
#GET
#Path("/candidates")
#Produces(MediaType.TEXT_PLAIN)
public String CandidateList()
{
String candidates=null ;
try {
candidateArr= new CandidateManager().getCandidates();
Gson gson=new Gson();
candidates=gson.toJson(candidateArr);
}catch (Exception e) {
e.printStackTrace();
}
return candidates;
}
#POST
#Path("/addCandidates")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_PLAIN)
public void submitCandidates(#FormParam("name") String name,
#FormParam("pass") String pass,
#FormParam("phone") String phone, #FormParam("email") String
email,#FormParam("city") String city)
{
Candidate candidate =new Candidate();
candidate.setName(name);
candidate.setPass(pass);
candidate.setPhone(phone);
candidate.setCity(city);
candidate.setEmail(email);
CandidateManager candidateManager=new CandidateManager();
try {
candidateManager.addCandidates(candidate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Model class
package com.example.model;
import java.sql.Connection;
import java.util.ArrayList;
import com.example.dao.Access;
import com.example.dao.Candidate;
import com.example.dao.Database;
public class CandidateManager {
public ArrayList<Candidate> getCandidates() throws Exception
{
ArrayList<Candidate> candidateList = new ArrayList<Candidate>();
Database db= new Database();
Connection con=db.getConnection();
Access access=new Access();
candidateList=access.getCandidates(con);
return candidateList;
}
public void addCandidates(Candidate candidate) throws Exception
{
// ArrayList<Candidate> candidateData = new ArrayList<Candidate>();
Database db= new Database();
Connection con=db.getConnection();
new Access().addCandidates(con,candidate);
}
}
This is the DAO class for execueteQuery purpose : code for addCandidate is here
package com.example.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class Access {
ResultSet rs=null;
public ArrayList<Candidate> getCandidates(Connection connection) throws
SQLException{
ArrayList<Candidate> candidateList =new ArrayList<Candidate>();
String sql="select * from candidate";
PreparedStatement psmt =connection.prepareStatement(sql);
rs=psmt.executeQuery();
try {
while(rs.next())
{
Candidate candidateObj = new Candidate();
candidateObj.setName(rs.getString("name"));
candidateObj.setPass(rs.getString("pass"));
candidateObj.setEmail(rs.getString("email"));
candidateObj.setPhone(rs.getString("phone"));
candidateObj.setCity(rs.getString("city"));
candidateList.add(candidateObj);
}
}catch (SQLException e) {
e.printStackTrace();
}
return candidateList;
}
public void addCandidates(Connection connection, Candidate candidate)
throws SQLException
{
String sql="insert into candidate values(?,?,?,?,?)";
try {
PreparedStatement preparedStatement
=connection.prepareStatement(sql);
// preparedStatement.executeQuery();
preparedStatement.setString(1, candidate.name);
preparedStatement.setString(2, candidate.pass);
preparedStatement.setString(3, candidate.phone);
preparedStatement.setString(4, candidate.city);
preparedStatement.setString(5, candidate.phone);
preparedStatement.execute();
connection.close();
}catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
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.
I am pulling my hair out over this. After numerous tutorials, I thought I found the perfect one (7th to be exact. But after following the tutorial, I found out that JSONparse is deprecated. Can someone please give me a solution for this. I just want to read an array from the url and populate a listview.
The array is:
{ "lotInfo":[{"lot":"A","spaces":"198","rates":"3.25"},
{"lot":"B","spaces":"165","rates":"7.50"}]}
MainActivity.Java:
package com.example.sahan.wtf;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
private Context context;
private static String url = "http://192.168.0.199/get_info.php";
private static final String lot = "lot";
private static final String spaces = "spaces";
private static final String rates = "rates";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(ListActivity activity) {
Log.i("1", "Called");
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { lot, spaces, rates }, new int[] { R.id.lot, R.id.spaces, R.id.rates });
setListAdapter(adapter);
lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vlot = c.getString(lot);
String vspaces = c.getString(spaces);
String vrates = c.getString(rates);
HashMap<String, String> map = new HashMap<String, String>();
map.put(lot, vlot);
map.put(spaces, vspaces);
map.put(rates, vrates);
jsonlist.add(map);
} catch (JSONException e)
{
e.printStackTrace();
}
}
return null;
}
}
}
JSONParser.Java:
package com.example.sahan.wtf;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("Error....", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return array;
}
}
The error I get is:
Error:(74, 13) error: cannot find symbol class JSONParse
It seems that you have a typo, instead of:
JSONParse jParser = new JSONParser();
Should be:
JSONParser jParser = new JSONParser();