I am making database of my school's building and classroom with Realm. But, 'for-loop' in try-catch doesn't work:
public void startCheckRealm() {
// Writing DataBase with Realm
try {
Log.d("Realm", "Init");
InitializeAPI.init_BuildingRoom(getActivity().getApplicationContext());
Log.d("Realm", "Complete");
} catch(Exception e) {
e.printStackTrace();
}
// Trying to check the Database whether it is right or wrong
try {
Log.d("Realm Test", "2nd Try Catch");
Realm.init(getActivity().getApplicationContext());
Realm realm = Realm.getDefaultInstance();
RealmResults<BuildingList> buildingLists = realm.where(BuildingList.class).findAllSorted("buildingCode");
int totalNumber = 0;
for(int i = 0; i < buildingLists.size(); i++) {
Log.d("For", "index = " + i);
RealmResults<RoomList> rooms = buildingLists.get(i).getRoomList().sort("roomCode");
String BuildingName = buildingLists.get(i).getBuildingName();
String BuildingCode = buildingLists.get(i).getBuildingCode();
for(int idx = 0; idx < rooms.size(); idx++) {
totalNumber++;
String RoomCode = rooms.get(idx).getRoomCode();
String RoomName = rooms.get(idx).getRoomName();
Log.d("Realm Test", "Number :: " + String.valueOf(totalNumber) + " BuildingCode :: " + BuildingCode + "\t\t BuildingName :: " + BuildingName + "\t\t RoomCode :: " + RoomCode + "\t\t RoomName :: " + RoomName);
}
}
Log.d("Realm Test", "2nd Try Catch Complete + " + String.valueOf(totalNumber));
} catch(RealmException e) {
e.printStackTrace();
}
}
In the first try-catch, the method, which does making database, is complete without Exception. I was curious whether this database is right or wrong.
So, in 2nd try-catch, I was trying to check realm files with queries.
The problem is "for-loop" doesn't work in 2nd try-catch. Below snippet is my logcat.
D/Realm: Init
I/System.out: bdList getLength :: 52
I/System.out: roomList getLength :: 2376
D/Realm: Complete
D/Realm Test: 2nd Try Catch
D/Realm Test: 2nd Try Catch Complete + 0
I want to check my realm data with Log but, doesn't work as you can see.
If there is no problem, the logcat shows lots of my building and room lists and ends with "D/Realm Test: 2nd Try Catch Complete + 2376".
Could you explain the reason why it doesn't work? I cannot understand the reason why it doesn't work even though there is no Exception.
While in your use-case this doesn't pose a problem, when you're iterating a RealmResults inside a transaction, the results are live in every version <= 0.88.3 and >= 3.0.0.
So in that case,
RealmResults<BuildingList> buildingLists = realm.where(BuildingList.class).findAllSorted("buildingCode");
for(int i = 0; i < buildingLists.size(); i++) {
BuildingList buildingList = buildingLists.get(i); // <-- !!!
will fail (it will skip every second item!)
So you should use iterators instead (3.0.0+! on <= 0.88.3 you'd do reverse iteration)
RealmResults<BuildingList> buildingLists = realm.where(BuildingList.class).findAllSorted("buildingCode");
for(BuildingList buildingList : buildingLists) { // <-- !!!
The reason why this works is because iterators by default create a new snapshot collection (3.0.0+), and iterating by index on a snapshot also works
OrderedRealmCollection<BuildingList> snapshot = buildingLists.createSnapshot();
for(int i = 0; i < ...
Simple: there is no exception thrown; and you only have your print statements inside the loop.
Thus the one and only conclusion: at that point in time when your for loops are executed, the corresponding list is empty. Therefore the loop body is not entered; nothing gets printed. And that has nothing to do with the fact that this loop is within a try-catch block.
That is all there is to this. So, the direct answer is: print the list size directly in front of the loop to avoid such surprises.
(of course, the interesting part is to understand what happens to the list which seems to be non-empty earlier on - but in order to debug that, you would have to add more of your code).
Two inputs:
1.Haven't used realm but looks like the syntax for getting sorted entriesis a bit different Official documentation
2.If the above point is wrong than from your code it looks like buildingList size is zero. Have you tried checking the size?
Let me know the results.
Try logging your catch block. Chances are the rest of the code including the loop didn't complete because your app was caught with the Exception.
You should debug buildingLists.size(); before for loop
Log.d("Building List Size ", buildingLists.size()+"");
In that case you can find the value of buildingLists.size();
Related
The entire process is working almost properly but I'd like to add some debug for a specific issue.
for (int j = 0; j < end.length; j++) {
String remove = end[j].trim();
if (cName.endsWith(remove)) {
mPhone = cName.substring(0, cName.length() - remove.length()).trim();
}
System.out.println(cName + ", " + remove + ", " + mPhone);
}
Where should I expect to see the output? It is not in the Script Output tab, or the DBMS Output tab, or the General tab.
Its been some time since I've looked into it my self but as per this other post, you may need to execute
set serveroutput on size 10000
exec dbms_java.set_output(10000)
and then try executing.
I am using selenium webdriver with java to test a web application in my company and I face a very strange problem. The web application after logging in displays this table with the values as shown in the picture in the link below:
https://drive.google.com/file/d/0B0i_2gNTlx1Sek9EQVQ1ZlY1a0E/view?usp=sharing
I have wrote this code that parses the table with xpath because the table's rows and td cells are id-less.
//Parsing the table.
int increment = 0;
int i = 0;
for(increment=1; increment <= 16; increment++){
StringBuilder nsb = new StringBuilder("");
StringBuilder sb = new StringBuilder("");
for(i=1; i <= 6; i++){
try {
WebElement f = wd.findElement((By.xpath("/html/body/div[1]/div/div[2]/div/div[2]/div[2]/div[2]/div/div[1]/form/div/div/table/tbody/tr["+increment+"]/td["+i+"]")));
sb.append(f.getText().replaceAll("\\n", " ")).append(" ");
} catch (StaleElementReferenceException ed) {
ed.getSuppressed();
}
}
System.out.println(sb);
}
System.out.println();
The problem now is that when I print the values of each row sometimes and in random order i lose some of the values on the output as shown in the picture i post below(for example if i re-run the program the second field in the second row called SAB will be missing).
Correct output is
https://drive.google.com/file/d/0B0i_2gNTlx1SQmFoZDd0UkgzVXM/view?usp=sharing
I tried instead of getText method the getAttribute("textContent") but i face the same random problem.
Does anyone have any idea why is this happening?
Sorry for the links but I didn't have any alternative to show you my problem..I can also post a random faulty output I got during testing if it's needed..
One thought,
why did you add ?
catch (StaleElementReferenceException ed) {
ed.getSuppressed();
}
Are you getting this exception if not catching?
if yes, then
might be your page or element is getting refreshed
and when you are referring f on second line to getText() you may get StaleElementReferenceException, But as you are suppressing it your loop continues and value is lost because of exception.
you can try replacing
WebElement f = wd.findElement((By.xpath("/html/body/div[1]/div/div[2]/div/div[2]/div[2]/div[2]/div/div[1]/form/div/div/table/tbody/tr["+increment+"]/td["+i+"]")));
sb.append(f.getText().replaceAll("\\n", " ")).append(" ");
with single statement
sb.append(wd.findElement((By.xpath("/html/body/div[1]/div/div[2]/div/div[2]/div[2]/div[2]/div/div[1]/form/div/div/table/tbody/tr["+increment+"]/td["+i+"]"))).getText().replaceAll("\\n", " ")).append(" ");
Probably this will avoid staleElement Exception if issue is caused by it.
I've spent several frustrating days on this now and would appreciate some help. I have a Java agent in Lotus Domino 8.5.3 which is activated by a cgi:POST from my Lotusscript validation agent which is checking that customer has filled in the Billing and delivery address form. This is the code that parses the incoming data into a HashMap where field names are mapped to their respective values.
HashMap hmParam = new HashMap(); //Our Hashmap for request_content data
//Grab transaction parameters from form that called agent (CGI: request_content)
if (contentDecoded != null) {
String[] arrParam = contentDecoded.split("&");
for(int i=0; i < arrParam.length; i++) {
int n = arrParam[i].indexOf("=");
String paramName = arrParam[i].substring(0, n);
String paramValue = arrParam[i].substring(n + 1, arrParam[i].length());
hmParam.put(paramName, paramValue); //Old HashMap
if (paramName.equalsIgnoreCase("transaction_id")) {
transactionID = paramValue;
description = "Order " + transactionID + " from Fareham Wine Cellar";
//System.out.println("OrderID = " + transactionID);
}
if (paramName.equalsIgnoreCase("amount")) {
orderTotal = paramValue;
}
if (paramName.equalsIgnoreCase("deliveryCharge")) {
shipping = paramValue;
}
}
}
The block of code above dates back over a year to my original integration of shopping cart to Barclays EPDQ payment gateway. In that agent I recover the specific values and build a form that is then submitted to EPDQ CPI later on in the agent like this;
out.print("<input type=\"hidden\" name=\"shipping\" value=\"");
out.println(hmParam.get("shipping") + "\">");
I want to do exactly the same thing here, except when I try the agent crashes with a null pointer exception. I can successfully iterate through the hashMap with the snippet below, so I know the data is present, but I can't understand why I can't use myHashMap.Get(key) to get each field value in the order I want them for the html form. The original agent in another application is still in use so what is going on? The data too is essentially unchanged String fieldnames mapped to String values.
Iterator it = cgiData.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
out.println("<br />" + pairs.getKey() + " = " + pairs.getValue());
//System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
I did two things that may have had an impact, in the process of trying to debug what was going on I needed these further imports;
import java.util.Iterator;
import java.util.Map;
Although I'm not iterating over the hashMap, I've left them in in case which gives me the option of dumping the hashMap out to my system audit trail when application is in production. In variations of the snippet below after it started working I was able to get to any of the data I needed, even if the value was Null, and toString() also seemed to be optional again, as it made no difference to the output.
String cgiValue = "";
cgiValue = hmParam.get("ship_to_lastname").toString();
out.println("<br />Lastname: " + cgiValue);
out.println("<br />Company name: " + hmParam.get("bill_to_company"));
out.println("<br />First name: " + hmParam.get("ship_to_firstname"));
The second thing I did, while trying to get code to work was I enabled the option "Compile Java code with debugging information" for the agent, this may have done something to the way the project was built within the Domino Developer client.
I think I have to put this down to some sort of internal error created when Domino Designer compiled the code. I had a major crash last night while working on this which necessitated a cold boot of my laptop. You also may find that when using Domino Designer 8.5.x that strange things can happen if you don't completely close down all the tasks from time to time with KillNotes
Here is what I have right now where, I am making multiple JDBC connections based on the IP address I have.
Map<String,Connection> connections = new HashMap<>();
DeviceStmt = connRemote.createStatement();
DeviceRS = DeviceStmt.executeQuery(maindbsql);
while (DeviceRS.next()) {
try {
final String ip_address = DeviceRS.getString("IP_vch");
System.out.println("Value of IP_vch Field:"+ip_address);
connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://"
+ ip_address + ":3306/test",RemoteUser,RemotePass));
if (connections.isEmpty()) {
System.err.println("Not successfull");
} else {
System.out.println("Connection to"+ip_address+"is successfull");
}
} catch(SQLException ex1) {
System.out.println("While Loop Stack Trace Below:");
ex1.printStackTrace();
}
}//END Of while(DeviceRS.next())
What I want to have :
Say for example I am making connections to following IP's : 11.11.1.111 and 22.22.2.222
I want to excute an additional query on 11.11.1.111 just after connection is established after the following line in the above code:
connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));
Since, I can't use the same resultset(DeviceRS) which I have already used , I am wondering how can I run a different query.
I want to do something like the following:
DeviceStmttwo = connRemote.createStatement();
DeviceRStwo = DeviceStmttwo.executeQuery(maindbsqlnew);
below the following code I mentioned in the above code:
DeviceStmt = connRemote.createStatement();
DeviceRS = DeviceStmt.executeQuery(maindbsql);
Should I go for different while(DeviceRStwo.next()) option just before the existing while(DeviceRS.next()) loop and make connections again which seems to be a overhead to me.
Using the "Network Updates API" example at the following link I am able to post network updates with no problem using client.postNetworkUpdate(updateText).
http://code.google.com/p/linkedin-j/wiki/GettingStarted
So posting works great.. However posting an update does not return an "UpdateKey" which is used to retrieve stats for post itself such as comments, likes, etc. Without the UpdateKey I cannot retrieve stats. So what I would like to do is post, then retrieve the last post using the getNetworkUpdates() function, and in that retrieval will be the UpdateKey that I need to use later to retrieve stats. Here's a sample script in Java on how to get network updates, but I need to do this in Coldfusion instead of Java.
Network network = client.getNetworkUpdates(EnumSet.of(NetworkUpdateType.STATUS_UPDATE));
System.out.println("Total updates fetched:" + network.getUpdates().getTotal());
for (Update update : network.getUpdates().getUpdateList()) {
System.out.println("-------------------------------");
System.out.println(update.getUpdateKey() + ":" + update.getUpdateContent().getPerson().getFirstName() + " " + update.getUpdateContent().getPerson().getLastName() + "->" + update.getUpdateContent().getPerson().getCurrentStatus());
if (update.getUpdateComments() != null) {
System.out.println("Total comments fetched:" + update.getUpdateComments().getTotal());
for (UpdateComment comment : update.getUpdateComments().getUpdateCommentList()) {
System.out.println(comment.getPerson().getFirstName() + " " + comment.getPerson().getLastName() + "->" + comment.getComment());
}
}
}
Anyone have any thoughts on how to accomplish this using Coldfusion?
Thanks
I have not used that api, but I am guessing you could use the first two lines to grab the number of updates. Then use the overloaded client.getNetworkUpdates(start, end) method to retrieve the last update and obtain its key.
Totally untested, but something along these lines:
<cfscript>
...
// not sure about accessing the STATUS_UPDATE enum. One of these should work:
// method 1
STATUS_UPDATE = createObject("java", "com.google.code.linkedinapi.client.enumeration.NetworkUpdateType$STATUS_UPDATE");
// method 2
NetworkUpdateType = createObject("java", "com.google.code.linkedinapi.client.enumeration.NetworkUpdateType");
STATUS_UPDATE = NetworkUpdateType.valueOf("STATUS_UPDATE");
enumSet = createObject("java", "java.util.EnumSet");
network = yourClientObject.getNetworkUpdates(enumSet.of(STATUS_UPDATE));
numOfUpdates = network.getUpdates().getTotal();
// Add error handling in case numOfUpdates = 0
result = yourClientObject.getNetworkUpdates(numOfUpdates, numOfUpdates);
lastUpdate = result.getUpdates().getUpdateList().get(0);
key = lastUpdate.getUpdateKey();
</cfscript>
You can also use socialauth library to retrieve updates and post status on linkedin.
http://code.google.com/p/socialauth