How to convert String to ArrayList - java

I need your help about retreive data from mysql db. I cant add string to array list.
my list declare
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
here my code
report_data = json.getJSONArray(TAG_REPORT_DATA);
for (int i = 0; i < report_data.length(); i++) {
//storing variable
JSONObject c = report_data.getJSONObject(i);
String reportID = c.getString(TAG_REPORT_ID);
String userID = c.getString(TAG_UID);
String projectName = c.getString(TAG_PROJECT_NAME);
String localWork = c.getString(TAG_LOCATION);
String timeStart = c.getString(TAG_TIME_START);
String timeEnd = c.getString(TAG_TIME_END);
Log.d(TAG_LOCATION, localWork);
// add data to Arraylist
reportList.add(new HandleListReport(reportID, userID, projectName, localWork, timeStart, timeEnd));
my problem my listReport missing string data. Logcat show reportList ---> []
thanks for answer!

create a list of string
List<String> list ......
list.add(String)
then list.toArray() method
http://docs.oracle.com/javase/6/docs/api/java/util/List.html#toArray(T[])

it seems you are trying to store object of HandleListReport in arraylist. In that case use the following to initiate
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();

It seems that the length of variable report_data is 0, so the element does not add the list.

Related

Trying to get the Text inside a <ul> tag but its only returning the First item Selenium

this is the structure of the unodered list
structure of the unodered list
i want to get the value of "var" and "time" to two strings and save them in a ArrayList
List<String[]> finalResult = new ArrayList<>();
This is what i tried
List<WebElement> typeElements =driver.findElements(By.xpath("//*[#id=\"container\"]/section[2]/div/div[2]/div[2]/ul/li"));
for(int i=0;i<typeElements.size();i++){
WebElement typeSingle = typeElements.get(i);
String stName = typeSingle.findElement(By.xpath("//div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("//div/a/time")).getText();
String singleType[] =stName,stTime};
finalResult.add(singleType);
}
im getting total of 13 items in the
finalResult
variable. but all the items are same
{"title1","00:23"}
{"title1","00:23"}
{"title1","00:23"}....
i want them to be like this
{"title1","00:23"}
{"title2","00:31"}.....
what am i doing wrong?
***Edit*
On each itterations inside the for loop typeSingle
is refering to different id's,
but stName , stTime variables are same
To get child element with xpath you need to use ./:
String stName = typeSingle.findElement(By.xpath("./div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("./div/a/time")).getText();
Or use css selector:
String stName = typeSingle.findElement(By.cssSelector("var")).getText();
String stTime = typeSingle.findElement(By.cssSelector("time")).getText();
Changing this
String stName = typeSingle.findElement(By.xpath("//div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("//div/a/time")).getText();
to this solved the issue
String stName = typeSingle.findElement(By.xpath("div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("div/a/time")).getText();

android- convert arraylist to one string in custom format

i have data in sqlit database so i use it to store categoreis and items
and i get it in arraylist like this:
public ArrayList showDataItems(String id_cate){
ArrayList<Items> arrayListItems = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cr = db.rawQuery("select * from items where id_cate = "+id_cate,null);
cr.moveToFirst();
while (cr.isAfterLast() == false){
String item_id = cr.getString(0);
String ItemName = cr.getString(1);
String Item_quantity = cr.getString(2);
String icon = cr.getString(3);
int isDone = Integer.parseInt(cr.getString(5));
arrayListItems.add(new Items(item_id,ItemName,Item_quantity,R.drawable.shopicon,icon,isDone));
cr.moveToNext();
}
return arrayListItems;
}
so i need to get this data and convert it to string and share it to other application like whatsapp in custom format for example :
1- first one *
2- second one *
3-....
so i use this code for send data
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT,"hello world");
intent.setType("text/plain");
startActivity(Intent.createChooser(intent,"send items i need all
data here"));
so we can use string builder or some thing to get data in one string
please help me!
As you said, there is a StringBuilder class who can help formatting strings.
Here are the java docs
From StringBuilder, see the append(..) method. For your example:
int size = list.size();
for(int i = 0; i< size-1;i++){
stringBuilder.append(i+1).append("- ").append(list.get(i)).append('\n');
}
stringBuilder.append(size).append("- ").append(list.get(size-1));
The last call to append is different from the firstone by not appending the end line

JSON Parsing in Java Webservice of multiple JSONObjects in JSONObject

This is my JSON string,
{
"listmain":{
"16":[{"brandid":"186"},{"brandid":"146"},{"brandid":"15"}],
"17":[{"brandid":"1"}],
"18":[{"brandid":"12"},{"brandid":"186"}],
}
}
I need to get values in "16","17","18" tag and add values and ids("16","17","18") to two ArrayList.
What i meant is,
when we take "16", the following process should happen,
List<String> lsubid = new ArrayList<String>();
List<String> lbrandid = new ArrayList<String>();
for(int i=0;i<number of elements in "16";i++) {
lsubid.add("16");
lbrandid.add("ith value in tag "16" ");
}
finally the values in lsubid will be---> [16,16,16]
the values in lbrandid will be---> [186,146,15]
Can anyone please help me to complete this.
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can parse the JSON like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONObject listMainObj = responseDataObj.getJSONObject("listmain");
Iterator keys = listMainObj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is 16,17,...
// get the value of the dynamic key
JSONArray currentDynamicValue = listMainObj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int i = 0; i < jsonrraySize; i++) {
JSONObject brandidObj = currentDynamicValue.getJSONObject(i);
String brandid = brandidObj.getString("brandid");
System.out.print("Brandid = " + brandid);
//store brandid in an arraylist
}
}
}
Source of this answer

Adding elements from one array to another Java

Just coming back to Java after a few years break. I am trying to select elements from one array and store them in another in Java. I have created a new array of the same type with a fixed number of elements. The array that I am copying from is not null I have printed it out. But when I try to display the new array the values are not there - just a reference to the element. There probably something that I have overlooked. I have been searching for the last day but am not getting anywhere. I would really appreciate some help. Code below:
PersonDetails user = new PersonDetails(userName,userGender,userAge,userInterests);
PersonDetails [] userArray = new PersonDetails [numberOfDaters];
PersonDetails [] dateArray = new PersonDetails [numberOfDaters];
userArray = user.getArray("datingdata.txt", numberOfDaters);
dateArray = Arrays.copyOf(userArray, userArray.length);
char [][] interestArray = new char[numberOfDaters][5];
for (int z =0;z<userArray.length; z++) {
interestArray[z] =
userArray[z].getAllInterests( userArray[z].getInterests());
}
String remove = user.getOnes(interestArray);
System.out.print(remove);
StringTokenizer st = new StringTokenizer(remove);
int num = st.countTokens();
PersonDetails [] userRemoveArray = new PersonDetails [num];
while(st.hasMoreTokens()) {
int token = Integer.parseInt(st.nextToken());
for(int x =0;x<userRemoveArray.length;x++) {
userRemoveArray[x] = userArray[token];
}
System.out.println(userRemoveArray);
}
The output is as follows:
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
Thanks in advance
You can use the .addAll(...) method or one of the many methods found here.
As for printing out the elements of the array... you will have to implement your own .toString() method to avoid displaying the object reference.
Here is a small example to make it more easier for you since you had noted that you are just coming back to Java after sometime and i hope this helps you out :)
public class PersonDetails {
private String userName;
private String gender;
#Override
public String toString() {
return "PersonDetails [userName=" + userName + ", gender=" + gender
+ "]";
}
}
Now when you print out the Array, the String created within the toString() method will print for each PersonDetail object.
You should use System.out.println(Arrays.asList(userRemoveArray));.
or
for(int i = 0; i < userRemoveArray.length;i++) {
System.out.print(userRemoveArray[i]+", ");
}
System.out.println();

What should I do to solve this error?

I was using JSONParser to obtain results of a search, for that I followed this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
The thing is that, the API I am using gives the results like this:
{"response":[50036,{"aid":88131498,"owner_id":61775052,"artist":"Terror Squad","title":"Lean Back (OST Need For Speed Underground 2)","duration":249,"url":"http:\/\/cs4408.vkontakte.ru\/u59557424\/audio\/7f70f58bb9b8.mp3","lyrics_id":"3620730"},{"aid":106963458,"owner_id":-24764574,"artist":"«Dr. Dre ft Eminem, Skylar Grey (Assault Terror)","title":"I Need A Doctor (ASSAULT TERROR DUBSTEP REMIX)»","duration":240,"url":"http:\/\/cs5101.vkontakte.ru\/u79237547\/audio\/12cd12c7f8c2.mp3","lyrics_id":"10876670"}]}
My problem comes when I have to parse the first integer (here it is 50036) which is the number of results found.
I don't know how to read that integer.
This is my code:
private void instance(String artisttrack){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String jsonurl = new String( "https://api.vk.com/method/audio.search?access_token=ACC_TOKEN&api_id=ID&sig=SIG&v=2.0&q=" + artistname + artisttrack + "&count=5");
JSONObject json = jParser.getJSONFromUrl(jsonurl);
try {
// Getting Array of Contacts
response = json.getJSONArray(TAG_RESPONSE);
// looping through All Contacts
for(int i = 0; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
// Storing each json item in variable
//int results = Integer.parseInt(c.getString(TAG_RESULTS));
String aid = c.getString(TAG_AID);
String owner_id = c.getString(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
String duration = c.getString(TAG_DURATION);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
String url = c.getString(TAG_URL);
String lyrics_id = c.getString(TAG_LYRICS_ID);
Log.e("áaaaaaaaaaaaaaa", url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The JSONParser.java is like written in the tutorial.
And here 2 lines of the logcat error:
W/System.err(10350): org.json.JSONException: Value 50036 at 0 of type java.lang.Integer cannot be converted to JSONObject
W/System.err(10350): at org.json.JSON.typeMismatch(JSON.java:100)
Your JSON sample is a poor way to organize the results: mixing the number in with the result objects. Is the number supposed to indicate the number of objects in the array or something else?
If you can assume that this number will always be the first element, and according to this then it's supposed to work this way, you can try to read the first value of the array outside the loop:
response = json.getJSONArray(TAG_RESPONSE);
// from your example, num will be 50036:
num = response.getInt(0);
for (int i = 1; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
Note that the example in the linked documentation has this number as a string:
{"response":
["5",
{"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
But JSONArray.getInt() will parse the String as an int for you.
And notice that some of the values in the objects in your array are also numbers, you may want to read those as int also:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
int duration = c.getInt(TAG_DURATION);
A lot of the values you are trying to parse in are not String objects, specifically "aid", "owner_id", and "duration". Use the correct method to retrieve values. For example:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
int duration = c.getInt(TAG_DURATION);
edit: Another error that I missed is you start your array with 50036. This is not a JSONObject and cannot be parsed as so. You can add a conditional statement to check if it's array index 0 to parse the int using getInt(), and then parse as JSONObjects for the rest of the array values.
Try changing
response = json.getJSONArray(TAG_RESPONSE);
into
response = (JSONObject)json.getJSONArray(TAG_RESPONSE);
I dont have any experience with JSONObject, but works often with type mismatches.
Try putting 50036 in quotes like this "50036" .

Categories