MultiList not displaying all result from webservice (Codename One) - java

Im trying to display some json records using a MultiList. I followed what was done here https://www.codenameone.com/manual/graphics.html but mine is returning only one record (Please see this image). The response came from this webservice
Below is my code. Please kindly show me where i'm wrong.
#Override
protected void beforeFormA(Form f) {
Style s = UIManager.getInstance().getComponentStyle("Button");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 4), false);
getattractive();//fetch results from webservice and store inside response variable
ArrayList arr = (ArrayList) response.get("results");
for (Object m:arr){
Map ma = (Map)m;
address =(String) ma.get("formatted_address");
name=(String)ma.get("name");
icon=(String)ma.get("icon");
ArrayList<Map<String, Object>> data = new ArrayList<>();
data.add(createListEntry(name,address,icon));
DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
MultiList ml = new MultiList(model);
ml.getUnselectedButton().setIconName("icon_URLImage");
ml.getSelectedButton().setIconName("icon_URLImage");
ml.getUnselectedButton().setIcon(placeholder);
ml.getSelectedButton().setIcon(placeholder);
f.add(BorderLayout.CENTER, ml);
}
}
private Map<String, Object> createListEntry(String name, String addr, String coverURL) {
Map<String, Object> entry = new HashMap<>();
entry.put("Line1", name);
entry.put("Line2", addr);
entry.put("icon_URLImage", coverURL);
entry.put("icon_URLImageName", name);
return entry;

You should fix the indentation. The for loop encapsulates everything so you are looping over all the elements and for X elements you are adding X multi lists.
This is something you would instantly see if you step over the code with a debugger...

done. I moved the line below out of the method and place it inside the class.
ArrayList> data = new ArrayList<>();

Related

MultiValueMap get values

hi im trying to access a MultiValueMap which is in a Hashmap
this is my HashMap insideprojectDetails HashMap
private HashMap<String, ClassDetails> classDetailsMap = new HashMap<String, ClassDetails>();
inside that classDetailsMap i have MultiValueMap called methodDetailsMap
private MultiMap<String, MethodDetails> methodDetailsMap = new MultiValueMap<String, MethodDetails>();
when im trying to access the methodDetailsMap by
Set<String> methodNamesSet = projectDetails.getClassDetailsMap().get(cls).getMethodDetailsMap().keySet();
String[] methodNames = methodNamesSet.toArray(new String[0]);
for (int i = 0; i < methodNames.length; i++) {
String methodName = methodNames[i];
System.out.println(cls + " "+methodName);
//codes used to access key values
Collection coll = (Collection) methodNamesSet.get(methodName);
System.out.println(cls + " "+methodNamesSet.get(methodName));
}
i get a error get saying cannot resolve method get(java.lang.String)
is there any way to access the MultiValueMap
Its a compilation error with your code. There is no get method in Set.
methodNamesSet.get(methodName)
To get method details, first loop through the set and then get method details from methodDetailsMap as below.
MultiValueMap<String, MethodDetails> methodDetailsMap = projectDetails.getClassDetailsMap().get(0).getMethodDetailsMap();
Set<String> methodNamesSet = methodDetailsMap.keySet();
for(String str: methodNamesSet) {
System.out.println(methodDetailsMap.get(str));
}
I read your code and as I understand first you need to get all method names of cls class then you want to get them one by one. So in the for loop you need to get from the getMethodDetailsMap().This will help you:
for (int i = 0; i < methodNames.length; i++) {
String methodName = methodNames[i];
System.out.println(cls + " "+methodName);
//codes used to access key values
Collection coll = projectDetails.getClassDetailsMap().get(cls).getMethodDetailsMap().get(methodName);
System.out.println(cls + " "+methodNamesSet.get(methodName));
}

How I can use HashMap with variables? Java sqlite

I have two variables (nom and marc) that come from a database (sqlite). I need to show these variables with a HashMap. I tried the following but it does not work:
private void populateList(String nom, String marc) {
list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, nom);
temp.put(SECOND_COLUMN, marc);
temp.put(THIRD_COLUMN, "1");
list.add(temp);
}
What am I doing wrong?
In a click event of a button I use a cursor to fetch data from the database:
Cursor c = db.rawQuery("Select * from prod where id_prod = " + id, null);
if (c.moveToFirst()){
do {
String nom = c.getString(1);
String marc = c.getString(2);
populateList(nom, marc);
} while(c.moveToNext());
}
As you can see PopulateList is a method different from the button that I need to send the variables. Maybe that I am doing wrong. Any answer will help. Thanks
Every time that a the populateList() method is called, you create a new instance of the list that you want to render!
Try to remove
list = new ArrayList<HashMap<String, String>>();
from the populateList(...)

Replacing multimap with mapping an element to a collection of elements

I am trying to map a meterId to a list of MeterBlinks that have that Id. I'm mainly confused on how to build the list up for the HashMap.put() call. Code below:
Map<String, List<MeterBlink>> IdToMetersMap = new HashMap<>();
for (MeterBlink meterBlink : createData()) {
List<MeterBlink> meterBlinkList = new ArrayList<>();
meterBlinkList.add(meterBlink);
String meterId = meterBlink.getMeterId();
idToMetersMap.put(meterId, meterBlinkList)
}
I think the issue is that I am creating a new list each time I iterate through but I am not sure how to resolve this.
Use the computeIfAbsent method added in jre 8:
Map<String, List<MeterBlink>> idToMetersMap = new HashMap<>();
for (MeterBlink meterBlink : createData()) {
String meterId = meterBlink.getMeterId();
idToMetersMap.computeIfAbsent(meterId, k -> new ArrayList<>()).add(meterBlinks);
}
Another option in java 8:
Map<String, List<MeterBlink>> idToMetersMap = createData().stream()
.collect(Collectors.groupingBy(MeterBlink::getMeterId));
I like the java8 answer, but here without java8 (without lambda expressions):
Map<String, List<MeterBlink>> idToMetersMap = new HashMap<>();
for (MeterBlink meterBlink : createData()) {
String meterId = meterBlink.getMeterId();
List<MeterBlink> meterBlinkList = idToMetersMap.get(meterId);
//if List doesn't exist create it and put in Map
if (meterBlinkList == null) {
meterBlinkList = new ArrayList<>();
idToMetersMap.put(meterId, meterBlinksList)
}
meterBlinkList.add(meterBlink);
}

How to avoid interference of HttpServletRequest.getReader and getParameterValues?

In my application I have to extract parameters of a request and put into a collection in the order of their appearance in the querystring.
For example, if the sender makes following request,
http://myapp.com/myrequest?param3=value3&param2=value2&param1=value1 ,
I need to generate a collection, in which the elements are placed in this order: param3, param2, param1.
To achieve this, I first extract the names of the parameters using the method getParameterNames shown below.
private List<String> getParameterNames(HttpServletRequest aRequest)
throws IOException {
final List<String> parameterNames = new LinkedList<>();
final BufferedReader reader = aRequest.getReader();
final String queryString = IOUtils.toString(reader);
final String[] parameterValuePairs = queryString.split("&");
for (String parameterValuePair : parameterValuePairs) {
final String[] nameValueArray = parameterValuePair.split("=");
parameterNames.add(nameValueArray[0]);
}
return parameterNames;
}
The problem: After invokation of this method, aRequest.getParameterValue(...) returns null for ever parameter name.
If I do it otherwise - first save the parameter map, and then invoke getParameterNames, then its result is null.
final Map<String,String[]> parameterMap = aRequest.getParameterMap();
final List<String> parameterNames = getParameterNames(aRequest);
I tried following things:
Make sure that reader.close() is not invoked in getParameterNames (elsewhere I read that this may cause problems).
Invoke reader.reset().
None of this helped.
How can I get a list of parameter-value pairs from a HttpServletRequest, which is sorted by parameter's appearance in the querystring?
With the first approach you don't need to use Reader to get the parameters. Instead do:
final List<String> parameterNames = new LinkedList<>();
final String queryString = query.getQueryString(); // get query string from query itself
// rest of your code stays unchanged
The reason it didn't work is because data from a request input stream can be read only once.
Or, if I am wrong and that is not the case, you can save parameters and their values into a LinkedHashMap:
final LinkedHashMap<String, String> parameterValues = new LinkedHashMap<>();
final BufferedReader reader = aRequest.getReader();
final String queryString = IOUtils.toString(reader);
final String[] parameterValuePairs = queryString.split("&");
for (String parameterValuePair : parameterValuePairs) {
final String[] nameValueArray = parameterValuePair.split("=");
parameterValues.put(nameValueArray[0], nameValueArray[1]);
}
Now parameterValues is a map with entries sorted by the order of appearance.

What is the syntax for EL that accesses List with object?

I'm having tough time figure out how to display object's properties in ArrayList using EL expression.
Many tutorial outside shows simple example like:
List<String> test = new ArrayList<String>();
request.setAttribute("test", test);
test.add("moo");
And it works fine.
<p>${test[0]}</p>
When the ArrayList contains actual object with properties, the value does not show up.
The code below gets the query result and store into Data Transfer Object "DTOTopics" then
I add the object into the ArrayList.
List<DTOTopics> list = new ArrayList<DTOTopics>();
request.setAttribute("recentTopics", list);
list = factory.getDAOTopics().findByLimit(5);
HTML
Each element in ArrayList is the object DTOTopics, so I tried to access to one of its properties "title" and nothing shows up on the page.
<h1>${recentTopics[0].title}</h1> //why this doesn't work???
Servlet
public class ShowRecentTopicsAction implements Action {
#Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
DAOFactory factory = null;
List<DTOTopics> list = new ArrayList<DTOTopics>();
request.setAttribute("recentTopics", list);
try {
factory = DAOFactory.getInstance();
list = factory.getDAOTopics().findByLimit(5);
}
catch (DAOConfigurationException e) {
Logger.log(e.getMessage() + " DAOConfEx, PostRegisterServlet.java.", e.getCause().toString());
}
catch (DAOException e) {
Logger.log(e.getMessage()+ " DAOEx, PostRegisterServlet.java", e.getCause().toString());
}
System.out.println("getRecentTopics() list = " + list);//just check if list returns null
//for testing
DTOTopics t = list.get(0);
System.out.println("TEST:::" + t.getTitle()); //ok
//these test works fine too
List<String> test = new ArrayList<String>();
request.setAttribute("test", test);
test.add("moo");
Map<String, String> map = new HashMap<String, String>();
request.setAttribute("mmm", map);
map.put("this", "that");
return "bulletinboard";
}
}
Here,
List<DTOTopics> list = new ArrayList<DTOTopics>();
request.setAttribute("recentTopics", list);
you're putting an empty arraylist in the request scope.
And then,
try {
factory = DAOFactory.getInstance();
list = factory.getDAOTopics().findByLimit(5);
you're reassigning the list reference with a new arraylist (instead of filling the original arraylist using add() or addAll() method). The one in the request scope still refers to the original empty arraylist!
Move request.setAttribute("recentTopics", list); to after you've obtained the list from the DAO and it should work. Your EL is perfectly fine.

Categories

Resources