I am using TableView, in this there a button to delete the row, S.no column have to update automatically
public void Delete()
{
int myIndex =
MyTable.getSelectionModel().getSelectedIndex();
System.out.println(myIndex);
ObservableList<Parent> selectedRow, allParents;
allParents = MyTable.getItems();
selectedRow = MyTable.getSelectionModel().getSelectedItems();
for(Parent parent : selectedRow)
{
allParents.remove(parent);
}
for (int i=myIndex; ts.getCellData(i)!=null;i++)
{
System.out.println(i+1);
// I need here to update my column with the following values
MyTable.getItems().forEach(item -> item.setId(k));
// I tried the above code but it display the same values in the S.no column
}
}
// This is my TableView Model
public class Parent {
private SimpleStringProperty ts, eo;
private SimpleIntegerProperty id;
Parent(Integer id, String ts, String eo){
this.id= new SimpleIntegerProperty(id);
this.ts= new SimpleStringProperty(ts);
this.eo= new SimpleStringProperty(eo);
}
public Integer getId() {
return id.get();
}
public void setId(Integer id) {
this.id.set(id);
}
public String getTs() {
return ts.get();
}
public void setTs(String ts) {
this.ts.set(ts);
}
public String getEo() {
return eo.get();
}
public void setEo(String eo) {
this.eo.set(eo);
}
}
expecting the results in S.no is
1
2
3
4
5
6
but results are getting like
1
2
3
5
6
Related
I know how to read or show all data inserted in the database but I don't know how to query a specific data. In the my database is in Post.cs it will store date/time and get 2 datas from user.
so like this: enter image description here
Column1(ID), Column2(Date), (column3(rain1), column4(rain2).
1 12/13/2019 21 22
2 12/16/2019 21 22
3 12/16/2019 11 12
I want to do: if (rain1 && rain2) have the same date. I would like to add 2data from rain1 which is 21+11 and save the total to rain1total=32 then rain2total would be 34. I don't know where to start
here is Post.cs
namespace listtoPDF.Model
{
//Post table, user posting drainvolume
//this is the source of Binding
public class Post: INotifyPropertyChanged
{
private double? rain1Vol;
private double? rain2Vol;
//from settingspage to show up in history
string rain1lbl = Settings.Drain1LocationSettings;
string rain2lbl = Settings.Drain2LocationSettings;
//ID primary key that we will autoincrement
//These are columns ID, drain1 to 8 so 9 columns
//These are binding source for Historypage
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public static bool showLabel { get; set; } //public class model
public string rain1Lbl
{
get => rain1lbl;
set => rain1lbl= Settings.Drain1LocationSettings;
}
public string rain2Lbl
{
get => rain2lbl;
set => rain2lbl= Settings.Drain2LocationSettings;
}
public string CDateTime { get; set; }
[MaxLength(3)]
public double? rain1vol
{
get { return rain1Vol; }
set
{
rain1Vol = value;
RaisePropertyChanged("rain1vol");
}
}
[MaxLength(3)]
public double? rain2vol
{
get { return rain2Vol; }
set
{
rain2Vol = value;
RaisePropertyChanged("rain2vol");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
}
here is the main that will list data entered with date
namespace listtoPDF
{
public partial class MainPage : ContentPage
{
List<Post> posts;
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
conn.CreateTable<Post>();
posts = conn.Table<Post>().ToList();
postListView.ItemsSource = posts;
conn.Close();
//right click quickwatch
}
void addbuttonHandle_Clicked(object sender, EventArgs args)
{
Navigation.PushModalAsync(new AddRainsPage());
}
private void GetValues()
{
//Initiate SQLite connection
//Create table with class
//Get the values in table
//close the line
SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
conn.CreateTable<Post>();
posts = conn.Table<Post>().ToList();
conn.Close();
}
}
Here is the page where i need query the add a certain column so i can add the data associated to it. So far it's connecting to the sqlite.
namespace listtoPDF
{
public partial class selecteddataPage : ContentPage
{
List<Post> posts;
public selecteddataPage()
{
InitializeComponent();
}
private void GetValues()
{
//Initiate SQLite connection
//Create table with class
//Get the values in table
//close the line
SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
conn.CreateTable<Post>();
posts = conn.Table<Post>().ToList();
**if (Post.rain1 values have the same date )
{
totalrain1= then add data that have same date
}
if (Post.rain2 values have the same date )
{
totalrain1= then add data that have same date
}**
conn.Close();
}
}
}
In the JavaFx ComboBox which uses a class object list .I want to select items in the ComboBox programmatically using getSelectionModel().select(object or index). i am not getting the desired result Although the value is set but it is something like this main.dao.Company.Company.CompanyTableData#74541e7b.
The code is somewhat like this.
ComboBox<CompanyTableData> company = new ComboBox<>();
company.setItems(GetCompany.getCompanyTableData());//where Observable list is set..
GetCompany.getCompanyTableData() returns observablelist of CompanyTableData class.
The ComboBox Looks as follows.
The CompanyTableData Class is as.
public class CompanyTableData {
private SimpleStringProperty itemCompanyId;
private SimpleStringProperty itemCompanyName;
private SimpleStringProperty createBy;
private SimpleStringProperty createdOn;
public CompanyTableData(CompanyData companyData){
this.itemCompanyId = new SimpleStringProperty(companyData.getItemCompanyId());
this.itemCompanyName = new SimpleStringProperty(companyData.getItemCompanyName());
this.createBy = new SimpleStringProperty(companyData.getCreatedBy());
this.createdOn = new SimpleStringProperty(companyData.getCreatedOn());
}
public String getItemCompanyId() {
return itemCompanyId.get();
}
public SimpleStringProperty itemCompanyIdProperty() {
return itemCompanyId;
}
public void setItemCompanyId(String itemCompanyId) {
this.itemCompanyId.set(itemCompanyId);
}
public String getItemCompanyName() {
return itemCompanyName.get();
}
public SimpleStringProperty itemCompanyNameProperty() {
return itemCompanyName;
}
public void setItemCompanyName(String itemCompanyName) {
this.itemCompanyName.set(itemCompanyName);
}
public String getCreateBy() {
return createBy.get();
}
public SimpleStringProperty createByProperty() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy.set(createBy);
}
public String getCreatedOn() {
return createdOn.get();
}
public SimpleStringProperty createdOnProperty() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn.set(createdOn);
}
}
The Cell Factory is set
company.setCellFactory(param -> new CompanyCell());
And the CompanyCell
public class CompanyCell extends ListCell<CompanyTableData> {
#Override
protected void updateItem(CompanyTableData item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item.getItemCompanyName() == null) {
setText(null);
} else {
setText(item.getItemCompanyName());
}
}
}
After all this when i try to set the items programmetically as
company.getSelectionModel().select(getSelectedCompanyIndex());
The getSelectedCompanyIndex() function is as follows.
public static CompanyTableData getSelectedCompanyIndex(){
CompanyTableData c = null,i;
Iterator<CompanyTableData> itr = GetCompany.getCompanyTableData().iterator();
while (itr.hasNext()){
i = itr.next();
if (i.getItemCompanyName().equals(Element.getItemTableData().getCompany())){
c = i;
}
}
return c;
}
And the result i am getting is
And
At the end it should select a name or item in the list but it has set some type of object i think.
Now what should i do. Is there any type of string conversion required.
The buttonCell used to display the item when the combobox popup is not shown is not automatically created using the cellFactory. You need to set this property too to use the same cell implementation:
company.setCellFactory(param -> new CompanyCell());
company.setButtonCell(new CompanyCell());
I want to populate a dynamic tableview from database with 32 columns,First column contain the name of employee and remaining 31 columns for marking employee attendence from day1 to day31(checkbox).But I can able to populate tableview from database with 2 columns(name,checkbox) using get and set methods.Here is my code
String sql ="SELECT * FROM attendence";
pst = (PreparedStatement) con.prepareStatement(sql);
rs=pst.executeQuery();
while (rs.next()) {
//get string from db,whichever way
String name=rs.getString(3);
int day=rs.getInt(6);
data.add(new User(name,day!=0)); //converting integer to boolean and storing on data(Observable list)
}
etname.setCellValueFactory(new PropertyValueFactory<>("name"));
col.setCellValueFactory(new PropertyValueFactory<>("day1));
col.setCellFactory(new Callback<TableColumn<User, Boolean>, TableCell<User, Boolean>>() {
public TableCell<User, Boolean> call(TableColumn<User, Boolean> p) {
return new CheckBoxTableCell<User, Boolean>();
}
});
jTable.getColumns().add(etname,col);
jTable.setItems(data);
}
This is User.java
public class User {
private final SimpleStringProperty ename;
private BooleanProperty day1;
User(String Ename,boolean day1)
{
this.ename = new SimpleStringProperty(Ename);
this.day1 = new SimpleBooleanProperty(day1);
this.day1.addListener(new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
System.out.println(enameProperty().get() + " invited: " + t1);
System.out.println();
}
});
}
public String getEname() {
return ename.get();
}
public void setEname(String Ename) {
ename.set(Ename);
}
public BooleanProperty day1Property() {
return day1;
}
public StringProperty enameProperty() {
return ename;
}
CheckBoxTableCell.java
public class CheckBoxTableCell<S, T> extends TableCell<S, T> {
private final CheckBox checkBox;
private ObservableValue<T> ov;
public CheckBoxTableCell() {
this.checkBox = new CheckBox();
this.checkBox.setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
setGraphic(checkBox);
}
#Override public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setGraphic(checkBox);
if (ov instanceof BooleanProperty) {
checkBox.selectedProperty().unbindBidirectional((BooleanProperty) ov);
}
ov = getTableColumn().getCellObservableValue(getIndex());
if (ov instanceof BooleanProperty) {
checkBox.selectedProperty().bindBidirectional((BooleanProperty) ov);
}
}
}
}
But no idea how i can do with 32 columns.
So i need a big help from anyone for my 2 problems.
1) How i can populate dynamic tableview from database with checkboxes 2) when i press a button should read all the names along with checkbox status(isSelected or not selected) like
jhon true true false ... ....
rose false false true ... ..
george true true true false
Answers will be appreciated.Thank you in advance.
.. ..
try with this code.
private static final List<String> groups = Arrays.asList("Group 1", "Group 2", "Group 3", "Group 4"); //declared an array
TableView<AttributeRow> attributeTable = new TableView<>(); //new Table
for (String group : groups) { //Creating dynamic column
TableColumn<AttributeRow, Boolean> groupColumn = new TableColumn<>(group);
groupColumn.setCellFactory(CheckBoxTableCell.forTableColumn(groupColumn));
groupColumn.setCellValueFactory(cellData -> cellData.getValue().activeProperty(group));
attributeTable.getColumns().add(groupColumn);
}
and AttributeRow class
class AttributeRow {
private final Map<String, BooleanProperty> activeByGroup = new HashMap<>();
public AttributeRow(List<String> companyGroups) {
for (String group : companyGroups) {
activeByGroup.put(group, new SimpleBooleanProperty()) ;
}
}
public final BooleanProperty activeProperty(String group) {
return activeByGroup.get(group) ;
}
public final boolean isActive(String group) {
return activeProperty(group).get();
}
public final void setActive(String group, boolean active) {
activeProperty(group).set(active);
}
For loading checkbox data(true or false) we can use following method
String sql ="SELECT * FROM attendence";
pst = (PreparedStatement) con.prepareStatement(sql);
rs=pst.executeQuery();
while (rs.next()) {
AttributeRow row = new AttributeRow(groups);
for(int j=0;j<5;j++) //here j<5 because array size =5
{
int i=j+6;
int day=rs.getInt(i); //getting Integer value(note:sqlite does not support boolean datatype so i stored as integer with 0 or 1)
row.setActive(day!=0); //converted into boolean useing day!=0
}
jTable.getItems().add(row);
}
I need to order the list of items based on a field say starredAt
I am loading the data in the recyclerview from Realm DB using RealmRecyclerView by thorbenprimke
The field changes it value on user's action i.e when user presses star button the item should be moved to top.
For this I am just updating the starredAt field of the object.
The items are already sorted by starredAt so realm loads the updated list but it randomly adds one more item to the recyclerview.
CheatSheet.java
public class CheatSheet extends RealmObject {
#PrimaryKey
private String id;
private RealmList<Item> items;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public RealmList<Item> getItems() {
return items;
}
public void setItems(RealmList<Item> items) {
this.items = items;
}
}
Item.java
public class Item extends RealmObject {
#PrimaryKey
private String id;
private String description;
private Date starredAt;
public Item() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getStarredAt() {
return starredAt;
}
public void setStarredAt(Date starredAt) {
this.starredAt = starredAt;
}
}
CheatSheetActivity.java
public class MainActivity extends AppCompatActivity {
RealmRecyclerView revItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setData();
}
private void setData() {
rvItems = (RealmRecyclerView) findViewById(R.id.rev_items);
RealmResults<Item> items = Realm.getDefaultInstance().where(CheatSheet.class)
.equalTo("id", "some-id").findFirst().getItems()
.where()
.findAllSorted("starredAt", Sort.DESCENDING);
ItemRealmListAdapter itemRealmListAdapter =
new ItemRealmListAdapter(this, items,
true, true);
rvItems.setAdapter(itemRealmListAdapter);
}
ItemRealmListAdapter.java
public class ItemRealmListAdapter extends RealmBasedRecyclerViewAdapter<Item,
ItemRealmListAdapter.ItemViewHolder> {
RealmResults<Item> mItems;
public ItemRealmListAdapter(Context context, RealmResults<Item> realmResults,
boolean automaticUpdate, boolean animateResults) {
super(context, realmResults, automaticUpdate, animateResults);
this.mItems = realmResults;
}
#Override
public ItemViewHolder onCreateRealmViewHolder(ViewGroup viewGroup, int i) {
return new ItemViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_layout_cs_text, viewGroup, false));
}
public Item getItem(int position) {
return mItems.get(position);
}
#Override
public void onBindRealmViewHolder(ItemViewHolder itemViewHolder, int position) {
itemViewHolder.txtBody.setText(getItem(position).getDescription());
if (getItem(position).getStarredAt() != null) {
itemViewHolder.imvStar.setImageResource(R.drawable.ic_star_yellow);
}
itemViewHolder.imvStar.setOnClickListener(v -> handleStarClick(v,position));
}
private void handleStarClick(View v, int position) {
if (getItem(position).getStarredAt() != null) {
((ImageView) v).setImageResource(R.drawable.ic_star);
CheatSheetStorage.unStarItem("some-id", getItem(position));
} else {
((ImageView) v).setImageResource(R.drawable.ic_star_yellow);
CheatSheetStorage.starItem("some-id", getItem(position));
}
}
public static class ItemViewHolder extends RealmViewHolder {
#Bind(R.id.txt_cheat_sheet)
TextView txtBody;
#Bind(R.id.img_star)
ImageView imvStar;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
CheatSheetStorage.java
public class CheatSheetStorage {
public static void unStarItem(String cheatSheetId, Item item) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CheatSheet cheatSheet = getCheatSheetById(cheatSheetId);
Item itemDB = cheatSheet.getItems().where().equalTo("id", item.getId()).findFirst();
itemDB.setStarredAt(null);
realm.commitTransaction();
}
public static void starItem(String cheatSheetId, Item item) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CheatSheet cheatSheet = getCheatSheetById(cheatSheetId);
Item itemDB = cheatSheet.getItems().where().equalTo("id", item.getId()).findFirst();
itemDB.setStarredAt(new Date());
realm.commitTransaction();
}
}
Please refer following screenshots for clearer idea :
Screenshot before starring
Screenshot after starring the sixth item
#Rohan-Peshkar - You will have to provide a animateExtraColumnName value to the adapter. For the animations, the adapter keeps track of the items and since that item's id doesn't change, the list isn't updated. With an additional column (in your case that should be the starredAt column - as long as it is stored as an Integer), the diffing algorithm will detect a change and the order is updated.
For reference: https://github.com/thorbenprimke/realm-recyclerview/blob/2835a543dce20993d8f98a4f773fa0e67132ce52/library/src/main/java/io/realm/RealmBasedRecyclerViewAdapter.java#L177
You can also check out the MainActivity in the example folder. The example changes a row's text from "ABC" to "Updated ABC" and the list recognizes the change because both the primary key and the quote field are used to basically create a composite key for diffing purposes.
In a JavaFX TreeView I'm using 'custom' classes which extend TreeItem. This makes me able to edit the items in the TreeView (I can double click them and edit the contents when running the application) but I can't seem to be able to set the .setOnEditCommit() method properly. I was hoping it'd work similar as the function in a tableview but I didn't have any luck yet.
This is my code in my controller in which I try to set the setOnEditCommit() method. In my TreeView called 'trvDivisies' I display football team divisions / competitions and one level lower I display all the teams that are in a certain division.
private void setUpTreeView() {
trvDivisies.setEditable(true);
trvDivisies.setShowRoot(false);
TreeItem<String> root = new TreeItem<>();
for (Divisie d : divisies) {
TreeItem<String> divisieTreeItem = d;
divisieTreeItem.valueProperty().set(d.getNaam());
for (VoetbalTeam vt : d.getVoetbalTeams()) {
TreeItem<String> voetbalTeamTreeItem = vt;
voetbalTeamTreeItem.valueProperty().setValue(vt.getTeamNaam());
divisieTreeItem.getChildren().add(voetbalTeamTreeItem);
}
root.getChildren().add(divisieTreeItem);
}
trvDivisies.setRoot(root);
trvDivisies.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
System.out.println(newValue);
}
});
trvDivisies.setCellFactory(TextFieldTreeCell.forTreeView());
// I get an error at the following line when compiling
trvDivisies.setOnEditCommit((TreeView.EditEvent p) -> {
TreeItem<String> selectedItem = p.getTreeItem();
if (selectedItem instanceof Divisie) {
updateDivisie((Divisie)selectedItem);
} else if (selectedItem instanceof VoetbalTeam) {
updateTeam((VoetbalTeam)selectedItem);
}
});
}
This is what my 'custom' classes look like.
public class Divisie extends TreeItem<String> {
private static int idCount = 0;
private int id;
private String naam;
private List<VoetbalTeam> voetbalTeams;
public int getId() {
return id;
}
public String getNaam() {
return naam;
}
public List<VoetbalTeam> getVoetbalTeams() {
return voetbalTeams;
}
public Divisie(int id, String naam) {
super(naam);
this.id = id;
this.naam = naam;
}
public Divisie(String naam) {
this.id = ++idCount;
this.naam = naam;
}
public void addTeam(VoetbalTeam toBeAdded) {
if (voetbalTeams == null) {
voetbalTeams = new LinkedList<>();
}
voetbalTeams.add(toBeAdded);
}
#Override
public String toString() {
return this.naam;
}
}
Second 'lower level' class
public class VoetbalTeam extends TreeItem<String> {
private static int idCount = 0;
private int id;
private String teamNaam;
private List<Speler> spelers;
public int getId() {
return id;
}
public String getTeamNaam() {
return teamNaam;
}
public List<Speler> getSpelers() {
return this.spelers;
}
public VoetbalTeam(int id, String teamNaam) {
super(teamNaam);
this.id = id;
this.teamNaam = teamNaam;
}
public VoetbalTeam(String teamNaam) {
super(teamNaam);
this.id = ++idCount;
this.teamNaam = teamNaam;
}
public void addSpeler(Speler nieuweSpeler) {
if (spelers == null) {
spelers = new LinkedList<>();
}
this.spelers.add(nieuweSpeler);
}
#Override
public String toString() {
return this.teamNaam;
}
}
When trying to run the application WITH the .setOnEditCommit() method I get an error saying:
Error:(97, 37) java: incompatible types: incompatible parameter types in lambda expression
I was hoping you guys can tell me what I need to change my TreeView.EditEvent lambda to or help me find an easier solution.
For a TreeView<T>, the signature of setOnEditCommit is
void setOnEditCommit(EventHandler<TreeView.EditEvent<T>> value)
Since you have (apparently) a TreeView<String>, you need
trvDivisies.setOnEditCommit((TreeView.EditEvent<String> p) -> {
// ...
});
Or, of course, you can just let the compiler do the work for you:
trvDivisies.setOnEditCommit(p -> {
// ...
});