This is what I have
public class AddNewCategoryController implements Initializable {
@FXML
private TextField name;
@FXML
private TextField description;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
public void save(){
final AtomicLong identifier = new AtomicLong(5);
Long id = identifier.incrementAndGet();
String catgoryName = name.getText();
String categoryDescription = description.getText();
Category category = new Category(id,catgoryName,categoryDescription);
ReadingDataFromFiles.writeCategory(category);
}
}
When the programs runs there's a screen to add a new category and the user has to write category's name and description but ID should be automatic and should be increased every time the user enters a new Category. The way I've done it doesn't work as intended, it's increased only once but since initial value stays 5 it's always 6.
Move this line:
final AtomicLong identifier = new AtomicLong(5);
… higher up, outside the method, to be a member field on the class.
In your existing code, each call to that save
method is creating a new AtomicLong
to replace the previous one. So your counting cannot accumulate.
Proper naming can help clarify. That AtomicLong
is not an “identifier”. It is an “identifierGenerator”. Each number returned by its incrementAndGet
method is the “identifier”.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.