Adding the results to an arraylist - java

I am facing some difficulties while assigning the values in an array list. My code is :
while (answer.hasMore()) {
SearchResult rslt = (SearchResult)answer.next();
Attributes attrs = rslt.getAttributes();
System.out.println();
if (attrs.get("department") != null && attrs.get("telephonenumber") != null) {
System.out.println(attrs.get("department") + " " + attrs.get("name") + " " +
attrs.get("Description") + " " + attrs.get("mail") + " " +
attrs.get("telephonenumber")+
attrs.get("samaccountname") + attrs.get("samaccountname") );
}
I want to assign the values of attrs.get("department") + attrs.get("description")+ attrs.get("name")+attrs.get("mail") each one to an array list.
I tried to define at the beginning:
String[] name = new String[100];
and in the while loop i tried to read the name attribute, I tried to do:
name = attrs.get("name");
But it did not work. Can anyone help.

In Java, an array and an ArrayList are quite different.
String[] name_array = new String[100];
creates a fixed-length array of Strings, but
ArrayList name_list = new ArrayList();
creates a variable-length ArrayList of objects (it will grow as you add more objects).
To add an object to an ArrayList, you can use its add() method.
name_list.add("Hello");
However, with an array you need to set the object at a specific index, e.g:
name_array[23] = "Hello";
You need to read a basic tutorial on the Java language and standard library.

You cannot directly assign strings to a array made of string "references". You need to index it first. But it would be much better to actually use a list (and maybe convert it to an array later). Check out List and ArrayList in the Java documentation.
As an example:
Attributes attrs = new Attributes();
List<String> attribValues = new ArrayList<String>();
System.out.println();
if (attrs.get("department") != null
&& attrs.get("telephonenumber") != null) {
System.out
.println(attrs.get("department") + " " + attrs.get("name")
+ " " + attrs.get("Description") + " "
+ attrs.get("mail") + " "
+ attrs.get("telephonenumber")
+ attrs.get("samaccountname")
+ attrs.get("samaccountname"));
attribValues.add(attrs.get("department"));
attribValues.add(attrs.get("telephonenumber"));
}
final String[] attribArray = attribValues.toArray(new String[attribValues.size()]);

First of all define your name as String not as an array of String like this:
String name;
And then read name as:
name = attrs.getString("name");
Now coming back to your issue of populating List, I am sure you will get ready-made answers here but I suggest you to do some reading on how to create and populate a List in Java.

Related

Elements of a split string array can't be used as function inputs?

Here is my code:
// This is the bug - this works.
String[] lst = {"desk", "pencil"};
String lst0 = lst[0];
System.out.println("path: " + lst[0]);
System.out.println("result: " + root.getDirectory(lst0).getFileName());
// This is the bug - this doesn't work.
String[] ef = "desk/pencil".split("/");
String ef1 = ef[0];
System.out.println("path: " + ef1);
System.out.println("result (without getFileName): " + root.getDirectory(ef1));
But in the second case, the function isn't called properly, as ef[0] seems considered differently from lst[0] by the compiler despite both being strings. I assume this is becaue lst is a array that resulted from list splitting. Is there any way to fix/work around this?

Split arraylist for specific info from a URL?

I'm a bit confused with how to split my arraylist, loop thru the list, and pull out only specific info.
I have an arraylist of 20 URLs:
"http://xxxx.websitename.com:1234/aaa/bbb/ccc"
"http://yyyy.websitename.com:5678/aaa/bbb/ccc"
etc.....
And I want to be able to have the results pull only:
xxxx 1234
yyyy 5678
How do I get this started if I want the above as my result? I can find how to do it as a string, but no good example as an array list.
public class HealthCheck {
public static void main(String[] args) {
ArrayList arlURL = new ArrayList();
arlURL.add("http://xxxx.websitename.com:1234/aaa/bbb/ccc");
arlURL.add("http://yyyy.websitename.com:5678/aaa/bbb/ccc");
System.out.println(arlURL);
There is no way to get only the (sub)domain and port by only using the ArrayList implementation. You can only get the entries as you put them into the ArrayList.
Use the build in URL class to parse the URLs of the ArrayList:
URL aURL = new URL("http://xxxx.websitename.com:1234/aaa/bbb/ccc");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
See http://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html
As you only want to have to subdomain you have to further split the aURL.getHost() string at the first dot (e.g., aURL.getHost().substring(0, aURL.getHost().indexOf(".")), be aware to first check that the string contains a dot before using this...).

Fetch data of JSON array on Android

I have a few test values in my database and i want to fetch them all in android.
This is my following JSON output of the values inside my Database:
[{"email_address":"rainier_gaari#hotmail.com","comment":"qwehgashdgaskdaweq","date_comment":"2014-06-21","time_comment":"08:28:00","password":"rainier1990"},
{"email_address":"rainier_gaari#hotmail.com","comment":"asfasdasdasd","date_comment":"2104-06-12","time_comment":"09:03:00","password":"rainier1990"}
{"email_address":"rainier_gaari#hotmail.com","comment":"asdsfafd","date_comment":"2014-06-22","time_comment":"04:44:00","password":"rainier1990"}]
But every time that I run this code: http://prntscr.com/3vhs5j , it only gives me the first line of the JSON output.: http://prntscr.com/3vi34b
How can I show all the rows( instead of 1 row)in android?
You can use a JSONObject provided by the android API. The JSONObject has a method called getJSONArray()
http://developer.android.com/reference/org/json/JSONObject.html#getJSONArray(java.lang.String)
your error there is that you are instantiating a JSONArray with your Object. you should try this:
JSONArray myArray =jsonObject.getJSONArray();
This is a snippet of code from one of my apps that worked very well to retrieve Json data.
success = jObject.getInt(TAG_SUCCESS);
vehicles = jObject.getJSONArray(Vehicle.TAG_VEHICLES);
if(success == 1) {
// loop through all the vehicles
for(int i = 0; i < vehicles.length(); i++) {
JSONObject obj = vehicles.getJSONObject(i);
// Get each element based on it's tag
String year = obj.getString(Vehicle.TAG_YEAR);
String model = obj.getString(Vehicle.TAG_MODEL);
String brand = obj.getString(Vehicle.TAG_BRAND);
String color = obj.getString(Vehicle.TAG_COLOR);
String license_plate = obj.getString(Vehicle.TAG_LICENSE);
String main_driver = obj.getString(Vehicle.TAG_DRIVER);
String policeNumber = obj.getString(Vehicle.TAG_POLICENUMBER);
String driversLicense = obj.getString(Vehicle.TAG_DRIVER_LICENSE);
String licenseState = obj.getString(Vehicle.TAG_LICENSE_STATE);
String driverBirthday = obj.getString(Vehicle.TAG_BIRTHDAY_MONTH) + "/" +
obj.getString(Vehicle.TAG_BIRTHDAY_DAY) + "/" +
obj.get(Vehicle.TAG_BIRTHDAY_YEAR);
String driverGender = obj.getString(Vehicle.TAG_DRIVER_GENDER);
ListRowGroup group = new ListRowGroup(brand + " " + year + " " + model, brand);
group.children.add(brand + " " + year + " " + model);
group.children.add(policeNumber);
group.children.add(model);
group.children.add(color);
group.children.add(license_plate);
group.children.add(main_driver);
group.children.add(driversLicense + " - " + licenseState);
group.children.add(driverBirthday + " - " + driverGender);
vehiclesGroup.append(i, group);
}
It would help if you put some of the code for getting the JSON in your question, to make it easier to reference, but, I don't see a loop, which is why it only gets the first line.
You may want to refer to this question: JSON Array iteration in Android/Java but basically use the length property of the JSONArray and loop through that many times.

Grouping duplicates till a specific count

I have a number of xml's that come in haphazardly that contain a Ocount, and Lnumber, as well as other data. I have created a class to get that data.
My problem is that how can I group xml's that have the same Lnumber(string), until it reaches the Ocount(int). (the xmls that have the same lnumber has the same Ocount). And eventually send out a email telling with xmls has been processed.
String readLine = FileHandler.checkListFile(sh.getShipmentHeader().getBillToCustomer());
if (!readLine.isEmpty())
{
int orderCount = 0;
int index = readLine.indexOf(";") + 1;
String customerName = readLine.substring(index, readLine.indexOf(";", index)).trim();
index = readLine.indexOf(";", index) + 1;
String to = readLine.substring(index, readLine.length()).trim();
if (!billMap.containsKey(sh.getShipmentHeader().getBillToCustomer()))
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), 1);
orderCount = 1;
}
else
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), ((int) billMap.get(sh.getShipmentHeader().getBillToCustomer())) + 1);
orderCount = (int) billMap.get(sh.getShipmentHeader().getBillToCustomer());
}
outboundMessage += sh.getShipmentHeader().getOrderNumber() + li ;
logger.info("On-Demand Outbound Export Info: " + orderCount + " processed out of " + sh.getShipmentHeader().getOrderCount() +
" for " + customerName);
if (orderCount == sh.getShipmentHeader().getOrderCount())
{
Email email = new Email();
billMap.remove(sh.getShipmentHeader().getBillToCustomer());
outboundMessage += li + "Total of #"+ sh.getShipmentHeader().getOrderCount() + " orders processed for "+ customerName + li ;
logger.info("On-Demand Email sent for " + customerName);
System.out.println(outboundMessage);
email.outboundEmail("TEST: Orders for " + customerName + " complete", outboundMessage, to);
outboundMessage = "";
email = null;
}}
I been working on this for days, where am I going wrong.
It seems like you are having difficulty obtaining information from xmls. I suggest using XStream [1]. It is capable of serialising objects to xml and back. By using XStream, you can get an Object from the xml and compare variables (Lnumber and Ocount) easily.
If you insist using this code, I suggest adding comments to notify us what you are doing, but if want an easier alternative to work with xml files using java, I highly suggest using XStream as a solution.
[1] http://x-stream.github.io/

getting session variables from session

I am getting the below error when I compile the below code
Enumeration e = bean.getSession().getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = session.getAttribute(name).toString();
System.out.println(name + " = " + value);
Error:
found : java.util.Iterator
required: java.util.Enumeration
Enumeration e = bean.getSession().getAttributeNames();
You shouldn't be using an enumeration, it should be an Iterator. Then use the methods of the Iterator like hasNext() to check if there is a next item and next() to get the next item. Hope it helps :)
how about just using a for loop?
for (String name : bean.getSession().getAttributeNames() ) {
String value = session.getAttribute(name).toString();
System.out.println( name + " = " + value );
}
It looks like you're actually using a getAttributeNames() method that return an instance of java.util.Iterator. So as a quick fix, this should work:
Iterator it = bean.getSession().getAttributeNames();
while (it.hasNext()) {
String name = (String)it.next();
String value = session.getAttribute(name).toString();
System.out.println(name + " = " + value);
More help/info could be provided if we knew the actual types of the bean variable and/or the return value of bean.getSession().
I think the problem is in the first line. This works for me:
<%
Enumeration attrs = session.getAttributeNames(); //you will need to include java.util.Enumeration
while(attrs.hasMoreElements()){ //for each item in the session array
String id = attrs.nextElement().toString(); //the name of the attribute
out.print("'" + id + "': '" + session.getAttribute(id) + "'"); //print out the key/value pair
}
%>
As others pointed out though, you should be using an Iterator

Categories

Resources