I'm using a HashMap. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this in Vala? In Java there is LinkedHashMap but I don't see any equivalent for Gee.Map.
As far as I know, there is no equivalent of LinkedHashMap in Vala. Using a TreeMap and setting the comparison function to always return 1 (or -1 if you want the reverse order) for other Map entries will preserve the order and allow you to iterate through the Map in the order that items were added but get will not function as expected.
Unfortunately, after thoroughly examining the Gee source, there appears to be no way other than to roll your own. The most straightforward way is to subclass HashMap and use an ArrayList to keep a track of the order of the keys as they are inserted. You could also use a LinkedList, you would only need to change the internal ArrayList _keys field to a LinkedList. The choice depends on your use case. From the docs -
This implementation (ArrayList) is pretty good for rarely modified data. Because they are stored in an array this structure does not fit for highly mutable data.
The following is a basic implementation, in Vala (arrayhashmap.vala):
using Gee;
public class ArrayHashMap<K,V> : HashMap<K,V> {
private weak Set<K> _keyset;
private weak Collection<V> _values;
private weak Set<Entry<K,V>> _entries;
internal ArrayList<K> _keys = new ArrayList<K>();
private class KeySet<K> : AbstractSet<K> {
private weak ArrayList<K> _keys;
public KeySet (ArrayList<K> keys) {
_keys = keys;
}
public override Iterator<K> iterator () {
return _keys.iterator();
}
public override int size {
get { return _keys.size; }
}
public override bool read_only {
get { return true; }
}
public override bool add (K key) {
assert_not_reached ();
}
public override void clear () {
assert_not_reached ();
}
public override bool remove (K key) {
assert_not_reached ();
}
public override bool contains (K key) {
return _keys.contains (key);
}
}
private class ValueCollection<K,V> : AbstractCollection<V> {
private weak ArrayHashMap<K,V> _map;
public ValueCollection (ArrayHashMap map) {
_map = map;
}
public override Iterator<V> iterator () {
return new ValueIterator<K,V> (_map);
}
public override int size {
get { return _map.size; }
}
public override bool read_only {
get { return true; }
}
public override bool add (V value) {
assert_not_reached ();
}
public override void clear () {
assert_not_reached ();
}
public override bool remove (V value) {
assert_not_reached ();
}
public override bool contains (V value) {
Iterator<V> it = iterator ();
while (it.next ()) {
if (_map.value_equal_func (it.get (), value)) {
return true;
}
}
return false;
}
}
private class ValueIterator<K,V> : Object, Traversable<V>, Iterator<V> {
protected weak ArrayHashMap<K,V> _map;
protected Iterator<K> _keys;
public ValueIterator (ArrayHashMap<K,V> map) {
_map = map;
_keys = map._keys.iterator();
}
public bool next () {
return _keys.next();
}
public bool has_next () {
return _keys.has_next();
}
public virtual bool read_only {
get {
return true;
}
}
public bool valid {
get {
return _keys.valid;
}
}
public new V get () {
return _map.get(_keys.get());
}
public void remove () {
assert_not_reached ();
}
public bool foreach(ForallFunc<V> f) {
foreach (K key in _map._keys)
if (!f(_map.get(key)))
return false;
return true;
}
}
private class EntrySet<K,V> : AbstractSet<Entry<K, V>> {
private weak ArrayHashMap<K,V> _map;
public EntrySet (ArrayHashMap<K,V> map) {
_map = map;
}
public override Iterator<Entry<K, V>> iterator () {
return new EntryIterator<K,V> (_map);
}
public override int size {
get { return _map.size; }
}
public override bool read_only {
get { return true; }
}
public override bool add (Entry<K, V> entry) {
assert_not_reached ();
}
public override void clear () {
assert_not_reached ();
}
public override bool remove (Entry<K, V> entry) {
assert_not_reached ();
}
public override bool contains (Entry<K, V> entry) {
return _map.has (entry.key, entry.value);
}
}
private class EntryIterator<K,V> : Object, Traversable<Entry<K,V>>, Iterator<Entry<K,V>> {
protected weak ArrayHashMap<K,V> _map;
protected Iterator<K> _keys;
public EntryIterator (ArrayHashMap<K,V> map) {
_map = map;
_keys = map._keys.iterator();
}
public bool next () {
return _keys.next();
}
public bool has_next () {
return _keys.has_next();
}
public virtual bool read_only {
get {
return true;
}
}
public bool valid {
get {
return _keys.valid;
}
}
public new Entry<K,V> get () {
K* k = _keys.get();
var ent = new Entry<K,V>(k, _map.get(k));
return ent;
}
public void remove () {
assert_not_reached ();
}
public bool foreach(ForallFunc<Entry<K,V>> f) {
foreach (K key in _map._keys)
if (!f(new Entry<K,V>(key, _map.get(key))))
return false;
return true;
}
}
public class Entry<K,V> : Map.Entry<K,V> {
weak K _key;
weak V _value;
public override K key {
get {
return _key;
}
}
public override V value {
get {
return _value;
} set {
_value = value;
}
}
public override bool read_only {get { return true; }}
public Entry (K key, V value) {
this._key = key;
this._value = value;
}
}
public new void #set(K key, V value) {
if (!_keys.contains(key))
_keys.add(key);
base.set(key, value);
}
public new void unset(K key, out V? value = null) {
_keys.remove(key);
base.unset(key, out value);
}
public new void clear() {
base.clear();
_keys.clear();
}
public new Set<unowned K> keys {
owned get {
Set<K> keys = _keyset;
if (_keyset == null) {
keys = new KeySet<K> (_keys);
_keyset = keys;
keys.add_weak_pointer ((void**) (&_keyset));
}
return keys;
}
}
public new Collection<unowned V> values {
owned get {
Collection<K> values = _values;
if (_values == null) {
values = new ValueCollection<K,V> (this);
_values = values;
values.add_weak_pointer ((void**) (&_values));
}
return values;
}
}
public override Set<Entry<K,V>> entries {
owned get {
Set<Entry<K,V>> entries = _entries;
if (_entries == null) {
entries = new EntrySet<K,V> (this);
_entries = entries;
entries.add_weak_pointer ((void**) (&_entries));
}
return entries;
}
}
}
You can test it with this awful test case (tests.vala):
public static void doTest() {
const string[] strings = { "test", "another", "one-more", "how-about-this-one", "even-more" };
var entries3 = new ArrayHashMap<string, int>();
for (int i = 0; i < strings.length; i++)
entries3.set(strings[i], i);
entries3.unset("one-more");
foreach (var entry in entries3.keys)
message ("%s:%d", entry, entries3.get(entry));
entries3.set ("for-your-viewing-pleasure", 3);
foreach (var entry in entries3.keys)
message ("%s:%d", entry, entries3.get(entry));
entries3.set ("for-your-viewing-pleasure", 7);
foreach (var entry in entries3.entries)
message ("%s:%d", entry.key, entries3.get(entry.key));
}
public static int main (string[] args) {
Test.init(ref args);
Test.add_func ("/ArrayHashMap", doTest);
Test.run();
return 0;
}
Run the whole package together:
valac --pkg gee-0.8 -g tests.vala arrayhashmap.vala
This is a very rough implementation, based on how HashMap works internally. You may want to refactor it for better maintainability and write some more unit tests. If you find any problems, let me know and we can work through them.
I hope this helps.
Never heard of Vala, but it's easy to do (roughly) on your own what LinkedHashMap does internally. Write a wrapper that contains a doubly linked list of keys along with the hash map. Values in the map must consist of pairs, where one element is the actual map value and the other is a reference to the linked list node for the key. For each add, enqueue the key at the end of the list in addition to adding the key-><value, node ptr> entry to the map. For each remove, delete the associated key from the list using the node pointer (a constant time operation due to the double links), then remove the entry from the map. To look up a key, use the map. To traverse in insertion order, traverse the list.
Okay, since the originally accepted answer turned out to be incorrect, here's a quick and dirty working example in Java. I'll let you translate to Vala.
import java.util.HashMap;
import java.util.Iterator;
public class MyLinkedHashMap<K, V> implements Iterable<K> {
private final HashMap<K, Pair<K, V>> map = new HashMap<>();
private final Link<K> header = makeHeader();
/** Hash value along with a link reference to support remove(). */
private static class Pair<K, V> {
V value;
Link<K> link;
Pair(V value, Link<K> link) {
this.value = value;
this.link = link;
}
}
/** A link in the doubly linked list of keys. */
private static class Link<K> {
K key;
Link<K> prev;
Link<K> next;
Link() {}
Link(K key, Link<K> prev, Link<K> next) {
this.key = key;
this.prev = prev;
this.next = next;
}
}
#Override
public Iterator<K> iterator() {
return new MyLinkedHashMapIterator();
}
/** Iterator over map keys guaranteed to produce insertion order. */
private class MyLinkedHashMapIterator implements Iterator<K> {
private Link<K> ptr = header.next;
#Override
public boolean hasNext() {
return ptr != header;
}
#Override
public K next() {
K key = ptr.key;
ptr = ptr.next;
return key;
}
}
/** Make a header for a circular doubly linked list. */
private static <K> Link<K> makeHeader() {
Link<K> header = new Link<K>();
return header.next = header.prev = header;
}
/** Put a key/value in the map, remembering insertion order with a link in the list. */
public V put(K key, V value) {
Link<K> link = new Link<K>(key, header.prev, header);
link.prev.next = link;
header.prev = link;
Pair<K, V> pair = map.put(key, new Pair<>(value, link));
return pair == null ? null : pair.value;
}
/** Get the value mapped to a key or return {#code null} if none. */
public V get(K key) {
Pair<K, V> pair = map.get(key);
return pair == null ? null : pair.value;
}
/** Remove a key from both map and linked list. */
public V remove(K key) {
Pair<K, V> pair = map.remove(key);
if (pair == null) {
return null;
}
pair.link.prev.next = pair.link.next;
pair.link.next.prev = pair.link.prev;
return pair.value;
}
/** Trivial unit test. */
public static void main(String [] args) {
MyLinkedHashMap<String, Integer> map = new MyLinkedHashMap<>();
int n = 0;
for (String key : new String [] { "one", "two", "three", "four", "five", "six", "seven" }) {
map.put(key, ++n);
}
for (String key : map) {
System.out.println("For key " + key + " we have " + map.get(key));
}
String [] evenKeys = new String [] { "two", "four", "six" };
for (String evenKey : evenKeys) {
map.remove(evenKey);
}
System.out.println("After even keys removed...");
for (String key : map) {
System.out.println("For key " + key + " we have " + map.get(key));
}
n = 0;
for (String evenKey : evenKeys) {
map.put(evenKey, n += 2);
}
System.out.println("After putting them back again...");
for (String key : map) {
System.out.println("For key " + key + " we have " + map.get(key));
}
}
}
This produces:
For key one we have 1
For key two we have 2
For key three we have 3
For key four we have 4
For key five we have 5
For key six we have 6
For key seven we have 7
After even keys removed...
For key one we have 1
For key three we have 3
For key five we have 5
For key seven we have 7
After putting them back again...
For key one we have 1
For key three we have 3
For key five we have 5
For key seven we have 7
For key two we have 2
For key four we have 4
For key six we have 6
Related
I have a AutoCompleteTextView that I give it 2 different adapters depending on the amount of text that is being present at the textview - if it has 0 characters I want it to display a list of "recently searched" strings adapter, while if it has more than 1 characters I want it to display auto completion list.
My getRecentlySearchedQueries method along with the RecentSearchedViewModel-
private List<String> recentlySearchedQueries = new ArrayList<>(); // pasted from the top of the class
#Override
public void getRecentlySearchedQueries() {
recentSearchViewModel.getAllQueries().observe(getActivity(), databaseRecentlySearchList -> {
if (databaseRecentlySearchList == null) {
return;
}
for (int i = 0; i < databaseRecentlySearchList.size(); i++) {
Log.d("localDBValue", "Added value - " + databaseRecentlySearchList.get(i).toString() + "\n");
String query = databaseRecentlySearchList.get(i).getQuery();
recentlySearchedQueries.add(query);
}
//Log.d("localDBValue", "recent search list value - " + recentlySearchedQueries);
});
}
public class RecentSearchViewModel extends AndroidViewModel {
private RecentSearchRepository recentSearchRepository;
private LiveData<List<RecentSearchModel>> allRecentlySearched;
public RecentSearchViewModel(#NonNull Application application) {
super(application);
recentSearchRepository = new RecentSearchRepository(application);
allRecentlySearched = recentSearchRepository.getAllRecentSearches();
}
public void insert(RecentSearchModel model) {
recentSearchRepository.insert(model);
}
public void update(RecentSearchModel model) {
// add implementation in the future if needed
}
public void delete(RecentSearchModel model) {
// add implementation in the future if needed
}
public LiveData<List<RecentSearchModel>> getAllQueries() {
return allRecentlySearched;
}
}
public class RecentSearchRepository {
private RecentSearchDao recentSearchDao;
private LiveData<List<RecentSearchModel>> allRecentSearches;
public RecentSearchRepository(Application application) {
MarketplaceDatabase database = MarketplaceDatabase.getRecentSearchInstance(application);
recentSearchDao = database.recentSearchDao();
allRecentSearches = recentSearchDao.getRecentSearchList();
}
public void insert(RecentSearchModel model) {
new RecentSearchRepository.InsertRecentSearchAsyncTask(recentSearchDao).execute(model);
}
public void update (RecentSearchModel model) {
//TODO - implement in future if needed
}
public void delete(RecentSearchModel model) {
//TODO - implement in future if needed
}
public LiveData<List<RecentSearchModel>> getAllRecentSearches() {
return allRecentSearches;
}
private static class InsertRecentSearchAsyncTask extends AsyncTask<RecentSearchModel, Void, Void> {
private RecentSearchDao recentSearchDao;
public InsertRecentSearchAsyncTask(RecentSearchDao recentSearchDao) {
this.recentSearchDao = recentSearchDao;
}
#Override
protected Void doInBackground(RecentSearchModel... recentSearchModels) {
recentSearchDao.insert(recentSearchModels[0]);
return null;
}
}
private static class UpdateRecentSearchAsyncTask extends AsyncTask<RecentSearchModel, Void, Void> {
private RecentSearchDao recentSearchDao;
public UpdateRecentSearchAsyncTask(RecentSearchDao recentSearchDao) {
this.recentSearchDao = recentSearchDao;
}
#Override
protected Void doInBackground(RecentSearchModel... recentSearchModels) {
recentSearchDao.update(recentSearchModels[0]);
return null;
}
}
}
#Dao
public interface RecentSearchDao {
#Insert()
void insert(RecentSearchModel model);
#Update
void update(RecentSearchModel model);
#Delete
void delete(RecentSearchModel model);
#Query("select * from recent_search_table")
LiveData<List<RecentSearchModel>> getRecentSearchList();
}
#Entity(tableName = "recent_search_table")
public class RecentSearchModel {
#PrimaryKey(autoGenerate = true)
private int ID;
private String query;
public RecentSearchModel(){
}
public RecentSearchModel(String query) {
this.query = query;
}
public void setID(int ID) {
this.ID = ID;
}
public int getID() {
return ID;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
#Override
public String toString() {
return "RecentSearchModel{" +
"query='" + query + '\'' +
'}';
}
#Override
public boolean equals(#Nullable Object obj) {
if (obj instanceof RecentSearchModel)
return this.query.equalsIgnoreCase(((RecentSearchModel) obj).query);
return false;
}
}
So, what I am doing here is for start getting all values inside my local DB and adding them to my String list that is part of the adapter. So far so good.
The issue I am facing is that the adapter won't show the amount of strings available in the list that populates it. In fact, it sometimes shows a view half-cut with wierd information, sometimes does not show anything and sometimes shows part of the corrent information. What am I missing?
Another thing I am facing is that the "recently searched" adapter won't work when clicking on the AutoCompleteTextView - it only works when typing and deleting values so the char length is 0. How can I make it work from start of focus?
Here is the way I am populating the information to the ViewModel -
/**
* Shows the searched products following
*/
#Override
public void getSearchedProducts(String searchedQuery) {
MarketplaceUtils.getSearchedProducts(searchedQuery, marketApiCalls, false, initialSearchTake, initialMarketplacePage, new MarketplaceUtils.OnProductsFetchCompleteListener() {
#Override
public void onSuccess(List<MiniProductModel> list) {
if (!searchedQuery.equals(currentSearchedText))
return;
if (list == null) {
//reaching here means we do not have a result to show to the UI so we empty the list.
currentProductList.clear();
productsAdapter.notifyDataSetChanged();
return;
}
if (searchedQuery.length() > 3 && searchAutoCompleteStrings.contains(searchedQuery)) {
Log.d("localDBValue", "searchedValue - " + searchedQuery);
recentSearchViewModel.insert(new RecentSearchModel(searchedQuery));
}
mPresenter.setDiscoverProductsLayoutVisibility(View.GONE);
currentProductList.clear();
currentProductList.addAll(list);
productsAdapter.notifyDataSetChanged();
}
#Override
public void onError(Throwable throwable) {
Log.d("searchedProducts", throwable.getMessage());
}
});
}
The default behaviour for #Insert method of Room is OnConflictStrategy.ABORT - so what I did is to implement equals() method to verify that the RecentSearchModels that are being compared are compared by their string value. Still does seems to effect anything.
In my TableView I have column with button for each row for update so I need when click the button to take all the values from the row to a new fxml window
This is my contractor class:
public class constractor {
private String co_id;
private String co_name;
private String co_address;
private String co_create_date;
private String co_description;
private String co_mobile;
private String co_type_compile;
private String co_status;
private String co_type_model;
private Button button;
public constractor(String co_id, String co_name, String co_type_compile, String co_description, String co_create_date, String co_status, String co_address, String co_mobile, String co_type_model, String button) {
this.co_id = co_id;
this.co_name = co_name;
this.co_type_compile = co_type_compile;
this.co_description = co_description;
this.co_create_date = co_create_date;
this.co_status = co_status;
this.co_address = co_address;
this.co_mobile = co_mobile;
this.co_type_model = co_type_model;
this.button = new Button("edit");
}
public String getCo_id() {
return co_id;
}
public void setCo_id(String co_id) {
this.co_id = co_id;
}
public String getCo_name() {
return co_name;
}
public void setCo_name(String co_name) {
this.co_name = co_name;
}
public String getCo_address() {
return co_address;
}
public void setCo_address(String co_address) {
this.co_address = co_address;
}
public String getCo_create_date() {
return co_create_date;
}
public void setCo_create_date(String co_create_date) {
this.co_create_date = co_create_date;
}
public String getCo_description() {
return co_description;
}
public void setCo_description(String co_description) {
this.co_description = co_description;
}
public String getCo_mobile() {
return co_mobile;
}
public void setCo_mobile(String co_mobile) {
this.co_mobile = co_mobile;
}
public String getCo_type_compile() {
return co_type_compile;
}
public void setCo_type_compile(String co_type_compile) {
this.co_type_compile = co_type_compile;
}
public String getCo_status() {
return co_status;
}
public void setCo_status(String co_status) {
this.co_status = co_status;
}
public String getCo_type_model() {
return co_type_model;
}
public void setCo_type_model(String co_type_model) {
this.co_type_model = co_type_model;
}
public Button getButton() {
return button;
}
public void setButton(Button button) {
this.button = button;
}
}
This is my class for table:
public class MainscreenController implements Initializable {
#FXML
private TableView<constractor> co_tableview;
#FXML
private TableColumn<constractor, String> col_id;
#FXML
private TableColumn<constractor, String> col_name;
#FXML
private TableColumn<constractor, String> col_compaile_type;
#FXML
private TableColumn<constractor, String> col_description;
#FXML
private TableColumn<constractor, String> col_ceartedat;
#FXML
public TableColumn<constractor, String> col_status;
#FXML
private TableColumn<constractor, String> col_mobile;
#FXML
private TableColumn<constractor, String> col_type_model;
#FXML
private TextField search;
#FXML
private TableColumn<constractor, Button> col_button;
int indexorder = -1;
ObservableList<constractor> orderdata = FXCollections.observableArrayList();
#FXML
public void ordertables() {
Connection con = DB.getConnection();
orderdata.clear();
try {
try (ResultSet rs = con.createStatement().executeQuery("select * from mr_order")) {
while (rs.next()) {
orderdata.add(new constractor(
rs.getString("co_id"),
rs.getString("co_name"),
rs.getString("co_type_model"),
rs.getString("co_description"),
rs.getString("co_create_date"),
rs.getString("co_status"),
rs.getString("co_mobile"),
rs.getString("co_address"),
rs.getString("co_type_compile"),
rs.getString("co_user_id")
));
}
countneworder();
}
} catch (SQLException ex) {
Logger.getLogger(MainscreenController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int tablesandsearchorder() {
////tableview Itemsinserting
col_id.setCellValueFactory(new PropertyValueFactory<>("co_id"));
col_name.setCellValueFactory(new PropertyValueFactory<>("co_name"));
col_compaile_type.setCellValueFactory(new PropertyValueFactory<>
("co_type_compile"));
col_description.setCellValueFactory(new PropertyValueFactory<>
("co_description"));
col_ceartedat.setCellValueFactory(new PropertyValueFactory<>
("co_create_date"));
col_status.setCellValueFactory(new PropertyValueFactory<>("co_status"));
col_mobile.setCellValueFactory(new PropertyValueFactory<>("co_mobile"));
col_type_model.setCellValueFactory(new PropertyValueFactory<>
("co_type_model"));
col_button.setCellValueFactory(new PropertyValueFactory<>("button"));
co_tableview.setItems(orderdata);
co_tableview.getItems().setAll(orderdata);
co_tableview.itemsProperty().addListener((observable, oldItems, newItems)
-> {
countorder.textProperty().bind(
Bindings.size(newItems).asString());
});
// 2. Set the filter Predicate whenever the filter changes.
search.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
filteredData.setPredicate(constractor -> {
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}
// Compare first name and last name of every person with filter text.
String lowerCaseFilter = newValue.toLowerCase();
if
(constractor.getCo_name().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches first name.
} else if (constractor.getCo_id().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches last name.
} else if
(constractor.getCo_description().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches last name.
}
return false; // Does not match.
});
});
// 3. Wrap the FilteredList in a SortedList.
SortedList<constractor> sortedData = new SortedList<>(filteredData);
// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(co_tableview.comparatorProperty());
// 5. Add sorted (and filtered) data to the table.
co_tableview.setItems(sortedData);
return 0;
}
#FXML
public void openinsert() {
try {
//in this fxml i create the new order and also i need for update the status the order from this fxml when i click the button inside the tableview
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("createorder.fxml"));
Scene scene = new Scene(fxmlLoader.load());
Stage stage = new Stage();
stage.setTitle("neworder");
stage.setScene(scene);
stage.setFullScreen(false);
stage.setResizable(false);
stage.setMinHeight(400);
stage.setMinWidth(600);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
It's usually recommended not mixing the view code (Button) with the model code (constractor). Instead you should use a custom TableCell class for the column.
Assuming you know how to pass the data (otherwise take a look here: Passing Parameters JavaFX FXML), all required info should be available via the constractor instance which you should pass to the new scene.
MainscreenController
#FXML
private TableColumn<constractor, Void> col_button;
...
private void editConstractor(constractor constractor) {
// TODO: implement
}
#FXML
private void initialize() {
col_button.setCellFactory(col -> new TableCell<constractor, Void>() {
private final Button button;
{
button = new Button("edit");
button.setOnAction(evt -> {
constractor item = getTableRow().getItem();
editConstractor(item);
});
}
#Override
protected void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
setGraphic(empty ? null : button);
}
});
}
You also need to remove the cellValueFactory for the button column.
Note:
Sticking to the java naming conventions would make the code easier to read. (Type names should start with an uppercase letter and identifiers should use camelCase instead of underscores assuming they're not for a static final field.)
constractor is most likely misspelled. Did you mean contractor? I recommend using the renaming functionality of your IDE to fix this typo...
(In my code I used the same spelling for the editConstractor method.)
I was trying to map ResultSet data to an object and returning it. Here is how i'm mapping data to an object. Now i'm having only 7 columns in resultset so this is working fine but what if i'm having 20 or 30 columns. How can i map dynamically those columns.
public class ProductsWrapperMapper implements ResultSetMapper<ProductsWrapper> {
public ProductsWrapper map(int i, ResultSet resultSet,
StatementContext statementContext) throws SQLException {
ProductsWrapper product = new ProductsWrapper();
if ((isColumnPresent(resultSet,"a_productid"))) {
product.setId(resultSet.getInt("a_productid"));
}
if ((isColumnPresent(resultSet,"a_productname"))) {
product.setProductName(resultSet.getString("a_productname"));
}
if ((isColumnPresent(resultSet,"a_productlink"))) {
product.setLink(resultSet.getString("a_productlink"));
}
if ((isColumnPresent(resultSet,"a_productimagelink"))) {
product.setImageLink(resultSet.getString("a_productimagelink"));
}
if ((isColumnPresent(resultSet,"a_websiteid"))) {
product.setWebsiteId(resultSet.getInt("a_websiteid"));
}
if ((isColumnPresent(resultSet,"a_productidentification"))) {
product.setProductIdentification(resultSet
.getString("a_productidentification"));
}
if ((isColumnPresent(resultSet,"a_adddate"))) {
product.setAddDate(resultSet.getString("a_adddate"));
}
return product;
}
public boolean isColumnPresent(ResultSet resultSet,String column) {
try {
#SuppressWarnings("unused")
int index = resultSet.findColumn(column);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
return false;
}
}
}
Below one is my class which i was returning the object from mapper class above.
#JsonInclude(Include.NON_NULL)
public class ProductsWrapper {
private int id;
private String productName;
private String link;
private String imageLink;
private int websiteId;
private String productIdentification;
private String addDate;
int getWebsiteId() {
return websiteId;
}
public void setWebsiteId(int websiteId) {
this.websiteId = websiteId;
}
public String getProductIdentification() {
return productIdentification;
}
public void setProductIdentification(String productIdentification) {
this.productIdentification = productIdentification;
}
public String getAddDate() {
return addDate;
}
public void setAddDate(String addDate) {
this.addDate = addDate;
}`enter code here`
public ProductsWrapper(int id) {
this.setId(id);
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImageLink() {
return imageLink;
}
public void setImageLink(String imageLink) {
this.imageLink = imageLink;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
You can also try Jdbi-folder. It automatically takes care of dynamic bynding and also it provides one to many mapping relationship.
You can add Rosetta as a mapper for your JDBI result sets (it also works for bindings). Have a look at the advanced features to map column names with underscores to snake snake case java names.
Beware that there is no warning message if Rosetta is unable to map a value: any missed property in the target bean will just be empty. I found that my database returned column names in capital letters, therefore the LowerCaseWithUnderscoresStrategy in the example didn't work for me. I created a UpperCaseWithUnderscoresStrategy.
To skip writing getters and setters in ProductsWrapper have a look at Lombok's #Data annotation.
I am using BeanItemContainer for my comboboxes to satisfy key-value pairs.
#SuppressWarnings("serial")
public class ComboBoxItem implements Serializable {
private String id;
private String description;
public ComboBoxItem(final String id, final String description) {
this.id = id;
this.description = description;
}
public final void setId(final String id) {
this.id = id;
}
public final void setDescription(final String description) {
this.description = description;
}
public final String getId() {
return id;
}
public final String getDescription() {
return description;
}
}
I created a sample combobox as below
List<ComboBoxItem> lstAuctionDateList = new ArrayList<ComboBoxItem>();
lstAuctionDateList.add(new ComboBoxItem("all", "All"));
BeanItemContainer<ComboBoxItem> auctionDateItems = new BeanItemContainer<ComboBoxItem>(ComboBoxItem.class,
lstAuctionDateList);
final ComboBox cbAuctionDate = new ComboBox("Auction Date", auctionDateItems);
cbAuctionDate.addStyleName("small");
cbAuctionDate.setNullSelectionAllowed(false);
cbAuctionDate.setTextInputAllowed(false);
cbAuctionDate.setItemCaptionPropertyId("description");
cbAuctionDate.addValueChangeListener(new ValueChangeListener() {
public void valueChange(final ValueChangeEvent event) {
if (cbAuctionDate.getValue() != null) {
System.out.println(((ComboBoxItem) cbAuctionDate.getValue()).getId());
System.out.println(((ComboBoxItem) cbAuctionDate.getValue()).getDescription());
}
}
});
It is fine but I can't select any of combobox items by using below codes
cbAuctionDate.select("all");
cbAuctionDate.select("All");
cbAuctionDate.setValue("all");
cbAuctionDate.setValue("All");
What am I wrong ? How can I select my comboxes by programmatically ?
when using a (bean) container and adding items, the identity of the item itself is used as the itemId in the container. E.g. cbActionDate.select(lstAuctionDateList[0]) should work.
You either have yo make your objects immutable or use ways to tell the container, what it has to use for an id (E.g. setBeanIdProperty("id") or setBeanIdResolver).
Making the object immutable should be easy right now (make the class and the private attributes final, drop the setters and let your IDE generate equals and hashCode for you)
You don't need the cbAuctionDate.addItem("All") call, you already have such a item in your collection
I would try it that way:
List<ComboBoxItem> lstAuctionDateList = new ArrayList<ComboBoxItem>();
ComboBoxItem allItems= new ComboBoxItem("all", "All");
lstAuctionDateList.add(allItems);
....
...
cbAuctionDate.select(allItems);
Now I created custom ComboBox component for my problem
public class ComboBox extends CustomComponent implements Serializable {
private com.vaadin.ui.ComboBox comboBox;
private BeanItemContainer<ComboBoxItem> entries = new BeanItemContainer<ComboBoxItem>(ComboBoxItem.class);
public ComboBox() {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCompositionRoot(comboBox);
}
public ComboBox(final String caption) {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCaption(caption);
setCompositionRoot(comboBox);
}
public ComboBox(final String caption, final List<ComboBoxItem> items) {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCaption(caption);
if (items != null && items.size() > 0) {
entries.addAll(items);
comboBox.setContainerDataSource(entries);
comboBox.setItemCaptionMode(ItemCaptionMode.PROPERTY);
addItems(entries);
comboBox.select(items.get(0));
comboBox.setItemCaptionPropertyId("description");
}
setCompositionRoot(comboBox);
}
public final void addItems(final List<ComboBoxItem> items) {
if (items != null && items.size() > 0) {
entries.addAll(items);
comboBox.setContainerDataSource(entries);
comboBox.setItemCaptionMode(ItemCaptionMode.PROPERTY);
addItems(entries);
comboBox.select(items.get(0));
comboBox.setItemCaptionPropertyId("description");
}
}
private void addItems(final BeanItemContainer<ComboBoxItem> items) {
comboBox.addItems(items);
}
public final void addItem(final ComboBoxItem item) {
if (item != null) {
comboBox.setContainerDataSource(entries);
comboBox.addItem(item);
comboBox.setItemCaptionPropertyId("description");
}
}
public final void selectByIndex(final int index) {
Object[] ids = comboBox.getItemIds().toArray();
comboBox.select(((ComboBoxItem) ids[index]));
}
public final void selectById(final String id) {
Object[] ids = comboBox.getItemIds().toArray();
for (int i = 0; i < ids.length; i++) {
if (((ComboBoxItem) ids[i]).getId().equals(id)) {
selectByIndex(i);
break;
}
}
}
public final void selectByItemText(final String description) {
Object[] ids = comboBox.getItemIds().toArray();
for (int i = 0; i < ids.length; i++) {
if (((ComboBoxItem) ids[i]).getDescription().equals(description)) {
selectByIndex(i);
break;
}
}
}
public final int getItemCount() {
return comboBox.getItemIds().toArray().length;
}
public final String getSelectedId() {
return ((ComboBoxItem) comboBox.getValue()).getId();
}
public final String getSelectedItemText() {
return ((ComboBoxItem) comboBox.getValue()).getDescription();
}
public final void addValueChangeListener(final ValueChangeListener listener) {
comboBox.addValueChangeListener(listener);
}
}
and below is test codes
final ComboBox combo = new ComboBox("My ComboBox");
combo.addItem(new ComboBoxItem("all", "All"));
// Add with list
List<ComboBoxItem> items = new ArrayList<ComboBoxItem>();
items.add(new ComboBoxItem("one", "One"));
items.add(new ComboBoxItem("two", "Two"));
items.add(new ComboBoxItem("three", "Three"));
combo.addItems(items);
combo.addItem(new ComboBoxItem("four", "Four"));
combo.addItem(new ComboBoxItem("five", "five"));
combo.selectByIndex(3);
combo.addValueChangeListener(new ValueChangeListener() {
public void valueChange(final ValueChangeEvent event) {
System.out.println(combo.getSelectedId() + " --- " + combo.getSelectedItemText());
}
});
I used a keywordfilter for a list which is populated from db .Its working good .Imagine the list contains a phrase 'A big bat' and there are other words starting with 'b' like books etc .But when I give 'b' in the search field the phrase 'A big bat' appears first and then only words starting with 'b'.Please help me to fix it
please see my code
public final class KeywordFilter
{
private KeywordFilterField _keywordFilterField;
private WordList _wordList;
private Vector _words;
public KeywordFilter()
{
_words = getDataFromDatabase();
if(_words != null)
{
_wordList = new WordList(_words);
_keywordFilterField = new KeywordFilterField();
_keywordFilterField.setSourceList(_wordList, _wordList);
CustomKeywordField customSearchField = new CustomKeywordField();
_keywordFilterField.setKeywordField(customSearchField);
KeywordFilterScreen screen = new KeywordFilterScreen(this);
screen.setTitle(_keywordFilterField.getKeywordField());
screen.add(_keywordFilterField);
UiApplication ui = UiApplication.getUiApplication();
ui.pushScreen(screen);
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Error reading data file.");
System.exit(0);
}
});
}
}
KeywordFilterField getKeywordFilterField()
{
return _keywordFilterField;
}
private Vector getDataFromDatabase()
{
Vector words = new Vector();
Database d;
for(;;)
{
try
{
URI myURI=URI.create("file:///SDCard/Databases/MyTestDatabase.db");
d=DatabaseFactory.open(myURI);
Statement st=d.createStatement("select (select distinct group_concat(eng) fromEnglish),group_concat(mal) from English e ,Malayalam m where e.Ecode=m.Mcode group by eng");
st.prepare();
net.rim.device.api.database.Cursor c=st.getCursor();
Row r;
while(c.next())
{
r=c.getRow();
String w=r.getString(0);
String meaning=r.getString(1);
words.addElement(new Word(w,meaning));
}
st.close();
d.close();
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
return words;
}
}
void addElementToList(Word w)
{
_wordList.addElement(w);
_keywordFilterField.updateList();
}
final static class CustomKeywordField extends BasicEditField
{
CustomKeywordField()
{
super(USE_ALL_WIDTH|NON_FOCUSABLE|NO_LEARNING|NO_NEWLINE);
setLabel("Search: ");
}
protected boolean keyChar(char ch, int status, int time)
{
switch(ch)
{
case Characters.ESCAPE:
if(super.getTextLength() > 0)
{
setText("");
return true;
}
}
return super.keyChar(ch, status, time);
}
protected void paint(Graphics graphics)
{
super.paint(graphics);
getFocusRect(new XYRect());
drawFocus(graphics, true);
}
}
}
class KeywordFilterScreen extends MainScreen
{
private KeywordFilter _app;
private KeywordFilterField _keywordFilterField;
public KeywordFilterScreen(KeywordFilter app)
{
_app = app;
_keywordFilterField = _app.getKeywordFilterField();
}
protected boolean keyChar(char key, int status, int time)
{
if (key == Characters.ENTER)
{
displayInfoScreen();
// Word w = (Word)_keywordFilterField.getSelectedElement();
// Status.show(w.getMeaning());
return true;
}
return super.keyChar(key, status, time);
}
public boolean invokeAction(int action)
{
switch(action)
{
case ACTION_INVOKE:
displayInfoScreen();
return true;
}
return super.invokeAction(action);
}
private void displayInfoScreen()
{
Word w = (Word)_keywordFilterField.getSelectedElement();
if(w != null)
{
InfoScreen infoScreen = new InfoScreen(w);
UiApplication ui=UiApplication.getUiApplication();
ui.pushScreen(infoScreen);
}
}
public boolean onSavePrompt()
{
return true;
}
private final static class InfoScreen extends MainScreen
{
InfoScreen(Word w)
{
setTitle(w.toString());
BasicEditField popField = new BasicEditField(" ",w.getMeaning(),300,Field.NON_FOCUSABLE);
FontManager.getInstance().load("DC124.TTF", "MyFont", FontManager.APPLICATION_FONT) ;
{
try {
FontFamily typeface = FontFamily.forName("MyFont");
Font myFont = typeface.getFont(Font.PLAIN, 25);
popField.setFont(myFont);
add(popField);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();}
}
}
}
}
This query is useful for you:
SELECT Name FROM Employee where Name like '%d%' order by Name;
Here Name is my column-name;
Try this;
I think you are using query like following
select colomname from tablename where colomname GLOB '%b%';
here you get all names which are contain letter 'b' (case sensitive)
if you want all words which are strted with letter 'b' use should writr query like
select colomname from tablename where colomname GLOB 'b%' order by colomname ;
here i am using "GLOB" it gives case sensitive to the out put records if you dont need case sensitive then you can use "LIKE" key word
thanks