How do I make an Array from jSoup Elements? (java) - java

How do I get the values in a piece of Html (values="valueIWant"), and have them in an Array ?
I tried the following, but that didn't work:
HttpEntity entity5 = response5.getEntity();
String defaultString = EntityUtils.toString(entity5);
Document defaultDoc = Jsoup.parse(defaultString);
Elements values = defaultDoc.getElementsByAttribute("value"); //DropDownList Values
String s[] = {""};
for(int a=0; a<values.size(); a++){
s[a] = values.get(a).toString();
}
return s;
So anyone got an answer? thanks. (Btw, i use Jsoup)

First of all: is your HTML parsed correctly? Can you provide the contents of defaultString? Is defaultDoc valid is there a problem with file encodings perhaps?
Assuming getElementsByAttribute actually returns some objects —note that you have a typo, value instead of values— you're currently populating the array with the descriptions of all Element-objects, not the values of the attribute. Try something like the following:
int i = 0;
String s[] = new String[values.size()];
for(Element el : values){
s[i++] = el.attr("values");
}

Related

how to get two string array item position and store in each separate string array in android

Sorry for my bad English. I am using two separate string array for each item of arraylist. All things working fine . My Question is I want to take each item of String array (say) if i take string array "asasaqty" and another item of string array "asasaId" then I want to store each item of string array value in third string array (say:[id1,qty1] and so on). Please let me know if there is a proper solution for this.
Below is my code.
Thanks in advance
String [] asasaqty;
String [] asasaId;
final AddToCartData addToCartData = response.body();
shoppingBagArrayList = addToCartData.getData();
asasaqty = new String[shoppingBagArrayList.size()];
asasaId = new String[shoppingBagArrayList.size()];
for (int i = 0; i < shoppingBagArrayList.size(); i++) {
asasaqty[i] = shoppingBagArrayList.get(i).getQty();
asasaId[i]=shoppingBagArrayList.get(i).getProductId();
System.out.println("==========wwwww========"+ Arrays.toString(asasaqty));
System.out.println("======wwwwssssswwwwss======"+ Arrays.toString(asasaId));
/* HashMap<String,String> map=new HashMap<String,String>();
for (int i = 0; i < asasaqty.length; i++) {
map.put(asasaqty[i],asasaId[i]);
System.out.println("======aaaaaaa======"+ map.put(asasaqty[i],asasaId[i]));
}*/
After printing the value in logcat the value is looking like
/System.out: ==========wwwww========[3, 2]
/System.out: ======wwwwssssswwwwss======[151, 10]
Now i want to take another String array and store each item asasaqty and asasaId in separate array like below
String[] xyz = [3,151] and
String[] abc = [2,10]
Please let me know how can we do this.
You can use productID and key (Assuming it is unique) and qty as value.
HashMap<Integer,Integer> dataMap = new HashMap<>();
for (int i=0; i <shoppingBagArrayList.size; i++){
dataMap.put(shoppingBagArrayList.get(i).getProductId() , shoppingBagArrayList.get(i).getQty());
}
System.out.println("DataMap: "+dataMap);

Fill string array with url links through for loop

I need a little help.
I have a string array (urllinks) which I want to fill with url links which are being parsed with jsoup through a for loop.
In below code example there are 2 urls but the list only gets filled with the first link. I don`t know how many links will be parsed, can be 1 but also 12.
public static String[] urllinks;
...
for (int i = 0; i < links.size(); i++) { // links size = 2
String url = doc.select("a").attr("abs:href");
urllinks[i] = url;
}
Any help would be appreciated.
Thanks in advance.
You problem is due to the fact that you call attr("abs:href") on doc.select("a") which returns an object of type Elements such that you always get the first match as stated in the javadoc:
Get an attribute value from the first matched element that has the
attribute.
You should rather iterate as next:
List<String> urls = new ArrayList<>();
// Iterate over all the links that have an attribute abs:href
for (Element link : doc.select("a[abs:href]")) {
urls.add(link.attr("abs:href"));
}
urllinks = urls.toArray(new String[urls.size()]);
To answer my own question, I solved it by creating an arraylist and then convert it back to a string array.
Dirty but it works.
{
private static String[] urllinks;
private static ArrayList<String> mStringList = new ArrayList<>();
...
int i = 0;
for (Element el : links) {
String url = el.attr("abs:href");
if (url != null) {
mStringList.add(i, url);
i++;
}
else {
// Do something
}
urllinks = mStringList.toArray(urllinks);
// check if urls are actualy in string array
Log.d("LINK 1", urllinks[0]);
Log.d("LINK 2", urllinks[1]);
...
}

accessing array outside the parent for loop in JAVA

i have this code snippet in my java application. i need to access the rule_body_arr_l2 outside the parent for loop. i tried to initialize the array outside the for loop but in the last line when i want to display its value, it says the array might not have been initialized yet.
String rule_body="person(?x),patientid(?y),haspid(?x,?y)";
System.out.println(rule_body);
String rule_body_arr[]=rule_body.split("\\),");
String rule_body_arr_l2[];
for(int x=0;x<rule_body_arr.length;x++)
{
System.out.println(rule_body_arr[x]);
rule_body_arr_l2=rule_body_arr[x].split("\\(");
System.out.println("LEVEL TWO SPLIT");
for(int y=0;y<rule_body_arr_l2.length;y++)
{
System.out.println(rule_body_arr_l2[y]);
}
}
for(int x=0;x<6;x++)
{
System.out.println(rule_body_arr_l2[x]);
}
Guidance is required in the matter
In Java, you must specify the array size. You haven't created an array. What you have done is, you have only created an array reference.
By default, in Java all references are set to null when initializing.
You must instantiate an array by giving an exact size for it.
For example,
int[] numberArray = new int[5];
If I understand your question, rather than using a split to parse the String you could use a regular expression with a Pattern to parse your String with something like
String rule_body = "person(?x),patientid(?y),haspid(?x,?y)";
Pattern p = Pattern.compile("person\\((.+)\\),patientid\\((.+)\\),haspid\\((.+)\\)");
Matcher m = p.matcher(rule_body);
if (m.matches()) {
System.out.printf("person = %s%n", m.group(1));
System.out.printf("patientid = %s%n", m.group(2));
System.out.printf("haspid = %s%n", m.group(3));
}
Which outputs
person = ?x
patientid = ?y
haspid = ?x,?y
If so then initialize rule_body_arr_l2 like
String[] rule_body_arr_l2 = new String[YOUR_POSSIBLE_LENGTH];
If you are not sure the length of String in prior declaration then better using ArrayList<String> like
ArrayList<String> rule_body_arr_l2= new ArrayList<String>();
try splitting at ), u wont get the comma problem

Two dimensional string array in java

I am new to java please help me with this issue.
I have a string lets say
adc|def|efg||hij|lmn|opq
now i split this string and store it in an array using
String output[] = stringname.split("||");
now i again need to split that based on '|'
and i need something like
arr[1][]=adc,arr[2][]=def and so on so that i can access each and every element.
something like a 2 dimensional string array.
I heard this could be done using Arraylist, but i am not able to figure it out.
Please help.
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:
String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\\|\\|");
int i=0;
String[][] names = new String[obj.length][];
for(String temp:obj){
names[i++]=temp.split("\\|");
}
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
// Similarly you can fetch other elements by yourList.get(1)[index]
What you can do is:
String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:
Arrays.asList(any_array);
Can hardly understand your problem...
I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>
String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
ArrayList<String> strList = new ArrayList<String>();
for(String str:strs.split("|"))
strList.add(str);
res.add(strList);
}

Java hashmap from python dict command?

I have a weird problem that I don't fully understand how to solve. Could someone please give me some pointers on hashmaps?
I have a variable:
/servlet/charting?base_color=grey&chart_width=288&chart_height=160&chart_type=png&chart_style=manufund_pie&3DSet=true&chart_size=small&leg_on=left&static_xvalues=10.21,12.12,43.12,12.10,&static_labels=blue,red,green,purple"
I basically want 10.21,12.12,43.12,12.10 to be associated with blue,red,green,purple (in the order displayed)
In python I created a method that does this with:
def stripChart(name):
name = str(name)
name = urlparse.urlparse(name)
name = cgi.parse_qs(name.query)
name = dict(zip( name['static_labels'][0].split(','), name['static_xvalues'][0].split(',')))
Not sure how to do this in java. So far I have:
URL imgURL = new URL (imgTag);
String[] result = imgURL.getFile().split("&");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
This gives me:
chart_width=288
chart_height=160
chart_type=png
chart_style=manufund_pie
3DSet=true
chart_size=small
leg_on=left
static_xvalues=10.21,12.12,43.12,12.10,
static_labels=blue,red,green,purple,
At this point I'm confused how to link static_labels and static_xvalues values.
Thanks so much. Any pointers would be awesome.
You want to look at StringTokenizer
Something like this (assuming you stored the labels into the String 'static_labels' and the values in the String 'static_xvalues'):
HashMap<String, Double> colorMap = new HashMap<String, Double>();
StringTokenizer labelTok = new StringTokenizer(static_labels, ",");
StringTokenizer valuesTok = new StringTokenizer(static_xvalues, ",");
while(labelTok.hasMoreElements()){
assert(valuesTok.hasMoreElements());
colorMap.put(labelTok.nextElement(), Double.parseDouble(valuesTok.nextElement()));
}
Look at using java.util.HashMap. Let's say you have stored the static_xvalues and static_labels request parameters into corresponding string variables. Something like the following will create the mapping for you:
String[] vals = static_xvalues.split(",");
String[] labels = static_labels.split(",");
HashMap<String,String> map = new HashMap<String,String>();
for (int i=0; i < vals.length; ++i) {
map.put(labels[i], values[i]);
}
You do not say if the xvalues need to be stored as floats or not. If so, you will need to convert the vals array into a Float (or Double) array first, and modify the HashMap instantiation accordingly:
HashMap<String,Float> = new HashMap<String,Float>();

Categories