Skip to content

Commit 3bddef4

Browse files
authored
Add new search function to DB to search with a prefix or the whole name (APPS-2401) (#264)
1 parent 6404d91 commit 3bddef4

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ All notable changes to this project will be documented in this file.
77
### Removed
88
### Fixed
99

10+
## [0.82.2]
11+
### Added
12+
* core: Add function to search for products by a prefix
13+
1014
## [0.82.2]
1115
### Added
1216
* ui: Add new authentication fragment to handle new checkout state

core/src/main/java/io/snabble/sdk/ProductDatabase.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.io.FileOutputStream;
2020
import java.io.IOException;
2121
import java.io.InputStream;
22+
import java.util.ArrayList;
2223
import java.util.Date;
2324
import java.util.List;
2425
import java.util.Scanner;
@@ -1134,6 +1135,49 @@ public Product findByName(String name) {
11341135
return getFirstProductAndClose(cursor);
11351136
}
11361137

1138+
/**
1139+
* Finds products by its prefix or the name itself. Matching is normalized, so "Apple" finds also "apple".
1140+
*
1141+
* @param namePrefix The name of the product.
1142+
* @return The firsts product matching, otherwise empty list if no product was found.
1143+
*/
1144+
public List<Product> findByNamePrefix(String namePrefix) {
1145+
if (namePrefix == null || namePrefix.isEmpty() || namePrefix.trim().isEmpty()) {
1146+
return new ArrayList<>();
1147+
}
1148+
1149+
String normalizedPrefix = StringNormalizer.normalize(namePrefix);
1150+
1151+
// Simple direct query on products table
1152+
String sql = "SELECT sku, name FROM products WHERE LOWER(name) LIKE ? ORDER BY name";
1153+
String[] args = {normalizedPrefix.toLowerCase() + "%"};
1154+
1155+
Cursor cursor = null;
1156+
List<Product> products = new ArrayList<>();
1157+
1158+
try {
1159+
cursor = db.rawQuery(sql, args);
1160+
1161+
while (cursor.moveToNext()) {
1162+
String sku = cursor.getString(0);
1163+
String name = cursor.getString(1);
1164+
1165+
// Create minimal Product object or however you construct them
1166+
Product product = new Product.Builder().setName(name).setSku(sku).build();
1167+
products.add(product);
1168+
}
1169+
} catch (Exception e) {
1170+
Logger.e("PRODUCT_SEARCH", "Error searching products", e);
1171+
} finally {
1172+
if (cursor != null) {
1173+
cursor.close();
1174+
}
1175+
}
1176+
1177+
return products;
1178+
}
1179+
1180+
11371181
private void exec(String sql) {
11381182
Cursor cursor = rawQuery(sql, null, null);
11391183
if (cursor != null) {

0 commit comments

Comments
 (0)