Accessing Items in an Array - AS3 - arrays

I've got an Object item.movieimage that contain some texts (item:Object) that is retrieve from my database. The text is changing every week automatically.
If I do trace(item.movieimage) the output is something like this :
text1
text2
text3
text4
The words changes as the code is taking them from my database. The database changes the words every week.
Now, I want my AS3 code to display the third element of item.movieimage.
I've tried to do this :
var my_str:String = item.movieimage+",";
var ary:Array = my_str.split(",");
trace(ary[2]);
But it's not working. The output is "undefined".
Do you know how can I access a specific item in the Array that I've created ? Or how can I access the third item of item.movieimage ?
If I do trace(ary);, the output is :
text1,
text2,
text3,
text4,
EDIT :
For infos :
trace(typeof(item.movieimage)) and trace(typeof(ary)) are :
typeof(item.movieimage)=string
typeof(ary)=object
EDIT 2 :
Here's a screen capture of item.movieimage
Screen Cap of item.movieimage
EDIT 3
Here's my code in order to understand how "item.movieimage"is working
//Variables for downloading content from my database to my AS3 code
var urlReqSearchAll: URLRequest = new URLRequest("http://www.myWebSite/searchMovie4.php");
var loader5:URLLoader = new URLLoader();
//downloading content
function searchAll():void {
if (contains(list)){
list.removeChildren();
}
urlReqSearchAll.method = URLRequestMethod.POST;
loader5.load(urlReqSearchAll);
loader5.addEventListener(Event.COMPLETE,complete);
var variables:URLVariables = new URLVariables();
}
//Content Downloaded.
function complete(e:Event):void {
addChild(list);
products = JSON.parse(loader5.data) as Array;
hourSaved.data.saved=loader5.data;
products.reverse();
for(var i:int = 0; i < products.length; i++){
createListItem(i, products[i]);
}
displayPage(0);
showList();
}
// If too much items --> creates multiple page
const itemsPerPage:uint = 7;
var currentPageIndex:int = 0;
function displayPage(pageIndex:int):void {
list.removeChildren();
currentPageIndex = pageIndex;
var firstItemIndex:int = pageIndex * itemsPerPage;
var j:int = 0;
var lastItemIndex: int = firstItemIndex + 7; // as lastItemIndex should be 10 more
if (lastItemIndex > products.length) // if lastindex is greater than products length
lastItemIndex = products.length;
for(var i:int = firstItemIndex; i< lastItemIndex; i++){
createListItem( j, products[i]); // j control the position and i points to particular element of array..
j++;
}
next.visible = lastItemIndex < products.length - 1;
if(currentPageIndex==0){
previous.visible=false;
}
}
// Display the information downloded from my database
function createListItem(index:int, item:Object):void {
var listItem:TextField = new TextField();
var myFormat:TextFormat = new TextFormat();
myFormat.size = item.title.length > 13 ? 22 : 26
listItem.multiline = true;
listItem.wordWrap = true;
myFormat.align = TextFormatAlign.CENTER;
myFormat.color = 0xA2947C;
myFormat.font = "Ebrima";
myFormat.bold = true;
listItem.defaultTextFormat = myFormat;
listItem.x = 135;
listItem.y = 123+ index * 84;
listItem.width = 200;
listItem.height = 80;
listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
showDetails(item);
});
list.addChild(listItem);
str = item.title;
}
My php file "SearchMovie4.php" is like this :
$products = array();
while ($row = mysql_fetch_array($sql_result)) {
$products[] = array(
"title" => $row["theTitle"],
"movieimage" => $row["movieimage"],
"movielength" => $row["movielength"],
"story" => $row["story"],
);
}
echo json_encode($products);
So, if I do trace(item.movieimage) in AS3 code, it will display all the items in the row movieimage of my database.
If I do trace(item.title) in AS3 code, it will display all the items in the row title of my database.
What I'd like is to be able to do, in my AS3 code, trace(item.movieimage[2]) in order to show me the third item in the row "movieimage".

Well, the text you've provided to the movieimage property of the item object has not the same delimiter as what you have provided to the split() method; in your case the character of comma!
I suspect the delimiter you have, is the "space" character or a new-line character, like the character of carriage retrun.
In the following code snippet, I've used the "space" as the delimiter character:
var item:Object = new Object();
item.movieimage = "text1 text2 text3 text4";
var my_str:String = item.movieimage;
var ary:Array = my_str.split(" ");
trace(ary[2]); // text3

As #someOne said the output shows the list items are each on a new line, so you need to split() against newlines. One of these should work:
// if server uses "\n" newline char
var movies:Array = item.movieimage.split("\n");
// if server uses "\r" carriage return char
var movies:Array = item.movieimage.split("\r");
// if you aren't sure or there's a mixture of newline chars
var movies:Array = item.movieimage.split(/[\r|\n]+/);
Also note that if you have any control over how the server returns these values, you should just return a JSON array (since I see in your screenshot you are already decoding JSON), then you won't have to do any string splitting.

Related

Filtering an Array of Sheets on three criteria with output being the URL link to the filtered sheets

I am creating two lists of links on my opening sheet (9060DASH) in Google Sheets. It looks like this:
One list is links to all sheets that are not hidden (Active) and one to all that are hidden. Each item must meet two other criteria to be included:
The sheet name must not include the numbers "9060."
The cell GH3 in the sheet must contain "Protected."
I have a functioning script, but it is loading too slowly. Here is a sample to show how it loads during onOpen(). How can I do this more efficiently? Can it be done better using "push"? Here is the script:
function populateSheetList() {
SpreadsheetApp.getActive().getSheetByName("9060DASH").activate();
var ss = SpreadsheetApp.getActive();
var ui = SpreadsheetApp.getUi();
ss.getRange('9060DASH!D4:E100').clear();
var counter = 4;
var sheetName = "";
var cellID= "";
var richValue = "";
var sheetURL = ss.getUrl();
var sheetLink = ""
var mySheet = "";
var shouldNotContain = '9060'; //array code from stackover to build array without 9060 sheets
var sheetNames = SpreadsheetApp.getActiveSpreadsheet().getSheets().map(s => s.getName());
var filtered = sheetNames.filter(x => !x.toLowerCase().match(shouldNotContain.toLowerCase()));
/** CREATES ACTIVE SHEETS LIST */
for(var i =0;i<filtered.length;i++){
cellID = '9060DASH!D'+counter;
sheetName = filtered[i];
mySheet = ss.getSheetByName(sheetName);
sheetLink = sheetURL+'#gid='+ mySheet.getSheetId();
if(mySheet.isSheetHidden() == false){
if(ss.getRange(sheetName+"!GH3").getValue() == "Protected"){
richValue = SpreadsheetApp.newRichTextValue()
.setText(sheetName)
.setLinkUrl(sheetLink)
.build();
ss.getRange(cellID).setRichTextValue(richValue);
counter = counter+1;
}
}
}
/** GATHERING HIDDEN SHEETS */
var counter = 4;
for(var i =0;i<filtered.length;i++){
cellID = '9060DASH!E'+counter;
sheetName = filtered[i];
mySheet = ss.getSheetByName(sheetName);
sheetLink = sheetURL+'#gid='+ mySheet.getSheetId();
if(mySheet.isSheetHidden() == true){
if(ss.getRange(sheetName+"!GH3").getValue() == "Protected"){
richValue = SpreadsheetApp.newRichTextValue()
.setText(sheetName)
.setLinkUrl(sheetLink)
.build();
ss.getRange(cellID).setRichTextValue(richValue);
counter = counter+1;
}
}
}
}
I have reduced the time to load the dashboard by rearranging a number of things and by getting a final array before writing anything out to the dash. I reformatted the cells and sorted the records before the evaluation loops began. I added more status messages, to keep users engaged while the background work was going on. I put the criteria of separating active from hidden sheets last and, depending on which, wrote the values to two different arrays (actvSheets and hidnSheets). Then I processed each array out to the dashboard. I did this in for loops. I suspect I could save even more time to write them out as one command from each array, but I have not been able to figure out how to write out in vertical form. Here is the code. Any refinements are welcome!
/**
* =================
* populateSheetList
* =================
* This function builds the available sheets in the
* 9060DASH sheet--containing all with the Protected
* status.
*/
function populateSheetListNEW() {
msgDash("Clearing sheet list . . . ")
// SpreadsheetApp.getActive().getSheetByName("9060DASH").activate();
var ss = SpreadsheetApp.getActive();
var ui = SpreadsheetApp.getUi();
ss.getRange('9060DASH!D4:E100')
.clear()
.setFontSize(14)
.setHorizontalAlignment('left')
.sort({column: 4, ascending: true})
msgDash("Evaluating sheets . . . ")
var counter = 4;
var sheetName = "";
var cellID= "";
var richValue = "";
var sheetURL = ss.getUrl();
var sheetLink = ""
var mySheet = "";
var actvSheets = [];
var hidnSheets = [];
msgDash("Eliminating administrative sheets . . . ")
var shouldNotContain = '9060'; //array code from stackover to build array without 9060 sheets
var sheetNames = SpreadsheetApp.getActiveSpreadsheet().getSheets().map(s => s.getName());
var filtered = sheetNames.filter(x => !x.toLowerCase().match(shouldNotContain.toLowerCase()));
var sortFilt = filtered.sort();
/** CREATES SHEET ARRAYS */
msgDash("Gathering census worksheets . . . ")
for(var i =0;i<sortFilt.length;i++){
sheetName = sortFilt[i];
mySheet = ss.getSheetByName(sheetName);
if(ss.getRange(sheetName+"!GH3").getValue() == "Protected"){
if(mySheet.isSheetHidden() == false){
actvSheets.push(sheetName);
} else {
hidnSheets.push(sheetName);
}
}
}
msgDash("Gathering active sheets . . . ")
/** WRITING DATA FROM ACTVSHEETS ARRAY */
for(var j = 0; j < actvSheets.length; j++){
sheetName = actvSheets[j];
mySheet = ss.getSheetByName(actvSheets[j]);
sheetLink = sheetURL+'#gid='+ mySheet.getSheetId();
richValue = SpreadsheetApp.newRichTextValue()
.setText(sheetName)
.setLinkUrl(sheetLink)
.build();
cellID = '9060DASH!D' + counter;
counter = counter+1;
ss.getRange(cellID).setRichTextValue(richValue);
}
msgDash("Gathering hidden sheets . . . ");
/** WRITING DATA FROM HDDNSHEETS ARRAY */
counter = 4;
for(var k = 0; k< hidnSheets.length; k++){
sheetName = hidnSheets[k];
mySheet = ss.getSheetByName(hidnSheets[k]);
sheetLink = sheetURL+'#gid='+ mySheet.getSheetId();
richValue = SpreadsheetApp.newRichTextValue()
.setText(sheetName)
.setLinkUrl(sheetLink)
.build();
cellID = '9060DASH!E' + counter;
counter = counter+1;
ss.getRange(cellID).setRichTextValue(richValue);
}
msgDash('Dashboard ready. Enjoy your census work!');
ss.getRange('9060DASH!D2').setValue("For hidden sheets, respond to 'Unhide' instruction. Click Refresh button to rebuild list.");
Utilities.sleep(20);
msgDash(''); //clears messages
}

Adding a movieclip in each square of my calendar (AS3)

I've got a calendar with squares in wich each date is wrote :
var myArray:Array = new Array();
var row:Number = 0;
var moonNum:Number;
var holder_txt:MovieClip = new MovieClip;
addChild(holder_txt);
holder_txt.x = 35;
holder_txt.y = 10;
startDay -= 1;
for (var t:int = 0; t < getDays(myDate); t++) {
myArray[t] = (t+1);
var textNum:String = myArray[t];
import box;
import moonPhase;
var square:MovieClip = new box();
var moon:MovieClip = new moonPhase();
holder_txt.addChild(square);
square.name = textNum
moonNum= calculateMoonPhase(myDate.fullYear, myDate.month,t+1);
square.texter.text = textNum +" "+ moonNum;
square.x = (startDay) *75
square.y = (row+1)*65
startDay++;
if(startDay >= 7){
startDay = 0;
row++;
I've got a function that calculate the moonPhase for everyday.
moonNum= calculateMoonPhase(myDate.fullYear, myDate.month,t+1);
It results as a number (between 0 and 8).
I've got movieClip of a moon with 8 frames (new moon,full moon...etc).
I'd like to add the movieClip of the moon on each square with the corresponding frame number.
moonClip.gotoAndStop(moonNum);
I've add each moonNum to each square day :
square.texter.text = textNum +" "+ moonNum;
But I've no idea how to add movieclips to each square day...
Any help ?
It's better to add moonPhase in the class box directly. So for each box that you copied, you have an instance of moon in it to.
But, in your sample code, you can add moon to the square directly to.
square.addChild(moon);

Can i display multiple copies of a movieclip inside a array at once

Is there a way to make the code below work properly? When I use this code it only shows one movieclip:
var tempHead:head001 = new head001();
var mcArr:Array = new Array( tempHead );
var firstHead:MovieClip = mcArr[0];
firstHead.y = 30;
addChild(firstHead);
var secondHead:MovieClip = mcArr[0];
secondHead.y = 180;
addChild(secondHead);
`
You were just assigning a reference to the MovieClip. That'y, its not working.
First take instance of head001 class using new operator as much you want and store it to an array, then you can access very easily.
var tempHead: head001;
var mcArr: Array = new Array();
for (var i: uint = 0; i < 2; i++) {
tempHead = new head001();
addChild(tempHead);
mcArr.push(tempHead);
mcArr[i].y = mcArr[i].height * i;
}

InvalidCastException: Cannot cast from source type to destination type

I have fetched the data from xml and stored it in an array.I have coded as below
Private var dataarray=new Array();
private var timearray=new Array();
private var distancearray=new Array();
private var detailStock : String;
private var distancedata : String;
private var timedata : String;
private var datalist : String;
private var data : String;
function readMe() {
var filepath : String = Application.dataPath+"/XmlDocs/"+"Stock"+".xml";
var xmlDoc : XmlDocument = new XmlDocument();
if(File.Exists (filepath))
{
xmlDoc.Load( filepath );
var Stock_list : XmlNodeList = xmlDoc.GetElementsByTagName("Stock");
for(var i : int = 0; i < Stock_list.Count;i++)
{
// getting child nodes of stock, like Rice and Wheat in a list
var StockItems_list : XmlNodeList = Stock_list.Item(i).ChildNodes;
// running a loop through all items present in the stock
for(var j : int = 0; j < StockItems_list.Count; j++)
{
//Debug.Log("StockItems_list count"+StockItems_list.Count);
// taking the properties of a item into a list like Price and Quantity
var StockItemsProperties_list : XmlNodeList = StockItems_list.Item(j).ChildNodes;
for(var k : int = 0; k < StockItemsProperties_list.Count; k++)
{
//Debug.Log("length....."+ StockItemsProperties_list[k].InnerText);
data=StockItemsProperties_list[k].InnerText+"\t";
//Debug.Log(data);
/*--------Pushed the full data into an array-----------*/
// dataarray=new Array();
dataarray.Push(data);
//Debug.Log("Elements in the array"+dataarray);
}
//var StockItemsProperties_list : XmlNodeList =StockItems_list[j].
// Getting Names of Items like Rice and Wheat
detailStock+="\n"+StockItems_list[j].Name+"\n";
// We know that Price is stored at Oth element of StockItemsProperties_list
detailStock+=StockItemsProperties_list[0].Name+" ";
// Inner Text of StockItemsProperties_list[0] (Price node) Contains the money
detailStock+=StockItemsProperties_list[0].InnerText+" "+"Rs"+"\n";
// And Quantity at 1st element of StockItemsProperties_list
detailStock+=StockItemsProperties_list[1].Name+" ";
// Inner Text of StockItemsProperties_list[1] (Quantity node) Contains the Quantity in Kg
detailStock+=StockItemsProperties_list[1].InnerText+" "+"Kg"+"\n";
//Debug.Log("distance"+StockItemsProperties_list[0].InnerText);
//Debug.Log("seconds"+StockItemsProperties_list[1].InnerText);
distancedata=StockItemsProperties_list[0].InnerText;
distancearray=new Array();
distancearray.Push(distancedata);
//Debug.Log("distance Array............ "+distancearray);
/*--------------Print the time into time array -----------------*/
timedata=StockItemsProperties_list[1].InnerText;
timearray=new Array();
timearray.Push(timedata);
// Debug.Log("time Array............ "+timearray);
/*-------------Distance and time from both array array ------------------*/
for(var d=0;d<distancearray.length;d++)
{
for(var t=0;t<timearray.length;t++)
{
// Debug.Log("distance : " +distancearray[d] +" "+"time: "+timearray[t]+"\n");
transform.position-=new Vector3(0,distancearray[d],0);
Debug.Log(transform.position);
}
}
With the above code Iam able to print the values.
But I want to move my object based on the values stored in the distancearray. transform.position-=new Vector3(0,distancearray[d],0);
the code for moving an object is getting the below exception
InvalidCastException: Cannot cast from source type to destination type.
Boo.Lang.Runtime.RuntimeServices.CheckNumericPromotion (IConvertible convertible)
Boo.Lang.Runtime.RuntimeServices.CheckNumericPromotion (System.Object value)
Boo.Lang.Runtime.RuntimeServices.UnboxSingle (System.Object value)
xmlDataReader.ReadXml () (at Assets/script/xmlDataReader.js:286)
xmlDataReader.OnGUI () (at Assets/script/xmlDataReader.js:141)
What will be the issue.Any problem with the variable declaration type?.Please help me out
This is UnityScript.
The issue is likely caused by distancedata being String, hence distancearray being array of String, not int.
Try this:
private var distancedata : int;
...
distancedata = parseInt(StockItemsProperties_list[0].InnerText);
Though malformed XML can also be the reason.

url sharepoint list camlquery

I'm trying to collect my url and the description of the url stored in a column of a list from sharepoint and i don't know how to collect the URL value.
This is my code :
var queryResultSaleListItems = clientContext.LoadQuery(listData);
clientContext.ExecuteQuery();
//Read the Data into the Object
var TipsList = from Tips in queryResultSaleListItems
select Tips;
ObservableCollection<Tips> colTips = new ObservableCollection<Tips>();
//Read Every List Item and Display Data into the DataGrid
foreach (SPSClient.ListItem item in TipsList)
{
var tips = new Tips();
tips.TitleTip = item.FieldValues.Values.ElementAt(1).ToString();
tips.App = item.FieldValues.Values.ElementAt(4).ToString();
//should collect the url
tips.URL = item.FieldValues.Values.ElementAt(5).ToString();
//should collect the description of the url
tips.URLdesc = item.FieldValues.Values.ElementAt(5).ToString();
colTips.Add(tips);
}
ListboxTips.DataContext = colTips;
In my expression its >
((Microsoft.SharePoint.Client.FieldUrlValue)(item.FieldValues.Values.ElementAt(5))).Url
((Microsoft.SharePoint.Client.FieldUrlValue)(item.FieldValues.Values.ElementAt(5))).Description
Thanks for your help,
Use FieldUrlValue for getting hyperlink field in Client Object Model.
Use Following Code:
string server = "siteURL";
var ctx = new ClientContext(server);
var web = ctx.Web;
var list = web.Lists.GetByTitle("CustomList");
var listItemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(listItemCollection);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem listItem in listItemCollection)
{
string acturlURL = ((FieldUrlValue)(listItem["URL"])).Url.ToString(); // get the Hyperlink field URL value
string actdesc = ((FieldUrlValue)(listItem["URL"])).Description.ToString(); // get the Hyperlink field Description value
}

Resources