Getting database values CODENAME ONE - java

I have an intermediate table that gets information from two other tables from the database (it gets their id), I'd like to show information of the other tables through that intermediate table in each of the others but it show me all of the information.
public showTheatreForm(Resources res, Theatre t) {
Toolbar tb=new Toolbar(true);
current=this;
setToolbar(tb);
getTitleArea().setUIID("Container");
setTitle("modifier actor");
getContentPane().setScrollVisible(false);
super.addSideMenu(res);
Label name = new Label((t.getName()));
Picker datePicker = new Picker();
datePicker.setDate(t.getRdate());
String datestring=(new SimpleDateFormat("yyyy-MM-dd")).format(datePicker.getDate());
Label date = new Label((datestring));
TextField description = new TextField((t.getDescription()));
TextField actors = new TextField((t.getTactor()));
//Label image = new Label((t.getImage()), "Image");
ImageViewer imavu;
try {
imavu = new ImageViewer(getImageFromServer(t.getImage()));
}
catch(Exception e) {
System.out.println(t.getImage());
imavu = new ImageViewer(res.getImage("s.png"));
}
description.setSingleLineTextArea(false);
actors.setSingleLineTextArea(false);
name.setUIID("NewsCenterLine");
date.setUIID("NewsCenterLine");
description.setUIID("NewsCenterLine");
imavu.setUIID("NewsCenterLine");
actors.setUIID("NewsCenterLine");
Label a = new Label("");
Label e = new Label ();
Container content = BoxLayout.encloseY(
e,a, (name),
createLineSeparator(), (actors),
createLineSeparator(),date,
createLineSeparator(), (description),
createLineSeparator(), (imavu)
);
add(content);
show();
}
And this is how I get it from the database:
public ArrayList<Theatre> ShowTheatre (){
ArrayList<Theatre> result=new ArrayList<>();
String url=Statics.BASE_URL+"/theatre/displayTheatre";
req.setUrl(url);
req.addResponseListener(new ActionListener<NetworkEvent>() {
#Override
public void actionPerformed(NetworkEvent evt) {
JSONParser Jsonp;
Jsonp=new JSONParser();
try{
Map<String,Object>mapTheatre= Jsonp.parseJSON(new CharArrayReader(new String(req.getResponseData()).toCharArray()));
List<Map<String,Object>> listofMaps = (List<Map<String,Object>>) mapTheatre.get("root");
for(Map<String,Object> obj : listofMaps)
{
Theatre th=new Theatre();
float id=Float.parseFloat(obj.get("id").toString());
String name=obj.get("name").toString();
String genre=obj.get("genre").toString();
String description=obj.get("description").toString();
String image=obj.get("image").toString();
String trailer=obj.get("trailer").toString();
String poster=obj.get("poster").toString();
String get=obj.get("theatreActors").toString();
th.setId((long)id);
th.setName(name);
th.setTactor(get);
System.out.println(get);
th.setDescription(description);
th.setImage(image);
th.setTrailer(trailer);
th.setPoster(poster);
th.setGenre(genre);
Map<String, Object> dd = (Map<String, Object>) obj.get("rdate");
float ll = Float.parseFloat(dd.get("timestamp").toString());
th.setRdate(new Date(((long) ll * 1000)));
}
result.add(th);
}
} catch (IOException ex) {
System.out.println(
"good");
}
}
});
NetworkManager.getInstance().addToQueueAndWait(req);
return result;
}
Result of the code
This is the result, but I only want to get the "name" and "date" or "description" from the intermediate table
My intermediate table
(the name of the table is theatreActors)

Related

Update the content of a ComboBox dynamically created in Javafx, from another ComboBox dynamically created

In a GridPane I am dynamically creating two ComboBox's. For the first ComboBox I am charging the items when the Scene is loaded. Then I want that when I perform an action in this ComboBox, the items of the other ComboBox are loaded according to the value selected.
ComboBox<String> combobox1 = loadItems();
ComboBox<String> combobox2 = new ComboBox<String>();
gridpane.add(combobox1, 0, 0);
gridpane.add(combobox2, 1, 0);
I've tried by using a listener, but it didn't seem to work:
combobox1.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
loadList(combobox2, newValue);
}
});
private void loadList(ComboBox<String> combobox, String value) {
combobox = getCorrespondingList(value);
}
public ComboBox<String> getCorrespondingList(String value) {
ComboBox<String> combobox = new ComboBox<String>();
ArrayList<String> list = new ArrayList<String>();
try {
String query = "select ... where Item = '" + value
+ "' order by c";
statement = connection.prepareStatement(query);
result = statement.executeQuery();
while (result.next()) {
list.add(result.getString(1));
}
}
catch (SQLException e) {
e.getMessage();
}
ObservableList<String> observableList = FXCollections.observableArrayList(list);
combobox.setItems(observableList);
return combobox;
}
I really appreciate any help.
Java is call by reference. Any assignment to a method parameter will only have an effect inside the method. Furthermore as far as I can tell you did create the ComboBox you want to modify earlier. Instead of creating a new ComboBox, just fill the modify the existing one:
private void loadList(ComboBox<String> combobox, String value) {
combobox.getItems().setAll(getCorrespondingList(value));
}
public List<String> getCorrespondingList(String value) {
ArrayList<String> list = new ArrayList<String>();
try {
// use PreparedStatement's placeholder functionality to avoid
// issues with quotes inside the string
String query = "SELECT ... WHERE Item = ? ORDER BY c";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, value);
// no need to keep this after the method exits
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace(System.err); // should provide more info in case an exception happens
}
return list;
}

search button not work with me

public Boolean load() {
Connection con = null;
PreparedStatement pre = null;
Boolean isexist = false;
try {
con = DBManager.getConnection();
String sql = "SELECT * FROM contacts WHERE mobile=?";
pre = con.prepareStatement(sql);
pre.setString(1, this.mobile);
ResultSet result = pre.executeQuery();
if (result.next()) {
isexist = true;
}
} catch (Exception e) {
} finally {
if (pre != null) {
try {
pre.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
}
}
}
return isexist;
}
// and in actionListner `
Contacts objj=new Contacts(this.mobile.getText());
if (objj.load())
{
this.name.setText("njkn");
this.mobile.setText("jbnlj");
this.address.setText("jnl");
this.email.setText("knkl");
} else
{
JOptionPane.showMessageDialog(null," error message");
}
I created 4 text fields in JFrame and I want when user put the mobile num then click on search button - display other information (name, email, address) but the it is display
You need to pass the mobile number to the load function as argument, otherwise you can't use it as a parameter for your search.
You need to somehow get the returned values back, either via return or with fields or smt.
You can use try with resources blocks for any autocloseable, like Connection or PreparedStatement.
I added more comments in the code.
// I use hashmap as a return value, the hashmap contains the values from the db
public static HashMap<String, String> load(String mobile) { // You need to pass the number you're looking for
String sql = "SELECT email, name, address FROM people WHERE mobile=?"; // You only need to return the columns you need
try (
Connection conn = DriverManager.getConnection(LOCATION);
PreparedStatement pre = conn.prepareStatement(sql)) { // try with ressources so that the connection and preparedstatement close automatically at the end
pre.setString(1, mobile); // enter the passed mobile variable in the query
ResultSet result = pre.executeQuery();
if (result.next()) {
// You need to return the values from the db somehow
HashMap<String, String> information = new HashMap<>();
information.put("email", result.getString("email")); // Get the value in the "email" column and store it with the "email" key
information.put("address", result.getString("address")); // Get the value in the "address" column and store it under "address" key
information.put("name", result.getString("name")); // Get the value in the "name" column and store it under "name" key
return information;
// You don't need to check if the values exist. If they don't exist it will just return null and you can check that when you call
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null; // return null if the values don't exist
}
// Sample method to build GUI
// I just used this to test everything was working, if you already have a GIU you don't need it
public void GUI() {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JLabel label = new JLabel("enter mobile number and click search");
JTextField name = new JTextField("name");
JTextField mobile = new JTextField("mobile");
JTextField address = new JTextField("address");
JTextField email = new JTextField("email");
JButton button = new JButton("Search");
button.addActionListener(e -> {
try { // try in case the method returns null
HashMap<String, String> information = load(mobile.getText());
// set the textfields with the returned values
email.setText(information.get("email"));
address.setText(information.get("address"));
name.setText(information.get("name"));
} catch (NullPointerException ex) { // catch the exception for when the entered number was invalid
label.setText("Invalid number"); // set error message
}
});
contentPane.add(label);
contentPane.add(mobile);
contentPane.add(name);
contentPane.add(email);
contentPane.add(address);
contentPane.add(button);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

Redirecting output to table in Java Swing

Newbie here, I have a problem, redirecting my output to a Jtable. The data is coming from a different class that does the real work which is Scanner.java.
With this said, Scanner.java could print what i want on console but since I added gui which am still learning I have created a new class MainFrame.java and I want search or scan result form Scanner.java to be populated in my JTable but am finding it hard to get the login.
Scanner.java
public void getCompanyProfile(){
Document sourceCode;
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
List<String> allLinks = results();
Document sourceCode;
int counter = 1;
for (String link : allLinks){
System.out.println("Link #:" + counter + " " + link);
sourceCode = PageVisitor.getHtmlSource(link);
Elements profile = sourceCode.select("div.company a.cd");
for (Element links : profile) {
String linkHref = links.attr("href");
System.out.println(linkHref);
setUserData(linkHref);
}
counter++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void setUserData(String url) throws IOException{
Extractor data = new Extractor();
// Scan each page alibaba initial result
data.setProfile(url);
this.companyName = data.getName();
this.country = data.getCountry();
HashSet<String> webites = data.getSellerUrls();
this.webAndEmail = new HashMap<String, HashSet<String>>();
HashSet<String> emails;
for (String webs: webites){
emails = data.emailExtractor(webs);
webAndEmail.put(webs, emails);
for (String anEmail : emails){
//This is the part i want to be displayed in my JTable Component.
System.out.println("Company=" +companyName + ", country=" + country + ", web="
+ webs + ", email=" + anEmail);
}
}
}
public String getProductName(){
return this.product;
}
public String getSource(){
return this.source;
}
public String getCompanyName(){
return this.companyName;
}
public String getCountry(){
return this.country;
}
public Map<String, HashSet<String>> getWebandEmail(){
return this.webAndEmail;
}
Finally, this is my MainFrame.java file below .
![JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnStart.setBounds(197, 166, 75, 29);
frame.getContentPane().add(btnStart);
//more statements like the above to establish all col. titles
String\[\] columnNames = {"Company Name", "Email", "Website", "Country", "Product", "Source"};
//Sample data to be printed
Object\[\]\[\] data =
{
{"Code Java Ltd", "bingo#codejava.net", "http://www.codejava.com", "Universe", "Polythecnic", "Ebay - B2B"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
resultTable = new JTable(model);
//resultTable.setBounds(37, 259, 553, 143);
resultTable.getColumnModel().getColumn(0).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(1).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(2).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(3).setPreferredWidth(150);
resultTable.getColumnModel().getColumn(4).setPreferredWidth(100);
resultTable.getColumnModel().getColumn(5).setPreferredWidth(100);
resultTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane( resultTable );
scrollPane.setBounds(37, 259, 806, 143);
frame.getContentPane().add( scrollPane );
//frame.add(resultTable);
JButton button = new JButton("Stop");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
button.setBounds(289, 166, 75, 29);
frame.getContentPane().add(button);][1]
This is what am trying to attain.
My other idea is to write the content to CSV from Scanner.java class file and read the file lated to populate the table. But like I said, am a beginner still don't think it would be that easy. So I kindly need someone to point me in the right direction.
Basically, you want to load your data from outside the Event Dispatching Thread, so as not to block the UI and make it "hang".
Next, you need some way for the Scanner to publish information it has generated, there are a number of ways you might do this, but the simplest might to use something like a Produce/Consumer Pattern.
With the Scanner acting as the producer, we need some way to inform the consumer that new content is available. Start with a simple interface...
public interface Consumer {
public void publish(String company, String country, String webLink, String email);
}
Note, I normally prefer to use objects (like a POJO), but I'm trying to keep it simple.
Next, we need to modify the Scannner to work with out Consumer...
public class Scanner {
public void getCompanyProfile(Consumer consumer) {
Document sourceCode;
List<String> allLinks = results();
Document sourceCode;
int counter = 1;
for (String link : allLinks) {
System.out.println("Link #:" + counter + " " + link);
sourceCode = PageVisitor.getHtmlSource(link);
Elements profile = sourceCode.select("div.company a.cd");
for (Element links : profile) {
String linkHref = links.attr("href");
System.out.println(linkHref);
setUserData(linkHref);
}
counter++;
}
}
private void setUserData(String url, Consumer consumer) throws IOException {
Extractor data = new Extractor();
// Scan each page alibaba initial result
data.setProfile(url);
this.companyName = data.getName();
this.country = data.getCountry();
HashSet<String> webites = data.getSellerUrls();
this.webAndEmail = new HashMap<String, HashSet<String>>();
HashSet<String> emails;
for (String webs : webites) {
emails = data.emailExtractor(webs);
webAndEmail.put(webs, emails);
for (String anEmail : emails) {
consumer.publish(companyName, country, webs, anEmail);
}
}
}
public String getProductName() {
return this.product;
}
public String getSource() {
return this.source;
}
public String getCompanyName() {
return this.companyName;
}
public String getCountry() {
return this.country;
}
public Map<String, HashSet<String>> getWebandEmail() {
return this.webAndEmail;
}
}
Now, we need some way to get the Scanner started and producing data, first we create the basic UI and then we start a SwingWorker, passing a reference of the TableModel to it, so it can add the new rows.
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultTableModel model = new DefaultTableModel(new String[]{"Company Name", "Email", "Website", "Country", "Product", "Source"}, 0);
JTable table = new JTable(model);
// Initialise remainder of the UI...
ScannerWorker worker = new ScannerWorker(model);
worker.execute();
}
});
And the SwingWorker to hold it all together...
public class ScannerWorker extends SwingWorker<Object, String[]> implements Consumer {
private DefaultTableModel tableModel;
public ScannerWorker(DefaultTableModel tableModel) {
this.tableModel = tableModel;
}
#Override
protected Object doInBackground() throws Exception {
Scanner scanner = new Scanner();
scanner.getCompanyProfile(this);
return null;
}
#Override
public void publish(String company, String country, String webLink, String email) {
publish(new String[]{company, email, webLink, country, "", ""});
}
#Override
protected void process(List<String[]> chunks) {
for (String[] rowData : chunks) {
tableModel.addRow(rowData);
}
}
}
Take a closer look at Worker Threads and SwingWorker and How to Use Tables for more details

ParseObject as a data to the table/chart

I'm new in coding and I have a problem to understand something. I follow the example form Parse.com Doc and wrote this.
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
int object_value = Integer.parseInt(obiect);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
I understand this like:
I send query to server
get obiect with "lxFzCTeOcl" id
if there is no exception I create String object which takes string
form "value" column.
convert String to int
My question is: How can I use object_value for example to make a chart or put it into a table?
Here we will add the array list to your code and start to store an object inside the array every time we call the getData method in your class.
private ArrayList<Integer> dataArray;
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(obiect);
if(dataArray==null)
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
And here I'm just adding a simple example of how to create a simple pie chart using our array list (note that I used the lib AChartEngine http://www.achartengine.org/):
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };
private GraphicalView createPieChart(ArrayList<Integer> data){
GraphicalView chartView;
CategorySeries series = new CategorySeries("PIE");
for (int i = 0; i < VALUES.length; i++) {
series.add(i, data.get(i));
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(series.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
chartView = ChartFactory.getPieChartView(this, series, new DefaultRenderer());
chartView.repaint();
return chartView;
}
Now you can add this GraphicalView to your view.
The returned object is much like a map, with key/value pairs. In your example, the key is "value", which makes it a little confusing, but it would be like this if you wanted all fields:
for (Field field : myInstance.getClass().getDeclaredFields()) {
String name = field.getName();
value = field.get(myInstance).toString();
map.put(name, value);
}

retrieve real-time data from JBloomberg API

I want to retrieve the time and the real-time last Price as double instead of having an output like
DataChangeEvent{ESA Index,ASK_SIZE: 204==>192}
from the code below
DataChangeListener lst = new DataChangeListener() {
#Override
public void dataChanged(DataChangeEvent e) {
System.out.println(e);
}
};
SubscriptionBuilder builder = new SubscriptionBuilder()
.addSecurity("ESA Index")
.addField(RealtimeField.LAST_PRICE)
.addField(RealtimeField.ASK)
.addField(RealtimeField.ASK_SIZE)
.addListener(lst);
session.subscribe(builder);
Thread.sleep(3000);
Just saw your question so it's probably a little late - but here it is anyway. DataChangeEvent contains the ticker, the field, the new and old price:
DataChangeListener lst = new DataChangeListener() {
#Override public void dataChanged(DataChangeEvent e) {
String ticker = e.getSource();
String field = e.getDataName();
double oldValue = e.getOldValue().asDouble();
double newValue = e.getNewValue().asDouble();
}
};

Categories