I'm trying to implement an expandable listview with data from a remote server. I've already have the JSON part covered. My sample has three value sets returned (confirmed by checking logcat on the original JSON response). My problem now is while dividing the JSON return into header and child datas, the first value set is skipped. My code is as follows:
int lisDataHeaderCounter = 0;
String searchKey;
for (int i = 0; i < components.length(); i++) {
List<String> component_value = new ArrayList<String>();
searchKey = main_components.get(i);
if (!listDataHeader.contains(searchKey)) {
listDataHeader.add(searchKey);
Iterator<Map.Entry<String, String>> entries = sub_components.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
Log.d("getValue() ", "+ " + entry.getValue());
if (searchKey == entry.getKey())
component_value.add(entry.getValue());
}
listDataChild.put(listDataHeader.get(lisDataHeaderCounter), component_value);
lisDataHeaderCounter++;
}
}
I've also tried the code below and it still has the same result.
for (Map.Entry<String, String> entry : sub_components.entrySet()) {
if (searchKey == entry.getKey())
component_value.add(entry.getValue());
}
Here is a sample of the JSON response that is being process by the above codes:
[{"activity_code":"1","activity_name":"Midterm Exam"},
{"activity_code":"1","activity_name":"Final Exam"},
{"activity_code":"2","activity_name":"Project"}]
With the current codes, in the for loop, the first value of searchKey is '1'. When I placed a Log.d(); in the while loop to check what the first value is read, I found that it is "Final Exam" and not "Midterm Exam". Is there a way for me to get the value of the first data set before it goes into the while loop?
Here is a workaround I've made to ensure that the first value would be included to the sub_components. But I guess it doesn't look neat. If anyone has a better solution, please feel free to share.
for (int i = 0; i < components.length(); i++) {
JSONObject c = components.getJSONObject(i);
String formula_code = c.getString(TAG_FORMULA_CODE);
String component_name = c.getString(TAG_ACTIVITY_NAME);
main_components.add(formula_code);
sub_components.put(formula_code, component_name);
if (!listDataHeader.contains(formula_code))
listDataHeader.add(formula_code);
if (i == 0) {
component_value.add(component_name);
}
}
for (int i = 0; i < listDataHeader.size(); i++) {
for (Map.Entry<String, String> entry : sub_components.entrySet()) {
if (listDataHeader.get(i) == entry.getKey())
component_value.add(entry.getValue());
}
listDataChild.put(listDataHeader.get(i), component_value);
component_value = new ArrayList<String>();
}
I can't see any off by one error on the two, but perhaps it's the searchKey == entry.getKey(), that might have to be searchKey.equals(entry.getKey()), but I would need to see more code to know for sure.
Related
I only want to check for:
if (lore.contains("§eSigned of ")) {
but it doesn't get that it does contain "§eSigned of "
I wrote a Minecraft Command /sign you can add a lore to an item ("Signed of playerrank | playername").
Then i wanted to add an /unsign command to remove this lore.
ItemStack is = p.getItemInHand();
ItemMeta im = is.getItemMeta();
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<String>();
if (lore.contains("§eSigned of " + getChatName(p))) { // this line is important!
for (int i = 0; i < 3; i++) {
int size = lore.size();
lore.remove(size - 1);
}
im.setLore(lore);
is.setItemMeta(im);
p.setItemInHand(is);
sendMessage(p, "§aThis item is no longer signed");
} else {
sendMessage(p, "§aThis item is not signed!");
}
return CommandResult.None;
Everything works fine until you e.g. change your name. than you can't remove the sign because getChatName(p) has changed.
To fix this i only want to check
if (lore.contains("§eSigned of ")) {
but than it doesn't get it and returns false. (it says lore does not contain "§eSigned of ")
I tried a lot but it only works with the string "§eSigned of " and getChatName(p).
As the documentation "contains" searches for the specific string so it should work as I thought right?
Add:
getChatName(p) returns the rank of the player and the playername like: "Member | domi"
sendMessage(p, "") sends a simple message in the Minecraft chat
The problem you run into is that contains(String) looks for a matching string. What you search for is a check if any string in the list starts with "§eSigned of ".
I would suggest adding a function isSignedItem like this:
private boolean isSignedItem(List<String> lore) {
for (String st : lore)
if (st.startsWith("§eSigned of "))
return true;
return false;
}
and then to use this function to check if the item is signed or not:
[...]
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<String>();
if (isSignedItem(lore)) { // this line is important!
for (int i = 0; i < 3; i++) {
int size = lore.size();
lore.remove(size - 1);
}
[...]
When the code is ran the nested loop causes it to create occasional duplicate entries to the system, i have spent a while looking through this but still cant find what is causing this, would greatly appreciate any help?
for(int i = 0; i < subWorkItemElement.getChildNodes().getLength(); i++) {
Boolean test = false;
WorkItemCommon existingChild = null;
String summary = null;
if(subWorkItemElement.getChildNodes().item(i).getNodeName().equals("workitem")) {
// We know it's a work item - but is it in the existing list?
Element childWorkItem = (Element) subWorkItemElement.getChildNodes().item(i);
for(int j = 0; j < subWorkItemElement.getChildNodes().getLength(); j++) {
if(childWorkItem.getChildNodes().item(j) instanceof Element) {
if(((Element)childWorkItem.getChildNodes().item(j)).getNodeName().equals("details")) {
summary = ((Element) childWorkItem.getChildNodes().item(j)).getElementsByTagName("summary")
.item(0).getTextContent();
for(String k : userInfoHashMap.keySet()) {
summary = summary.replace("${" + k + "}", userInfoHashMap.get(k));
}
if(childHashTable.containsKey(summary)) {
test = true;
existingChild = childHashTable.get(summary);
IWorkItem workItem = existingChild.getWorkItem();
System.out.println("INFO: The task with summary \"" + summary + "\" already exists. Skipping creation.");
System.out.println("this task is work item: " + workItem.getId());
//either check the tasks in the xml for updated details and then modify the existing workitem
//or just modify the work item without checking for updates
makeChildTask(childWorkItem, existingChild, childHashTable, userInfoHashMap, workItemHashMap, rtc, false);
break;
}
}
}
}
if(!test) {
System.out.println("INFO: The task with summary " + summary + " does not currently exist. Creating.");
makeChildTask(childWorkItem, thisItem, childHashTable, userInfoHashMap, workItemHashMap, rtc, true);
} else makeFromExistingChildTask(childWorkItem, existingChild, userInfoHashMap, workItemHashMap, rtc);
}
}
You are possibly (not sure what makeChildTask() does) changing an XML structure while iterating through the children list. While not necessarily incorrect, this can mean you get entries inserted while you process the list. Since you call the subWorkItemElement.getChildNodes().getLength() each time instead of cache'ing it, this might result in the length changing in between the loop iterations.
I am trying to iterate two hash maps and print the keys that are matching in both of them.Although both of the hash maps have got matching elements it is consistently saying "no match found".
Below posted is my code.
try {
String s = new String(data);
String string = new String(input_bytes);
StringTokenizer stringTokenizer = new StringTokenizer(s);
StringTokenizer input_stringTokenizer = new StringTokenizer(string);
while(stringTokenizer.hasMoreTokens())
{
map.put(stringTokenizer.nextToken(), stringTokenizer.nextToken());
}
while(input_stringTokenizer.hasMoreTokens())
{
input_map.put(input_stringTokenizer.nextToken(),
input_stringTokenizer.nextToken());
}}
catch (Exception e1) {
e1.printStackTrace();
}}
Iterator input1 = map.entrySet().iterator();
Iterator input_2 = input_map.entrySet().iterator();
while (input_2.hasNext() && input1.hasNext()) {
Map.Entry input_val1 = (Map.Entry) input1.next();
Map.Entry input_val2 = (Map.Entry) input_2.next();
String temp = input_val1.getKey().toString().substring(input_val1.getKey().toString().lastIndexOf("\\") + 1);
String temp_2 = input_val2.getKey().toString().substring(input_val2.getKey().toString().lastIndexOf("\\") + 1);
if(temp.equals(temp_2))
{
System.out.println("element matched");
}
else
{
System.out.println("no match found!");
}
}
My input files are "data" and "input_bytes"
The path in these files is the "key" and the hash is the "value" of the hashmap.
For effective matching i have trimmed the path such that it gives me only the element after the last slash.
"temp" variable in the code will print in the following way :
com.example.android.notepad_4.4.2-eng.build.20150616.1901504.apk ﹕
com.facebook.orca_34.0.0.22.2114.apk
com.android.contacts_4.4.2-eng.build.20150616.1901504.apk
com.amazon.venezia_release-13.0003.844.1C_6430003104.apk
com.android.deskclock_3.0.04.apk
com.google.android.apps.photos_1.0.0.943910814.apk
apuslauncher-2.apk
com.android.vending-v5.8.11-80381100-Android-2.3.apk
net.sylark.apkextractor_1.0.54.apk
Here is how my "data" file look like:
C:\Users\rishii\Desktop\input_3\com.amazon.venezia_release-
13.0003.844.1C_6430003104.apk
266796d1b8e2e016753ee3bf1b50e591
C:\Users\rishii\Desktop\input_3\com.android.browser_4.4.2-
eng.build.20150616.1901504.apk
4aa2091b0e21fc655e19d07e2ae20982
C:\Users\rishii\Desktop\input_3\com.android.calculator2_4.4.2-
eng.build.20150616.1901504.apk
85313ccbd39a43952906b70b941d321b
C:\Users\rishii\Desktop\input_3\com.android.calendar_4.4.2-
eng.build.20150616.1901504.apk
3c85cb87f2e134a4157e5f3747e4df1b
Here is my "input_bytes" file looks like:
C:\Users\rishii\Desktop\baal\com.amazon.venezia_release-
13.0003.844.1C_6430003104.apk
266796d1b8e2e016753ee3bf1b50e591
C:\Users\rishii\Desktop\baal\com.android.browser_4.4.2-
eng.build.20150616.1901504.apk
4aa2091b0e21fc655e19d07e2ae20982
C:\Users\rishii\Desktop\baal\com.android.calculator2_4.4.2-
eng.build.20150616.1901504.apk
85313ccbd39a43952906b70b941d321b
C:\Users\rishii\Desktop\baal\com.android.calendar_4.4.2-
eng.build.20150616.1901504.apk
3c85cb87f2e134a4157e5f3747e4df1b
C:\Users\rishii\Desktop\baal\com.android.camera2_2.0.002-
eng.build.ef73894.060315_142358-704.apk
482205cda6991f89fb35311dea668013
If you can see there are some matches in both the files.Any help would be highly appreciated.
Here's a much simpler way to check if they contain the same keys:
public void findSameKeys(Map<String, String> map1, Map<String, String> map2) {
for (String key : map1.keySet()) {
if (map2.containsKey(key)) {
System.out.println("Matching key: " + key);
}
}
}
The containsKey() method is very useful here.
I currently have the following code, which gets a table from a webpage, and put the elements into a HashMap (I think).
Document doc = Jsoup.connect(
"http://www.sportinglife.com/greyhounds/abc-guide").get();
Element tableHeader = doc.select("tbody").first();
Map<String, String> data = new HashMap<>();
for (Element element : tableHeader.children()) {
// Here you can do something with each element
if (element.text().indexOf("Pelaw Grange") > 0
|| element.text().indexOf("Shawfield") > 0
|| element.text().indexOf("Shelbourne Park") > 0
|| element.text().indexOf("Harolds Cross") > 0) {
// do nothing
} else {
String dog = element.select("td:eq(0)").text();
String race = element.select("td:eq(1)").text();
data.put(dog, race);
}
}
analyseRunners(data);
}
This seems to work OK and I now need it to run another method "analyseRunners", where it needs to go through each of the dogs and use that "dog" name to access another webpage where there is another table. Here's what I have so far...
String dogPage = "http://www.gbgb.org.uk/raceCard.aspx?dogName=" + dog;
Document doc1 = Jsoup.connect(dogPage).get();
int firsts = 0, seconds = 0, thirds = 0;
Element tblHeader = doc1.select("tbody").first();
for (Element element1 : tblHeader.children()){
String position = element1.select("td:eq(4)").text();
if (position.equals("1st")){
firsts++;
} else if (position.equals("2nd")){
seconds++;
} else if (position.equals("3rd")){
thirds++;
} else {
//do nothing
}
}
System.out.println("Firsts: " + firsts);
System.out.println("Seconds: " + seconds);
System.out.println("Thirds: " + thirds);
As you can see, I am trying to navigate to the webpage in jSoup using the "dog" from the first method above... this isn't working as it says "dog" cannot be resolved. How do I go about getting the dog name out of the HashMap and looping through every dog to work out how many 1st, 2nds and 3rds it has? (the fifth column on this page: http://www.gbgb.org.uk/raceCard.aspx?dogName=A%20Real%20Legend)
Use the dog names on your data map in a loop :
for(String dog : data.keySet())
{
// use dog as required
}
first iterate your map's key list and get the available dogs.
then process your logic inside that..
for (String dog: data.keySet()) {
String dogPage = "http://www.gbgb.org.uk/raceCard.aspx?dogName=" + dog;
Document doc1 = Jsoup.connect(dogPage).get();
....................
}
I want to count the numbers of pp/np/vp in the text but I don't know how to identify PP-tags/NP-tags/VP-tags in openNLP chunker? I have tried this code but it's not working.
ChunkerModel cModel = new ChunkerModel(modelIn);
ChunkerME chunkerME = new ChunkerME(cModel);
String result[] = chunkerME.chunk(whitespaceTokenizerLine, tags);
HashMap<Integer,String> phraseLablesMap = new HashMap<Integer, String>();
Integer wordCount = 1;
Integer phLableCount = 0;
for (String phLable : result) {
if(phLable.equals("O")) phLable += "-Punctuation"; //The phLable of the last word is OP
if(phLable.split("-")[0].equals("B")) phLableCount++;
phLable = phLable.split("-")[1] + phLableCount;
System.out.println(wordCount + ":" + phLable);
phraseLablesMap.put(wordCount, phLable);
wordCount++;
}
Integer noPP=0;
Integer TotalPP=0;
for (String PPattach: result) {
if (PPattach.equals("PP")) {
for (int i=0;i<result.length;i++)
TotalPP = noPP +1;
}
}
System.out.println(TotalPP);
Output:
1:NP1
2:VP2
3:NP3
4:NP3
5:VP4
6:PP5
7:NP6
8:NP6
9:NP6
10:NP6
11:PP7
12:NP8
13:NP8
14:NP8
15:PP9
16:NP10
17:NP10
18:PP11
19:NP12
20:NP12
21:VP13
22:VP13
23:NP14
24:NP14
25:PP15
26:NP16
27:NP16
28:Punctuation16
0
best way is by using the span objects, they have a getType() method that returns the chunk type.
see this post
grouping all Named entities in a Document