I believe I've searched all of the similar questions, but still am not seeing my issue anywhere. I am populating an ObservableList from a database which is succeeding per my Console output. I have a multiple controller setup for a school project to create a scheduler app. I have a root controller which functions as the borderPane, two functional controllers for Appointments and Customers which are all Singleton, and a shared DataView controller which is not to allow each view to instantiate its' own DataView. I've implemented toString on each of the controllers to spit out what the values and/or object Ids of each element are and everything seems to line up. I can't for the life of me figure out why the ListView or TableView aren't outputting the bound data. Here's the view data that I'm trying to bind to both ListView and TableView
public class AppointmentView implements IAppointmentView {
private final ZonedDateTime createdDate;
private final String createdBy;
// Interface needs these components
private ReadOnlyStringProperty title;
private ReadOnlyStringProperty description;
private ReadOnlyStringProperty location;
private ReadOnlyStringProperty contact;
private ReadOnlyStringProperty url;
private ReadOnlyStringProperty customerName;
private ReadOnlyObjectProperty<ZonedDateTime> start;
private ReadOnlyObjectProperty<ZonedDateTime> end;
private ReadOnlyProperty<ZonedDateTime> lastUpdated;
/***
*
* #param title
* #param description
* #param location
* #param contact
* #param url
* #param customerName
* #param start
* #param end
* #param createDate
* #param createdBy
* #param lastUpdate
*/
public AppointmentView(String title, String description, String location, String contact, String url, String customerName, Timestamp start, Timestamp end, Timestamp createDate, String createdBy, Timestamp lastUpdate) {
this.title = new SimpleStringProperty(title);
this.description = new SimpleStringProperty(description);
this.location = new SimpleStringProperty(location);
this.contact = new SimpleStringProperty(contact);
this.customerName = new SimpleStringProperty(customerName);
this.start = new SimpleObjectProperty<>(ZonedDateTime.ofInstant(start.toInstant(), ZoneId.systemDefault()));
this.end = new SimpleObjectProperty<>(ZonedDateTime.ofInstant(end.toInstant(), ZoneId.systemDefault()));
this.lastUpdated = new SimpleObjectProperty<>(ZonedDateTime.ofInstant(lastUpdate.toInstant(), ZoneId.systemDefault()));
this.url = new SimpleStringProperty(url);
this.createdDate = ZonedDateTime.ofInstant(createDate.toInstant(), ZoneId.systemDefault());
this.createdBy = createdBy;
}
public String getTitle() {
return title.getValue();
}
ReadOnlyStringProperty titleProperty() {
return title;
}
public String getDescription() {
return description.getValue();
}
ReadOnlyStringProperty descriptionProperty() {
return description;
}
public String getLocation() {
return location.getValue();
}
ReadOnlyStringProperty locationProperty() {
return location;
}
public String getContact() {
return contact.getValue();
}
ReadOnlyStringProperty contactProperty() {
return contact;
}
public String getUrl() {
return url.getValueSafe();
}
ReadOnlyStringProperty urlProperty() {
return url;
}
public String getCustomerName() {
return customerName.getValue();
}
ReadOnlyStringProperty customerNameProperty() {
return customerName;
}
public ZonedDateTime getStart() {
return ZonedDateTime.ofInstant(start.getValue().toInstant(), ZoneId.systemDefault());
}
ReadOnlyProperty<ZonedDateTime> startProperty() {
return start;
}
public ZonedDateTime getEnd() {
return ZonedDateTime.ofInstant(end.getValue().toInstant(), ZoneId.systemDefault());
}
ReadOnlyProperty<ZonedDateTime> endProperty() {
return end;
}
public LocalDate getCreateDate() {
return createdDate.toLocalDate();
}
public String getCreatedBy() {
return createdBy;
}
public ZonedDateTime getLastUpdate() {
return ZonedDateTime.ofInstant(lastUpdated.getValue().toInstant(), ZoneId.systemDefault());
}
ReadOnlyProperty<ZonedDateTime> lastUpdatedProperty() {
return lastUpdated;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("AppointmentView{");
sb.append("createdDate=").append(createdDate);
sb.append(", createdBy='").append(createdBy).append('\'');
sb.append(", titleProperty=").append(title);
sb.append(", descriptionProperty=").append(description);
sb.append(", locationProperty=").append(location);
sb.append(", contactProperty=").append(contact);
sb.append(", urlProperty=").append(url);
sb.append(", customerName=").append(customerName);
sb.append(", startProperty=").append(start);
sb.append(", endProperty=").append(end);
sb.append(", lastUpdated=").append(lastUpdated);
sb.append('}');
return sb.toString();
}
}
Here's the AppViewController:
public class AppViewController extends BorderPane {
private BorderPane rootPane;
private MenuBar menuBar;
private Menu fileMenu;
private Menu editMenu;
private Menu reportMenu;
private Menu helpMenu;
private MenuItem closeMenuItem;
private MenuItem copyMenuItem;
private MenuItem monthlyAppointmentReportMenuItem;
private MenuItem consultantScheduleMenuItem;
private MenuItem customersByCountryMenuItem;
private MenuItem aboutMenuItem;
private VBox vbAppView;
private TabPane tpAppPane;
private Tab tabCustomers;
private ScrollPane spCustomerEditor;
private Tab tabAppointments;
private ScrollPane spAppointmentEditor;
private MainApp mainApp;
private static AppViewController instance;
private static AppointmentViewController appointmentViewController = AppointmentViewController.getInstance();
private static CustomerViewController customerViewController = CustomerViewController.getInstance();
private static DataViewController dataViewController;
private AppViewController() {
initialize();
}
public static AppViewController getInstance() {
if (instance == null) {
new AppViewController();
}
return instance;
}
/**
* Called to initialize a controller after its root element has been
* completely processed.
**/
public void initialize() {
instance = this;
this.rootPane = new BorderPane();
this.menuBar = new MenuBar();
this.fileMenu = new Menu("_File");
this.editMenu = new Menu("_Edit");
this.reportMenu = new Menu("_Report");
this.helpMenu = new Menu("_Help");
this.closeMenuItem = new MenuItem("Close");
this.copyMenuItem = new MenuItem("Copy");
this.monthlyAppointmentReportMenuItem = new MenuItem("Monthly Appointment Report");
this.consultantScheduleMenuItem = new MenuItem("Consultant Schedule Report");
this.customersByCountryMenuItem = new MenuItem("Customers by Country Report");
this.aboutMenuItem = new MenuItem("About");
this.vbAppView = new VBox();
this.tpAppPane = new TabPane();
this.tabCustomers = new Tab("Customers");
this.tabCustomers.setClosable(false);
this.spCustomerEditor = new ScrollPane();
this.tabAppointments = new Tab("Appointments");
this.tabAppointments.setClosable(false);
this.spAppointmentEditor = new ScrollPane();
// populate menus and menuBar and add them to top pane
this.fileMenu.getItems().setAll(closeMenuItem);
this.fileMenu.setMnemonicParsing(true);
this.editMenu.getItems().setAll(copyMenuItem);
this.editMenu.setMnemonicParsing(true);
this.reportMenu
.getItems()
.setAll(monthlyAppointmentReportMenuItem, consultantScheduleMenuItem, customersByCountryMenuItem);
this.reportMenu.setMnemonicParsing(true);
this.helpMenu.getItems().setAll(aboutMenuItem);
this.helpMenu.setMnemonicParsing(true);
this.menuBar.getMenus().addAll(fileMenu, editMenu, reportMenu, helpMenu);
this.rootPane.setTop(menuBar);
// populate scroll panes with included views
this.spAppointmentEditor.setContent(getAppointmentView());
this.spCustomerEditor.setContent(getCustomerView());
// populate tab panes and controllers and add them to the center pane
this.tabAppointments.setContent(spAppointmentEditor);
this.tabCustomers.setContent(spCustomerEditor);
this.tpAppPane.getTabs().addAll(tabAppointments, tabCustomers);
vbAppView.getChildren().addAll(tpAppPane);
this.rootPane.setCenter(vbAppView);
// add data view to bottom pane
this.rootPane.setBottom(AppointmentViewController.getDataView());
setupEventHandlers(this);
}
private void setupEventHandlers(AppViewController appViewController) {
this.tabCustomers.setOnSelectionChanged((event -> {
if (tabCustomers.isSelected()) {
// Change to Customer View
setCustomerView();
} else {
setAppointmentView();
}
}));
this.tabAppointments.setOnSelectionChanged(event -> {
if (tabAppointments.isSelected()) {
setAppointmentView();
} else {
setCustomerView();
}
});
this.closeMenuItem.setOnAction(event -> quitApp());
this.tpAppPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if(newValue.getText().toLowerCase().equals("Customer".toLowerCase())){
setCustomerView();
}
if (newValue.getText().toLowerCase().equals("Appointments".toLowerCase())){
setAppointmentView();
}
});
}
private void setCustomerView() {
CustomerViewController customerViewController = CustomerViewController.getInstance();
setDataView(customerViewController.getDataViewController().tabPane);
customerViewController.getGpCustomerEditor().getChildren().filtered(node -> toggleTextFields(node, true));
}
private void setAppointmentView() {
AppointmentViewController controller = AppointmentViewController.getInstance();
setDataView(controller.getDataViewController().tabPane);
controller.getGpAppointmentEditor().getChildren().filtered(node -> toggleTextFields(node, true));
}
/***
* Sets whether text fields are enabled or disabled
* true = disable Text Fields
* false = enable Text Fields
* #param node the child nodes of the editor
* #param disabled whether to disable or enable the text fields
* #return whether node was affected or not
*/
public static boolean toggleTextFields(Node node, boolean disabled) {
if (node instanceof TextField) {
((TextField) node).setEditable(!disabled);
node.setDisable(disabled);
return true;
}
return false;
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
}
private void quitApp() {
Platform.exit();
}
public Parent getBorderPane() {
return rootPane;
}
public TabPane getTpAppPane() {
return tpAppPane;
}
public Tab getTabCustomers() {
return tabCustomers;
}
public Tab getTabAppointments() {
return tabAppointments;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("AppViewController{");
sb.append("\nrootPane=").append(rootPane);
sb.append(",\n menuBar=").append(menuBar);
sb.append(",\n fileMenu=").append(fileMenu);
sb.append(",\n editMenu=").append(editMenu);
sb.append(",\n reportMenu=").append(reportMenu);
sb.append(",\n helpMenu=").append(helpMenu);
sb.append(",\n closeMenuItem=").append(closeMenuItem);
sb.append(",\n copyMenuItem=").append(copyMenuItem);
sb.append(",\n monthlyAppointmentReportMenuItem=").append(monthlyAppointmentReportMenuItem);
sb.append(",\n consultantScheduleMenuItem=").append(consultantScheduleMenuItem);
sb.append(",\n customersByCountryMenuItem=").append(customersByCountryMenuItem);
sb.append(",\n aboutMenuItem=").append(aboutMenuItem);
sb.append(",\n vbAppView=").append(vbAppView);
sb.append(",\n tpAppPane=").append(tpAppPane);
sb.append(",\n tabCustomers=").append(tabCustomers);
sb.append(",\n spCustomerEditor=").append(spCustomerEditor);
sb.append(",\n tabAppointments=").append(tabAppointments);
sb.append(",\n spAppointmentEditor=").append(spAppointmentEditor);
sb.append(",\n dataViewController=").append(dataViewController);
sb.append("\n}");
return sb.toString();
}
public void setDataViewController(DataViewController dataViewController) {
this.dataViewController = dataViewController;
}
public DataViewController getDataViewController() {
return dataViewController;
}
}
And the AppointmentView:
private TableView<AppointmentView> tvAppointments = new TableView<>();
private TableColumn<AppointmentView, String> tcTitle = new TableColumn<>("Title");
private TableColumn<AppointmentView, String> tcDescription = new TableColumn<>("Description");
private TableColumn<AppointmentView, String> tcLocation = new TableColumn<>("Location");
private TableColumn<AppointmentView, String> tcContact = new TableColumn<>("Contact");
private TableColumn<AppointmentView, String> tcUrl = new TableColumn<>("URL");
private TableColumn<AppointmentView, String> tcCustomerName = new TableColumn<>("Customer Name");
private TableColumn<AppointmentView, ZonedDateTime> tcStart = new TableColumn<>("Start Time");
private TableColumn<AppointmentView, ZonedDateTime> tcEnd = new TableColumn<>("End Time");
private TableColumn<AppointmentView, ZonedDateTime> tcCreateDate = new TableColumn<>("Created Date");
private TableColumn<AppointmentView, String> tcCreatedBy = new TableColumn<>("Created By");
private TableColumn<AppointmentView, Timestamp> tcLastUpdate = new TableColumn<>("Last Updated");
---- snip ----
this.tcTitle.setCellValueFactory(new PropertyValueFactory<>("title"));
this.tcTitle.setVisible(true);
this.tcTitle.setMinWidth(50);
this.tcCustomerName.setCellValueFactory(new PropertyValueFactory<>("customerName"));
this.tcCustomerName.setVisible(true);
this.tcCustomerName.setMinWidth(40);
this.tcDescription.setCellValueFactory(new PropertyValueFactory<>("description"));
this.tcDescription.setVisible(true);
this.tcDescription.setMinWidth(100);
this.tcLocation.setCellValueFactory(new PropertyValueFactory<>("location"));
this.tcLocation.setVisible(true);
this.tcLocation.setMinWidth(40);
this.tcContact.setCellValueFactory(new PropertyValueFactory<>("contact"));
this.tcContact.setVisible(true);
this.tcContact.setMinWidth(40);
this.tcUrl.setCellValueFactory(new PropertyValueFactory<>("url".toUpperCase()));
this.tcUrl.setVisible(true);
this.tcUrl.setMinWidth(40);
this.tcStart.setCellValueFactory(new PropertyValueFactory<>("start"));
this.tcStart.setVisible(true);
this.tcStart.setMinWidth(40);
this.tcEnd.setCellValueFactory(new PropertyValueFactory<>("end"));
this.tcEnd.setVisible(true);
this.tcEnd.setMinWidth(40);
this.tcCreateDate.setCellValueFactory(new PropertyValueFactory<>("createDate"));
this.tcCreateDate.setVisible(true);
this.tcCreateDate.setMinWidth(40);
this.tcCreatedBy.setCellValueFactory(new PropertyValueFactory<>("createdBy"));
this.tcCreatedBy.setVisible(true);
this.tcCreatedBy.setMinWidth(40);
this.tcLastUpdate.setCellValueFactory(new PropertyValueFactory<>("lastUpdate"));
this.tcLastUpdate.setVisible(true);
this.tcLastUpdate.setMinWidth(40);
this.tvAppointments = new TableView<>();
this.tvAppointments.setItems(appointmentViews);
this.tvAppointments.getColumns().addAll(
tcTitle,
tcDescription,
tcLocation,
tcContact,
tcUrl,
tcCustomerName,
tcStart,
tcEnd,
tcCreateDate,
tcCreatedBy,
tcLastUpdate);
this.lvListView = new ListView<>();
this.lvListView.setItems(appointmentViews);
this.dataViewController.setTableView(this.tvAppointments);
this.dataViewController.setLblListView(new Label("Appointment List"));
this.dataViewController.setListView(this.lvListView);
this.dataViewController.setLblTableView(new Label("Appointments"));
And the base DataViewController that I'm trying to manipulate:
public class DataViewController extends TabPane {
// private static DataViewController instance;
public TabPane tabPane;
private Tab tabTableView;
private Tab tabListView;
private VBox vbListView;
private VBox vbTableView;
private Label lblListView;
private Label lblTableView;
protected ScrollPane spListView;
protected ScrollPane spTableView;
private ListView<?> listView;
private TableView<?> tableView;
private MainApp mainApp;
public DataViewController() {
initialize();
}
/* public static DataViewController getInstance(){
if(instance == null){
new DataViewController();
}
return instance;
}*/
/**
* Called to initialize a controller after its root element has been
* completely processed.
*
*/
public void initialize() {
// this.instance = this;
this.tabPane = new TabPane();
this.tabPane.setPrefHeight(250.0);
this.tabPane.setMaxHeight(400.0);
this.tabPane.setMaxWidth(Integer.MAX_VALUE);
this.tabTableView = new Tab("Table View");
this.tabTableView.setClosable(false);
this.tabListView = new Tab("List View");
this.tabListView.setClosable(false);
this.spListView = new ScrollPane();
this.spTableView = new ScrollPane();
this.lblListView = new Label("List View");
this.lblTableView = new Label("Table View");
this.vbListView = new VBox();
this.vbTableView = new VBox();
this.listView = new ListView<>();
this.tableView = new TableView<>();
this.vbListView.getChildren().setAll(this.lblListView, this.listView);
this.spListView.setContent(this.listView);
this.tabListView.setContent(this.spListView);
this.vbTableView.getChildren().setAll(this.lblTableView, this.spTableView);
this.spTableView.setContent(this.tableView);
this.tabTableView.setContent(vbTableView);
this.tabPane.getTabs().setAll(tabListView, tabTableView);
}
public Label getLblListView() {
return lblListView;
}
public void setLblListView(Label lblListView) {
this.lblListView = lblListView;
}
public Label getLblTableView() {
return lblTableView;
}
public void setLblTableView(Label lblTableView) {
this.lblTableView = lblTableView;
}
public ListView<?> getListView() {
return listView;
}
public void setListView(ListView<?> listView) {
this.listView = listView;
}
public TableView<?> getTableView() {
return tableView;
}
public void setTableView(TableView<?> tableView) {
this.tableView = tableView;
}
public void setMainApp(MainApp mainApp){
this.mainApp = mainApp;
}
/* public static DataViewController getInstance() {
if (instance == null){
instance = new DataViewController();
}
return instance;
}*/
#Override
public String toString() {
return new StringBuilder()
.append("DataViewController{")
.append("\ntabPane=")
.append(tabPane)
.append(", \ntabTableView=")
.append(tabTableView)
.append(", \ntabListView=")
.append(tabListView)
.append(", \nvbListView=")
.append(vbListView)
.append(", \nvbTableView=")
.append(vbTableView)
.append(", \nlblListView=")
.append(lblListView.getText())
.append(", \nlblTableView=")
.append(lblTableView.getText())
.append(", \nspListView=")
.append(spListView)
.append(", \nspTableView=")
.append(spTableView)
.append(", \nlistView=")
.append(listView.getItems())
.append(", \ntableView=")
.append(tableView.getColumns())
.append("\n}")
.toString();
}
}
As mentioned, I put in a few toString calls and implementations and I keep seeing the objects in DataViewController per this:
listView=[AppointmentView{createdDate=2017-09-02T00:00-07:00[America/Los_Angeles], createdBy='test1', titleProperty=StringProperty [value: Meet with Amari], descriptionProperty=StringProperty [value: Meeting WR of the Raiders], locationProperty=StringProperty [value: Raiders HQ, Alameda], contactProperty=StringProperty [value: Jack DelRio], urlProperty=StringProperty [value: raiders.com], customerName=StringProperty [value: Amari Cooper], startProperty=ObjectProperty [value: 2017-09-04T16:00-07:00[America/Los_Angeles]], endProperty=ObjectProperty [value: 2017-09-04T16:15-07:00[America/Los_Angeles]], lastUpdated=ObjectProperty [value: 2017-09-02T23:07-07:00[America/Los_Angeles]]}, AppointmentView{createdDate=2017-09-02T00:00-07:00[America/Los_Angeles], createdBy='test1', titleProperty=StringProperty [value: Meet with Amari], descriptionProperty=StringProperty [value: Meeting WR of the Raiders], locationProperty=StringProperty [value: Raiders HQ, Alameda], contactProperty=StringProperty [value: Jack DelRio], urlProperty=StringProperty [value: raiders.com], customerName=StringProperty [value: Amari Cooper], startProperty=ObjectProperty [value: 2017-09-04T16:00-07:00[America/Los_Angeles]], endProperty=ObjectProperty [value: 2017-09-04T16:15-07:00[America/Los_Angeles]], lastUpdated=ObjectProperty [value: 2017-09-02T23:07-07:00[America/Los_Angeles]]}],
tableView=[javafx.scene.control.TableColumn#6167e82, javafx.scene.control.TableColumn#50658769, javafx.scene.control.TableColumn#f65aae1, javafx.scene.control.TableColumn#2d5ab3ab, javafx.scene.control.TableColumn#180d2aec, javafx.scene.control.TableColumn#64afb84b, javafx.scene.control.TableColumn#463f349d, javafx.scene.control.TableColumn#3e80101a, javafx.scene.control.TableColumn#4fab076c, javafx.scene.control.TableColumn#565f8332, javafx.scene.control.TableColumn#697bdeb8]
And here's the MainApp method that's calling it:
private void initLayout() {
// rootPane = new BorderPane();
appointmentViewController = AppointmentViewController.getInstance();
appointmentView = appointmentViewController.apAppointmentView;
appointmentViewController.setMainApp(this);
dataViewController = appointmentViewController.getDataViewController();
dataView = dataViewController.tabPane;
dataViewController.setMainApp(this);
customerViewController = CustomerViewController.getInstance();
customerView = customerViewController.apCustomerView;
customerViewController.setMainApp(this);
appViewController = AppViewController.getInstance();
appView = appViewController.getBorderPane();
appViewController.setMainApp(this);
appViewController.setDataViewController(appointmentViewController.getDataViewController());
System.out.println(this.dataViewController);
System.out.println(this.dataView);
System.out.println(appointmentViewController.toString());
System.out.println(customerViewController.toString());
System.out.println(appViewController.toString());
rootPane = (BorderPane) appView;
scene = new Scene(rootPane);
scene.getStylesheets().add("/styles/Styles.css");
primaryStage.setScene(scene);
primaryStage.show();
}
I've setup the CellValueFactories,etc. What am I missing here?
This is how the UI is shown:
In DataViewController the scene structure is initialized from the constructor. Using any of the setters in this class modifies the fields, it does not modify the scene in any way leaving the old empty ListView in the scene but printing the new one containing items from the toString method.
Related
I have got implemented filtering in nattables. How to add sorting? do I have to create new columnHeaderLayer? Here is my code:
1 class BodyLayerStack
class BodyLayerStack extends AbstractLayerTransform {
private final FilterList<TableLine> filterList;
private final SelectionLayer selectionLayer;
private final DataLayer bodyDataLayer;
private final IRowDataProvider<TableLine> bodyDataProvider;
private final SortedList<TableLine> sortedList;
public DataLayer getBodyDataLayer() {
return bodyDataLayer;
}
public SelectionLayer getSelectionLayer() {
return selectionLayer;
}
public IRowDataProvider<TableLine> getBodyDataProvider() {
return bodyDataProvider;
}
getting values from tables:
public BodyLayerStack(List<TableLine> values, IColumnAccessor<TableLine> columnAccessor, Integer[] columnIndicesForRowHeaders) {
EventList<TableLine> eventList = GlazedLists.eventList(values);
TransformedList<TableLine, TableLine> rowObjectsGlazedList = GlazedLists.threadSafeList(eventList);
creating filter and sorted list:
this.filterList = new FilterList<>(rowObjectsGlazedList);
this.sortedList = new SortedList<>(filterList, null);
this.bodyDataProvider = new ListDataProvider<TableLine>(this.sortedList, columnAccessor);
bodyDataLayer = new DataLayer(this.bodyDataProvider);
ColumnOverrideLabelAccumulator bodyLabelAccumulator = new ColumnOverrideLabelAccumulator(bodyDataLayer);
bodyDataLayer.setConfigLabelAccumulator(bodyLabelAccumulator);
if( columnIndicesForRowHeaders != null ) {
for ( int i = 0; i < columnIndicesForRowHeaders.length; i++ ) {
bodyLabelAccumulator.registerColumnOverrides(
columnIndicesForRowHeaders[i],
RowHeaderLabel);
}
}
event layer:
GlazedListsEventLayer<TableLine> glazedListsEventLayer =
new GlazedListsEventLayer<>(bodyDataLayer, this.filterList);
this.selectionLayer = new SelectionLayer(glazedListsEventLayer, false);
selectionLayer.setSelectionModel(new RowSelectionModel<TableLine>(selectionLayer, this.bodyDataProvider, new IRowIdAccessor<TableLine>()
{
#Override
public Serializable getRowId(TableLine line)
{
return line.getId();
}
}));
adding configuration to selection layer
selectionLayer.addConfiguration(new DefaultSelectionLayerConfiguration()
{
#Override
protected void addSelectionUIBindings()
{
addConfiguration(new SelectionBindings());
}
#SuppressWarnings("rawtypes")
#Override
protected void addMoveSelectionConfig()
{
addConfiguration(new RowOnlySelectionConfiguration());
}
});
viewport layer + return
ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);
setUnderlyingLayer(viewportLayer);
}
public FilterList<TableLine> getFilterList() {
return this.filterList;
}
}
If you want to add sorting by click on column header cells, you have to add the SortHeaderLayer to your column header layer stack.
Please check the NatTable examples, like for example the SortableFilterableColumnGroupExample
I am writing a Market Watch program which displays live quotes in a JFXTreeTableView, but when I update the data in the ObservableList, it doesn't get updated in the JFXTreeTableView. The changeDataDemo() method is actually tracking changes in the prices and is working fine (I'm using RethinkDB changefeeds to do it.) However I have removed the changefeed code here to increase readability. There is a method that adds rows to TreeTableView and is working perfectly but I have removed the code from here.
This is my code:
public class MainWindow implements Initializable {
private ObservableList<MarketWatchEntry> marketWatchEntries = FXCollections.observableArrayList();
private JFXTreeTableColumn<MarketWatchEntry, String> instrument_token_col;
private JFXTreeTableColumn<MarketWatchEntry, String> exchange_col;
private JFXTreeTableColumn<MarketWatchEntry, String> instrument_type_col;
private JFXTreeTableColumn<MarketWatchEntry, String> symbol_col;
private JFXTreeTableColumn<MarketWatchEntry, String> expiry_col;
private JFXTreeTableColumn<MarketWatchEntry, Number> buy_qty_col;
private JFXTreeTableColumn<MarketWatchEntry, Number> buy_price_col;
private JFXTreeTableColumn<MarketWatchEntry, Number> seller_price_col;
private JFXTreeTableColumn<MarketWatchEntry, Number> sell_qty_col;
#FXML
private JFXTreeTableView<MarketWatchEntry> MarketWatch;
#Override
public void initialize(URL location, ResourceBundle resources) {
populateMarketWatch();
}
private void populateMarketWatch() {
instrument_token_col = new JFXTreeTableColumn<>("Instrument Token");
instrument_token_col.setPrefWidth(80);
instrument_token_col.setVisible(false);
instrument_token_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().instrument_token);
exchange_col = new JFXTreeTableColumn<>("Exchange");
exchange_col.setPrefWidth(80);
exchange_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().exchange);
instrument_type_col = new JFXTreeTableColumn<>("Instrument");
instrument_type_col.setPrefWidth(80);
instrument_type_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().instrument_type);
symbol_col = new JFXTreeTableColumn<>("Symbol");
symbol_col.setPrefWidth(80);
symbol_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().trading_symbol);
expiry_col = new JFXTreeTableColumn<>("Expiry");
expiry_col.setPrefWidth(80);
expiry_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, String> param) -> param.getValue().getValue().expiry);
buy_qty_col = new JFXTreeTableColumn<>("Buy Qty");
buy_qty_col.setPrefWidth(80);
buy_qty_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, Number> param) -> param.getValue().getValue().buy_qty);
buy_price_col = new JFXTreeTableColumn<>("Buyer Price");
buy_price_col.setPrefWidth(80);
buy_price_col.setCellValueFactory((JFXTreeTableColumn.CellDataFeatures<MarketWatchEntry, Number> param) -> param.getValue().getValue().buyer_price);
seller_price_col = new JFXTreeTableColumn<>("Seller Price");
seller_price_col.setPrefWidth(80);
seller_price_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, Number> param) -> param.getValue().getValue().seller_price);
sell_qty_col = new JFXTreeTableColumn<>("Sell Qty");
sell_qty_col.setPrefWidth(80);
sell_qty_col.setCellValueFactory((TreeTableColumn.CellDataFeatures<MarketWatchEntry, Number> param) -> param.getValue().getValue().sell_qty);
final TreeItem<MarketWatchEntry> root = new RecursiveTreeItem<>(marketWatchEntries, RecursiveTreeObject::getChildren);
MarketWatch.getColumns().setAll(instrument_token_col, exchange_col, instrument_type_col, symbol_col, expiry_col,
buy_qty_col, buy_price_col, seller_price_col, sell_qty_col, ltp_col, ltq_col, open_price_col, high_price_col,
low_price_col, close_price_col, average_price_col, change_col, net_change_col);
MarketWatch.setRoot(root);
MarketWatch.setShowRoot(false);
}
private void changeDataDemo() {
marketWatchEntries.get(0).buyer_price = new SimpleDoubleProperty(100);
}
}
I have removed irrelevant code blocks to increase readability.
My question is how to get TreeTableView to update all the cells when the collection is updated with new data.
MarketWatchEntry class
class MarketWatchEntry extends RecursiveTreeObject<MarketWatchEntry> {
StringProperty instrument_token;
StringProperty exchange;
StringProperty instrument_type;
StringProperty trading_symbol;
StringProperty expiry;
DoubleProperty buy_qty;
DoubleProperty buyer_price;
DoubleProperty seller_price;
DoubleProperty sell_qty;
DoubleProperty last_price;
DoubleProperty last_qty;
DoubleProperty open_price;
DoubleProperty high_price;
DoubleProperty low_price;
DoubleProperty close_price;
DoubleProperty average_price;
DoubleProperty change;
DoubleProperty net_change;
public MarketWatchEntry(String instrument_token, String exchange, String instrument_type, String trading_symbol,
String expiry, double buy_qty, double buy_price, double sell_price, double sell_qty,
double last_price, double last_qty, double open_price, double high_price, double low_price,
double close_price, double average_price, double change, double net_change) {
this.instrument_token = new SimpleStringProperty(instrument_token);
this.exchange = new SimpleStringProperty(exchange);
this.instrument_type = new SimpleStringProperty(instrument_type);
this.trading_symbol = new SimpleStringProperty(trading_symbol);
this.expiry = new SimpleStringProperty(expiry);
this.buy_qty = new SimpleDoubleProperty(buy_qty);
this.buyer_price = new SimpleDoubleProperty(buy_price);
this.sell_qty = new SimpleDoubleProperty(sell_qty);
this.seller_price = new SimpleDoubleProperty(sell_price);
this.last_price = new SimpleDoubleProperty(last_price);
this.last_qty = new SimpleDoubleProperty(last_qty);
this.open_price = new SimpleDoubleProperty(open_price);
this.high_price = new SimpleDoubleProperty(high_price);
this.low_price = new SimpleDoubleProperty(low_price);
this.close_price = new SimpleDoubleProperty(close_price);
this.average_price = new SimpleDoubleProperty(average_price);
this.change = new SimpleDoubleProperty(change);
this.net_change = new SimpleDoubleProperty(net_change);
}
#Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return this.instrument_token.getValue().equals(((MarketWatchEntry) obj).instrument_token.getValue());
}
#Override
public int hashCode() {
return 7 + 5 * Integer.valueOf(instrument_token.getValue());
}
}
The problem is in your changeDataDemo method:
private void changeDataDemo() {
marketWatchEntries.get(0).buyer_price = new SimpleDoubleProperty(100);
}
You are creating new instances of your properties instead of changing their values.
Something like this works:
private void changeDataDemo() {
marketWatchEntries.get(0).buyer_price.set(100);
}
But it is recommended to provide setters/getters on your Entity class:
class MarketWatchEntry extends RecursiveTreeObject<MarketWatchEntry> {
private final DoubleProperty buyer_price;
...
public MarketWatchEntry(String instrument_token, String exchange, String instrument_type, String trading_symbol,
String expiry, double buy_qty, double buy_price, double sell_price, double sell_qty) {
...
this.buyer_price = new SimpleDoubleProperty(buy_price);
...
}
public final DoubleProperty buyer_priceProperty() {
return buyer_price;
}
public final double getBuyer_price() {
return buyer_price.get();
}
public final void setBuyer_price(double value) {
buyer_price.set(value);
}
...
}
so you can just call:
private void changeDataDemo() {
marketWatchEntries.get(0).setBuyer_price(100);
}
I have a tableview that i populate using an observablelist, ObservableList<Member>. The some attributes in Member object are optional, so the table cell for that row will be empty.
I have implemented FilteredList<Member> and SortedList<Member> although when i search, because of those null values in some cells, a java.lang.NullPointerException is thrown. I have no idea on how to solve this problem.
The following is SSCCE, that demonstrate my problem
package com.yunusfx.javafxcustomcontrols.yunusreproduceproblem;
import javafx.application.Application;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
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.BorderPane;
import javafx.stage.Stage;
public class TableSearch extends Application{
private TableView<Member> tv = new TableView();
private TextField tfSearch = new TextField();
ObservableList<Member> memberList = FXCollections.observableArrayList();
ListProperty<Member> memberListProperty = new SimpleListProperty<>();
public static void main(String[] args) { launch(args); }
#Override
public void start(Stage primaryStage) throws Exception {
TableColumn<Member, String> name = createNameColumn();
TableColumn<Member, Integer> age = createAgeColumn();
TableColumn<Member, String> account = createAccountColumn();
TableColumn<Member, String> location = createLocationColumn();
tfSearch.setPromptText("Search here");
tv.getColumns().addAll(name, age, account, location);
memberListProperty.set(memberList);
tv.itemsProperty().bindBidirectional(memberListProperty);
tv.setItems(memberListProperty);
setData();
FilteredList<Member> filteredData = new FilteredList<>(memberList, p -> true);
tfSearch.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(Member -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (Member.getName().toLowerCase().contains(lowerCaseFilter)) {
return true;
// } else if(Member.getAge().toLowerCase().contains(lowerCaseFilter)){
// No idea how to search if is integer
// return true;
}else if(Member.getLocation().toString().toLowerCase().contains(lowerCaseFilter)){
return true;
}else if(Member.getAccount().toLowerCase().contains(lowerCaseFilter)){
return true;
}
return false;
});
});
SortedList<Member> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(tv.comparatorProperty());
tv.setItems(sortedData);
BorderPane borderPane = new BorderPane();
borderPane.setTop(tfSearch);
borderPane.setCenter(tv);
Scene scene = new Scene(borderPane, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private TableColumn createNameColumn() {
TableColumn<Member, String> colName = new TableColumn("Name");
colName.setMinWidth(25);
colName.setId("colName");
colName.setCellValueFactory(new PropertyValueFactory("name"));
return colName;
}
private TableColumn createAgeColumn() {
TableColumn<Member, Integer> colAge = new TableColumn("Age");
colAge.setMinWidth(25);
colAge.setId("colAge");
colAge.setCellValueFactory(new PropertyValueFactory("age"));
return colAge;
}
private TableColumn createAccountColumn() {
TableColumn<Member, String> colAccount = new TableColumn("Account");
colAccount.setMinWidth(25);
colAccount.setId("colAccount");
colAccount.setCellValueFactory(new PropertyValueFactory("account"));
return colAccount;
}
private TableColumn createLocationColumn() {
TableColumn<Member, String> colAccount = new TableColumn("Location");
colAccount.setMinWidth(25);
colAccount.setId("colLocation");
colAccount.setCellValueFactory(new PropertyValueFactory("location"));
return colAccount;
}
private void setData(){
Member m = new Member();
m.setAccount("we123");
m.setAge(456);
m.setLocation("Nairobi");
m.setName("Member 1");
memberList.add(m);
Member m1 = new Member();
m1.setAccount("OP5623");
m1.setAge(321);
m1.setLocation("Mombasa");
m1.setName("Doe");
memberList.add(m1);
Member m2 = new Member();
m2.setAge(569);
m2.setLocation("Meru");
m2.setName("John");
memberList.add(m2);
Member m3 = new Member();
m3.setAccount("YGTR665");
m3.setAge(666);
m3.setLocation("Eldoret");
m3.setName("Arif");
memberList.add(m3);
Member m4 = new Member();
m4.setAccount("BHJI58966");
m4.setAge(397);
m4.setName("Yunus");
memberList.add(m4);
}
public class Member {
private int id;
private String name;
private Integer age;
private String account;
private String location;
public Member(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
}
Clarification
By optional i mean some attributes in Member object might not have been set hence its table cell will be empty
I wasn't able to add age column to be searchable
Based on James_D's comment i was able to make search work but first check if value is null for optional attributes. For integer, convert it to string then use the string value. The important point is, the code is only dealing with actual data.
Following is what i updated:
FilteredList<Member> filteredData = new FilteredList<>(memberList, p -> true);
tfSearch.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(Member -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (Member.getName().toLowerCase().contains(lowerCaseFilter)) {
return true;
} else if(Integer.toString(Member.getAge()).contains(lowerCaseFilter)){
return true;
}else if(Member.getLocation() != null && Member.getLocation().toLowerCase().contains(lowerCaseFilter)){
return true;
}else if(Member.getAccount() != null && Member.getAccount().toLowerCase().contains(lowerCaseFilter)){
return true;
}
return false;
});
});
This is my testfragment where i build the list based on a switch:
public class TestFragment extends Fragment {
public String Workshop;
public int NumberOfQuestions;
public Button SaveButton;
public TextView GradeView;
public String Grades;
private OnFragmentInteractionListener mListener;
public TestFragment() {}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle bundle){
View rootView = inflater.inflate(R.layout.questionscomplete,
container, false);
Workshop = getArguments().getString("Workshoptitle");
GradeView = ((TextView) rootView.findViewById(R.id.GradeView));
// Inflate the layout for this fragment
if (!Workshop.equals("Doodlz Drawing")) {
rootView = inflater.inflate(R.layout.fragment_test,
container, false);
final ListView lv1 = (ListView) rootView.findViewById(R.id.listview);
ArrayList image_details = getListData();
lv1.setAdapter(new CustomListAdapter(getActivity(), image_details));
SaveButton = ((Button) rootView.findViewById(R.id.Save));
SaveButton.setOnClickListener(Grading);
}
return rootView;
}
private ArrayList getListData() {
ArrayList<QuestionItem> results = new ArrayList<QuestionItem>();
switch (Workshop) {
case "Android Studio":
Workshop = "Android Studio";
QuestionItem[] Item1 = new QuestionItem[3];
QItem WS1 = new QItem();
NumberOfQuestions = Item1.length;
String[] WS1Q = WS1.getQuestions(Workshop, NumberOfQuestions);
String[] WS1QA = WS1.getAnswers(Workshop);
for (int i = 0; i < NumberOfQuestions; i++) {
Item1[i] = new QuestionItem();
Item1[i].setQuestion(WS1Q[i]);
Item1[i].setAnswer1(WS1QA[i * 10 + 0]);
Item1[i].setAnswer2(WS1QA[i * 10 + 1]);
Item1[i].setAnswer3(WS1QA[i * 10 + 2]);
Item1[i].setAnswer4(WS1QA[i * 10 + 3]);
// Toast.makeText(getActivity(), Item1[i].GetAnswer(),
// Toast.LENGTH_LONG).show();
results.add(Item1[i]);
}
break;
case "Java Basics":
Workshop = "Java Basics";
QuestionItem[] Item2 = new QuestionItem[5];
QItem WS2 = new QItem();
NumberOfQuestions = Item2.length;
String[] WS2Q = WS2.getQuestions(Workshop, NumberOfQuestions);
String[] WS2QA = WS2.getAnswers(Workshop);
for (int i = 0; i < NumberOfQuestions; i++) {
Item2[i] = new QuestionItem();
Item2[i].setQuestion(WS2Q[i]);
Item2[i].setAnswer1(WS2QA[i * 10 + 0]);
Item2[i].setAnswer2(WS2QA[i * 10 + 1]);
Item2[i].setAnswer3(WS2QA[i * 10 + 2]);
Item2[i].setAnswer4(WS2QA[i * 10 + 3]);
results.add(Item2[i]);
// Toast.makeText(getActivity(), Item2[i].GetAnswer(),
// Toast.LENGTH_LONG).show();
}
break;
My listadapter:
public class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
public String Answer;
public String[] Answers;
private ArrayList<QuestionItem> listData;
public CustomListAdapter(Context aContext, ArrayList<QuestionItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.questions, null);
holder = new ViewHolder(
);
holder.QuestionView = (TextView) convertView.findViewById(R.id.q);
holder.Answer1View = (TextView) convertView.findViewById(R.id.qa1);
holder.Answer2View = (TextView) convertView.findViewById(R.id.qa2);
holder.Answer3View = (TextView) convertView.findViewById(R.id.qa3);
holder.Answer4View = (TextView) convertView.findViewById(R.id.qa4);
//
holder.Answer1Button = (RadioButton) convertView.findViewById(R.id.qa1);
holder.Answer2Button = (RadioButton) convertView.findViewById(R.id.qa2);
holder.Answer3Button = (RadioButton) convertView.findViewById(R.id.qa3);
holder.Answer4Button = (RadioButton) convertView.findViewById(R.id.qa4);
holder.ButtonGroupView = (RadioGroup) convertView.findViewById(R.id.group);
convertView.setTag(holder);
holder.ButtonGroupView.getCheckedRadioButtonId();
holder.ButtonGroupView
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
Integer pos = (Integer) group.getTag(); // To identify the Model object i get from the RadioGroup with getTag()
// an integer representing the actual position
QuestionItem element = listData.get(pos);
switch (checkedId) { //set the Model to hold the answer the user picked
case R.id.qa1:
element.setAnswer("1");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa2:
element.setAnswer("2");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa3:
element.setAnswer("3");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa4:
element.setAnswer("4");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
default:
element.setAnswer(null); // Something was wrong set to the default
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
QuestionItem element = (QuestionItem) getItem(position);
holder.QuestionView.setText(listData.get(position).getQuestion());
holder.Answer1View.setText(listData.get(position).Getanswer1());
holder.Answer2View.setText(listData.get(position).Getanswer2());
holder.Answer3View.setText(listData.get(position).Getanswer3());
holder.Answer4View.setText(listData.get(position).Getanswer4());
holder.ButtonGroupView.setTag(new Integer(position)); // I passed the current position as a tag
return convertView;
}
//
class ViewHolder {
TextView t = null;
TextView QuestionView;
TextView Answer1View;
TextView Answer2View;
TextView Answer3View;
TextView Answer4View;
RadioButton Answer1Button, Answer2Button, Answer3Button, Answer4Button;
RadioGroup ButtonGroupView;
}}
My question Item:
public class QuestionItem {
private String Question;
private String Answer1;
private String Answer2;
private String Answer3;
private String Answer4;
private String Answer;
public String getQuestion() {
return Question;
}
public void setQuestion(String Question) {
this.Question = Question;
}
public String Getanswer1() {
return Answer1;
}
public void setAnswer1(String Answer1) {
this.Answer1 = Answer1;
}
public String Getanswer2() {
return Answer2;
}
public void setAnswer2(String Answer2) {
this.Answer2 = Answer2;
}
public String Getanswer3() {
return Answer3;
}
public void setAnswer3(String Answer3) {
this.Answer3 = Answer3;
}
public String Getanswer4() {
return Answer4;
}
public void setAnswer4(String Answer4) {
this.Answer4 = Answer4;
}
public String GetAnswer() {
return Answer;
}
public void setAnswer(String Answer) {
this.Answer = Answer;
}
}
I want to save all the answers and compare them to the right answers and save the score to be used as a variable in another fragment.
UPDATE: added "Log.d(listData.get(pos).toString(), element.GetAnswer());" And i can see it is storing the choses answers so how do i request them in the testfragment and check them
Ive tried several things but cannot find the solution. pls help:)?
I have a listview in my main activity.In each row i have a image view,when i click that image view QuickAction(Like popover in ios) will appears.My request is, I want to setText the text from listview to the another Activity's edittext when i click the action item in the quick action.Please help..
Here is my Main Activity
public class ExampleActivity extends Activity {
private static final int ID_UP = 1;
private static final int ID_DOWN = 2;
private static final int ID_SEARCH = 3;
private static final int ID_INFO = 4;
private QuickAction quickAction;
private ActionItem nextItem;
private ActionItem prevItem;
private ActionItem searchItem;
private ListView view;
private ContactsAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (ListView) findViewById(R.id.listView1);
final Weather weather_data[] = new Weather[] { new Weather(R.drawable.icon, "Cloudy"),
new Weather(R.drawable.icon, "Showers"),
new Weather(R.drawable.icon, "Snow"),
new Weather(R.drawable.icon, "Storm"),
new Weather(R.drawable.icon, "Sunny")
};
adapter = new ContactsAdapter(this, R.layout.main1,
weather_data);
}
void functiontorun(View view1) {
quickAction = new QuickAction(this,QuickAction.HORIZONTAL);
nextItem = new ActionItem(ID_DOWN, "Next", getResources().getDrawable(
R.drawable.menu_down_arrow));
prevItem = new ActionItem(ID_UP, "Prev", getResources().getDrawable(
R.drawable.menu_up_arrow));
searchItem = new ActionItem(ID_SEARCH, "Find", getResources()
.getDrawable(R.drawable.menu_search));
// use setSticky(true) to disable QuickAction dialog being dismissed
// after an item is clicked
prevItem.setSticky(true);
nextItem.setSticky(true);
// add action items into QuickAction
quickAction.addActionItem(nextItem);
quickAction.addActionItem(prevItem);
quickAction.addActionItem(searchItem);
// Set listener for action item clicked
final int position1 = view.getPositionForView(view1);
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
if (actionId == ID_SEARCH) {
Intent i=new Intent(ExampleActivity.this,Second.class);
i.putExtra("position",position1 );
Log.v("position","po" +position1);
startActivity(i);
} else if (actionId == ID_INFO) {
Toast.makeText(getApplicationContext(),
"I have no info this time",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
actionItem.getTitle() + " selected",
Toast.LENGTH_SHORT).show();
}
}
});
quickAction.show(view1);
}
}
And my another activity
public class Second extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
EditText d1=(EditText) findViewById(R.id.editText1);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
final int position = (Integer) bundle.get("position");
Log.v("position","po1 " +position);
ArrayList<Weather> array = new ArrayList<Weather>();
Log.v("position","po1 " +array);
}
}
}
contacts adapter:
public class ContactsAdapter extends ArrayAdapter{
Context context;
int layoutResourceId;
Weather data[] = null;
public ContactsAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imageView1);
holder.imgIcon.findViewById(R.id.imageView1).setOnClickListener(mBuyButtonClickListener);
holder.txtTitle = (TextView)row.findViewById(R.id.textView1);
//((ImageView) row.findViewById(R.id.im)).setOnClickListener(mBuyButtonClickListener);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
((ExampleActivity) context).functiontorun(v);
}
};
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
WeatherHolder holder = (WeatherHolder) v.getTag;
String string = holder.txtTitle .getText();
((ExampleActivity) context).functiontorun(string);
}
};
just pass the string to your activity and change the parameter of the functiontorun as string