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();
}
};
Related
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)
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
I'm trying to retrieve some data from my Db (I'm using SQLite) using DAO
public class ClassSectionDAO implements IClassSectionDAO{
#Override
public void selectAllClassSection() {
d = new DBManager();
sqliteQuery = new SqliteQueries();
d.executeQuery(sqliteQuery.selectAllFrom("classSection"));
try{
while(d.getResultSet().next()){
ClassSection classSection = new ClassSection();
classSection.setClassSectionId(d.getResultSet().getString("classSectionId"));
classSection.setSchoolClassCode(d.getResultSet().getString("schoolClassCode"));
classSection.setClassSectionNumber(d.getResultSet().getInt("classSectionNumber"));
classSection.setClassSectionAvailability(d.getResultSet().getString("classSectionAvailability"));
classSectionList.add(classSection);
System.out.println("classSectionList: " + classSectionList);
}
}
catch(Exception e){
Logger.getLogger(ClassSectionDAO.class.getName()).log(Level.SEVERE, null, e);
classSectionList = null;
}
finally{
d.closeDatabaseConnection();
}
}
}
All I'm getting is a list of objects like
classSectionList: [entities.classSection.ClassSection#19ccf6d, entities.classSection.ClassSection#1faf0e7, entities.classSection.ClassSection#1cf8409]
What should I do in order to get the values instead?
PS: If you want to see more code, let me know
I think you just made a typo, as you already said in your question: I get a list of Objects (of type ClassSection). That's clear because you print the list of Objects.
If you want to do it in the while loop (print immediately the value for every result), just change the last line in the loop to:
System.out.println("classSectionList: " + classSection.getSchoolClassCode());
If you want to print the values of all results (after all results are processed), just add Michaƫl's solution after the wile loop.
for(ClassSection c : classSectionList) {
System.out.println(c.getSchoolClassCode());
// print other attributes
}
EDIT :
Firt solution :
public class ClassSectionDAO implements IClassSectionDAO{
#Override
public void selectAllClassSection() {
d = new DBManager();
sqliteQuery = new SqliteQueries();
d.executeQuery(sqliteQuery.selectAllFrom("classSection"));
try{
while(d.getResultSet().next()){
ClassSection classSection = new ClassSection();
classSection.setClassSectionId(d.getResultSet().getString("classSectionId"));
classSection.setSchoolClassCode(d.getResultSet().getString("schoolClassCode"));
classSection.setClassSectionNumber(d.getResultSet().getInt("classSectionNumber"));
classSection.setClassSectionAvailability(d.getResultSet().getString("classSectionAvailability"));
classSectionList.add(classSection);
// Solution of ProgrammingIsAwsome
System.out.println("classSectionList: " + classSection.getSchoolClassCode());
}
}
catch(Exception e){
Logger.getLogger(ClassSectionDAO.class.getName()).log(Level.SEVERE, null, e);
classSectionList = null;
}
finally{
d.closeDatabaseConnection();
}
}
}
Second solution :
public class ClassSectionDAO implements IClassSectionDAO{
#Override
public void selectAllClassSection() {
d = new DBManager();
sqliteQuery = new SqliteQueries();
d.executeQuery(sqliteQuery.selectAllFrom("classSection"));
try{
while(d.getResultSet().next()){
ClassSection classSection = new ClassSection();
classSection.setClassSectionId(d.getResultSet().getString("classSectionId"));
classSection.setSchoolClassCode(d.getResultSet().getString("schoolClassCode"));
classSection.setClassSectionNumber(d.getResultSet().getInt("classSectionNumber"));
classSection.setClassSectionAvailability(d.getResultSet().getString("classSectionAvailability"));
classSectionList.add(classSection);
}
// Print the list after the while
for(ClassSection c : classSectionList) {
System.out.println(c.getSchoolClassCode());
// print other attributes
}
}
catch(Exception e){
Logger.getLogger(ClassSectionDAO.class.getName()).log(Level.SEVERE, null, e);
classSectionList = null;
}
finally{
d.closeDatabaseConnection();
}
}
}
I have a LinkedHashMap which fills with data from db with loop "for" string by string and when I try to show the first or the last String, the method can show me only the last String in log. But in application listViewContent is filled fully. So I don't understand why I can't see any string that I want. I need to collect all strings I get from db and compare them in future.
How can I collect all strings and what method should I call to show the string I want to see?Unfortunately I can only retrieve one (and the last instead of the first) string.
Here is my example code :
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FirstMethod();
}
public FirstMethod() {
SecondMethod newMethod = .. // getting data from the second method
}
public SecondMethod() {
public void onResponseReceived(String result) {
try {
...
if (posts != null) {
for (WallPostItem post : posts) { // this loop
//create new map for a post
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put(ATTRIBUTE_NAME_TEXT, post.text);
PictureItem postPicture = new PictureItem();
map.put(ATTRIBUTE_NAME_IMAGE, postPicture);
map.put(ATTRIBUTE_NAME_DATE, post.date);
sAdapter.notifyDataSetChanged();
};
};
...
List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String, Object>>(GlobalMap.entrySet());
Map.Entry<String, Object> firstInsertedEntry = list.get(0);
Log.w("FirstEntryOfMap",""+firstInsertedEntry); // this log shows me the last string instead of the first
}
if (isRefresh) {
isRefresh = false;
lvSimple.setSelectionAfterHeaderView();
}
} catch (Exception e) {
Log.d("exceptions", "problem in get wall post task after post execute: " + e.toString());
}
}
You aren't putting your values into a List, you are putting them into a Map (that preserves key order). I would suggest you create a POJO class,
class MyAttribute {
final String postName;
final PictureItem postPicture;
final Date postDate;
public MyAttribute(String postName, PictureItem postPicture, Date postDate) {
this.postName = postName;
this.postPicture = postPicture;
this.postDate = postDate;
}
public String getPostName() {
return postName;
}
public Date getPostDate() {
return postDate;
}
public PictureItem getPostPicture() {
return postPicture;
}
}
Then you could create a
List<MyAttribute> myAttributes = new ArrayList<>();
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);
}