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.
Related
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...).
Is it possible to fetch javascript output to a string in java. I am working with Selenium WebDriver and I expect all child nodes to be listed for which I want to make use of javascript. I am making use of JavascriptExecutor functionality. I want something like this;
JavascriptExecutor js = (JavascriptExecutor)LaunchBrowserTest.driver;
List<String> s = (List<String>)(js.executeScript(" var text = 'aa'; "
+ "var list = document.getElementById('jstree'); "
+ "var anchorlist = document.getElementsByTagName('a'); "
+ "for( i = 0; i < anchorlist.length; i++ ) "
+ "{ "
+ "text = text + anchorlist[i].innerHTML; "
+ "};"
+ "console.log(text);"));
System.out.println("String Array: " + s );
Is there any way I could expect the text outputted and captured into String 's' in java ?
After I get the list, I wanted them to be used in Selenium to click on the nodes as below
WebElement element = driver.findElement(By.linkText(s[i])); where i < s.length
The present output shows me String Array: []
Please suggest me changes/links to get the functionality working.
Answer:
JavascriptExecutor js = (JavascriptExecutor)LaunchBrowserTest.driver;
List<String> s = (List<String>)(js.executeScript(" var text = 'aa'; "
+ "var list = document.getElementById('jstree'); "
+ "var anchorlist = document.getElementsByTagName('a'); "
+ "for( i = 0; i < anchorlist.length; i++ ) "
+ "{ "
+ "text = text + anchorlist[i].innerHTML; "
+ "};"
+ "return text;"));
System.out.println("String Array: " + s );
If you look through the documentation of Selenium JavascriptExecutor and look for the executeScript() method, you will see that your Javascript has to return something in
order to catch it up in Java itself.
Here you can see what kind of data type you will get in Java if your JS script returns
anything.
I hope this helps you out, good luck.
I'm writing something similar to smarterChild (that automated AOL Instant Messenger chat program from back in the day) and was curious about my method of determining sentence structure and response.
Currently, the bare bones design is to use 5 main methods which collectively determine the appropriate response given the user input:
1) Read(): initially accepts user input, then calls first of many methods: sentenceType()
2) getSentenceType(): User sentence type: Question, statement, directive, suggestion, etc…
3) getWho(): If question is about the computer, or about someone else…
4) getCategory(): What category the question is about (weather, sports…)
5) getResponse(): finally, form a response
These methods will query a database to determine if the user input contains key words...
Example of getSentenceType():
public String getSentenceType(String sentence) {
String type = null;
for (String s : db.getQuestions()) {
if (sentence.contains(s)) {
type = "question";
break;
}
else {
type = "statement";
}
}
return getWho(type, sentence);
}
Example of the final method which returns sentence structure:
//final call...
public String getResponse(String cat, String who, String type) {
String response = new String();
String auxVerb, subject, mainVerb, noun;
auxVerb = "do";
subject = who;
mainVerb = "like";
noun = cat;
//question structure: auxiliary verb + subject + main verb + noun/pronoun
// DO YOU LIKE MARY?
if (type.equals("question")) {
response = subject + " " + auxVerb + " " + mainVerb + " " + noun + ". ";
}
else {
response = auxVerb + " " + subject + " " + mainVerb + " " + noun + "?";
}
return response;
}
Sample database methods:
public String[] getQuestions() {
String[] questions = new String[] {"why", "?"};
return questions;
}
public String[] getWeather() {
String[] weather = new String[] {"cold", "hot", "rainy", "weather"};
return weather;
}
It will then progressively concatenate all the method results into a coherent response… then send that result back to Read(), which will print out the result to the user...
Is this an inefficient way to go about this? I know that if I continue down this path... to make a robust system, it will take tons of if else checks and a massive database to determine every possible type of response for user input.
Are there any suggested methods?
Thank you
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/
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.