Replacing UUID of player to player's name - minecraft

I am trying to send a message to the player with his saved friends. These friends are saved in a .yml file, but only the UUIDS of each individual player.
I am then trying to replace the UUID or convert it to the players name when the message is displayed (if that made sense)
CODE:
p.sendMessage("§7▄▄▄▄▄▄▄▄▄▄▄▄§aFriend System - page 1 of 1§7▄▄▄▄▄▄▄▄▄▄▄▄");
int i = 1;
int length = cfg.getList(p.getUniqueId() + ".Friends").size();
if (length != 0)
{
while (i <= length)
{
String uuid = (String)cfg.getList(p.getUniqueId() + ".Friends").get(i - 1);
ProxiedPlayer p2 = ProxyServer.getInstance().getPlayer(UUID.fromString(uuid));
if (p2 != null)
{
TextComponent prefix = new TextComponent(Main.prefix);
TextComponent join = new TextComponent("§a§lONLINE");
prefix.addExtra("§9" + p2.getName());
prefix.addExtra(" ");
prefix.addExtra(join);
p.sendMessage(prefix);
}
else
{
String name = getNamebyUUID(uuid);
if (name != null)
{
p.sendMessage(Main.prefix + "§9" + name + " §c§lOFFLINE");
Main.names.put(uuid, name);
}
else if (Main.names.containsKey(uuid))
{
p.sendMessage(Main.prefix + "§9" + (String)Main.names.get(uuid) + " §8[§c§lOFFLINE§8]");
}
else
{
p.sendMessage(Main.prefix + "§cThis is not a valid player!");
}
}
i++;
}
}
else
{
p.sendMessage(Main.prefix + "§cYou don't have any friends.");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}

Related Question: Get Offline Player by UUID
If the Player is online:
String playerUUID;
Bukkit.getPlayer(playerUUID).getDisplayName();
If the Player is offline:
Not trully possible. The Player can change names at any time, and Bukkit can't keep that information and keep updating all the player's name whenever they change.
You can either use the online-player-only method above, or store the player's name together with the uuid.
#UPDATE
As stated by the user Pokechu22, Bukkit does save the last name the user used before logging out. It can be retrieved this way:
OfflinePlayer off = Bukkit.getOfflinePlayer(String uuid);
String lastKnownName = off.getName();
But be very careful! It might not be the up-to-date name of the player.

Related

Cannot add row without complete selection of batch/serial numbers

ERROR: (-4014) Cannot add row without complete selection of batch/serial numbers.
The default function of DI API SaveDraftToDocument() is working fine on MS SQL Database but not SAP HANA.
I am posting the Delivery document with Serial Numbers.
SAPbobsCOM.Documents oDrafts;
oDrafts = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);
oDrafts.GetByKey(Convert.ToInt32(EditText27.Value));
var count = oDrafts.Lines.Count;
var linenum = oDrafts.Lines.LineNum;
//Validation
#region
var RsRecordCount = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
var sQryRecordCount = String.Format("Select * from \"SANTEXDBADDON\".\"#TEMPITEMDETAILS\" where \"U_DraftNo\" = '{0}'", EditText27.Value);
RsRecordCount.DoQuery(sQryRecordCount);
#endregion
if (count == RsRecordCount.RecordCount)
{
//LINES
string ItemCode = "", WhsCode = ""; double Quantity = 0; int index = 0;
for (int i = 0; i < oDrafts.Lines.Count; i++)
{
oDrafts.Lines.SetCurrentLine(index);
ItemCode = oDrafts.Lines.ItemCode;
//SERIAL NUMBERS
var RsSerial = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
string table = "\"#TEMPSERIALS\"";
var sQrySerial = String.Format(
"Select \"U_ItemCode\" , \"U_DistNumber\" from \"SANTEXDBADDON\".\"#TEMPSERIALS\" where " +
"\"U_DraftNo\" = '{0}' and \"U_ItemCode\" = '{1}'", EditText27.Value, ItemCode);
RsSerial.DoQuery(sQrySerial);
int serialindex = 1, lineindex = 0;
#region
if (RsSerial.RecordCount > 0)
{
while (!RsSerial.EoF)
{
//OSRN SERIALS
var RsSerialOSRN = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
var sQrySerialOSRN = String.Format(
"Select * from OSRN where \"DistNumber\" = '{0}' and \"ItemCode\" = '{1}'"
, RsSerial.Fields.Item("U_DistNumber").Value.ToString(), ItemCode);
RsSerialOSRN.DoQuery(sQrySerialOSRN);
oDrafts.Lines.SerialNumbers.SetCurrentLine(0);
oDrafts.Lines.SerialNumbers.BaseLineNumber = oDrafts.Lines.LineNum;
oDrafts.Lines.SerialNumbers.SystemSerialNumber =
Convert.ToInt32(RsSerialOSRN.Fields.Item("SysNumber").Value.ToString());
oDrafts.Lines.SerialNumbers.ManufacturerSerialNumber =
RsSerialOSRN.Fields.Item("DistNumber").Value.ToString();
oDrafts.Lines.SerialNumbers.InternalSerialNumber =
RsSerialOSRN.Fields.Item("DistNumber").Value.ToString();
oDrafts.Lines.SerialNumbers.Quantity = 1;
if (RsSerial.RecordCount != serialindex)
{
Application.SBO_Application.StatusBar.SetText("INTERNAL NO " + oDrafts.Lines.SerialNumbers.InternalSerialNumber, SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
oDrafts.Lines.SerialNumbers.Add();
serialindex++;
lineindex++;
}
RsSerial.MoveNext();
}
}
#endregion
index++;
}
var status = oDrafts.SaveDraftToDocument();
if (status == 0)
{
oDrafts.Remove();
Application.SBO_Application.StatusBar.SetText("Delivery Posted Successfully !", SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
}
else
{
int code = 0; string message = "";
oCompany.GetLastError(out code, out message);
Application.SBO_Application.SetStatusBarMessage(message, SAPbouiCOM.BoMessageTime.bmt_Medium, true);
}
}`
The error you have posted explains the problem. You are trying to deliver products but have not included all of the serial/batch numbers.
I don't think there's enough information to be sure where this problem happens, but here are some pointers:
You are reading the serial numbers from a custom table. Are the values you are reading valid? For example, could another user have added them to a different order? Could the values be for a different product?
Are you specifying the correct quantity of serial numbers? Is it possible that the item quantity on the line is more than the number of serial numbers you are adding?
Believe the error message until you can prove it's wrong. It doesn't seem like this is a HANA issue (we use HANA extensively) it's a logical problem with the data you are providing.
You may want to capture more debugging information to help you if you can't easily identify where the problem is.

How to avoid to fetch a list of followers of the same Twitter user that was displayed before

I'm very new at coding and I'm having some issues. I'd like to display the followers of followers of ..... of followers of some specific users in Twitter. I have coded this and I can set a limit for the depth. But, while running the code with a small sample, I saw that I run into the same users again and my code re-display the followers of these users. How can I avoid this and skip to the next user? You can find my code below:
By the way, while running my code, I encounter with a 401 error. In the list I'm working on, there's a private user, and when my code catches that user, it stops. Additionally, how can I deal with this issue? I'd like to skip such users and prevent my code to stop.
Thank you for your help in advance!
PS: I know that I'll encounter with a 429 error working with a large sample. After fixing these issues, I'm planning to review relevant discussions to deal with.
public class mainJava {
public static Twitter twitter = buildConfiguration.getTwitter();
public static void main(String[] args) throws Exception {
ArrayList<String> rootUserIDs = new ArrayList<String>();
Scanner s = new Scanner(new File("C:\\Users\\ecemb\\Desktop\\rootusers1.txt"));
while (s.hasNextLine()) {
rootUserIDs.add(s.nextLine());
}
s.close();
for (String rootUserID : rootUserIDs) {
User rootUser = twitter.showUser(rootUserID);
List<User> userList = getFollowers(rootUser, 0);
}
}
public static List<User> getFollowers(User parent, int depth) throws Exception {
List<User> userList = new ArrayList<User>();
if (depth == 2) {
return userList;
}
IDs followerIDs = twitter.getFollowersIDs(parent.getScreenName(), -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User child = twitter.showUser(id);
userList.add(child);
getFollowers(child, depth + 1);
System.out.println(depth + "th user: " + parent.getScreenName() + " Follower: " + child.getScreenName());
}
return userList;
}
}
I guess graph search algorithms can be implemented for this particular issue. I chose Breadth First Search algorithm because visiting root user's followers at first would be better. You can check this link to additional information about algorithm.
Here is my implementation for your problem:
public List<User> getFollowers(User parent, int startDepth, int finalDepth) {
List<User> userList = new ArrayList<User>();
Queue<Long> queue = new LinkedList<Long>();
HashMap<Long, Integer> discoveredUserId = new HashMap<Long, Integer>();
try {
queue.add(parent.getId());
discoveredUserId.put(parent.getId(), 0);
while (!queue.isEmpty()) {
long userId = queue.remove();
int discoveredDepth = discoveredUserId.get(userId);
if (discoveredDepth == finalDepth) {
continue;
}
User user = twitter.showUser(userId);
handleRateLimit(user.getRateLimitStatus());
if (user.isProtected()) {
System.out.println(user.getScreenName() + "'s account is protected. Can't access followers.");
continue;
}
IDs followerIDs = null;
followerIDs = twitter.getFollowersIDs(user.getScreenName(), -1);
handleRateLimit(followerIDs.getRateLimitStatus());
long[] ids = followerIDs.getIDs();
for (int i = 0; i < ids.length; i++) {
if (!discoveredUserId.containsKey(ids[i])) {
discoveredUserId.put(ids[i], discoveredDepth + 1);
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
userList.add(child);
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
queue.add(ids[i]);
} else {//prints to console but does not check followers. Just for data consistency
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
return userList;
}
//There definitely are more methods for handling rate limits but this worked for me well
private void handleRateLimit(RateLimitStatus rateLimitStatus) {
//throws NPE here sometimes so I guess it is because rateLimitStatus can be null and add this conditional expression
if (rateLimitStatus != null) {
int remaining = rateLimitStatus.getRemaining();
int resetTime = rateLimitStatus.getSecondsUntilReset();
int sleep = 0;
if (remaining == 0) {
sleep = resetTime + 1; //adding 1 more second
} else {
sleep = (resetTime / remaining) + 1; //adding 1 more second
}
try {
Thread.sleep(sleep * 1000 > 0 ? sleep * 1000 : 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
in this code HashMap<Long, Integer> discoveredUserId is used to prevent program checking same users repeatedly and storing in which depth we faced with this user.
and for private users, there is isProtected() method in twitter4j library.
Hope this implementation helps.

Sales force EMP connector, stops receiving notification after some time

I am performing a POC to check Streaming API stability, POC is as follows
Program 1 : subscribe to pushtopic created against Account object
Program 2 : create, update & delete single record after every 10 min interval
Both this programs were kept running for more than 12 hours (left overnight), after that I verified if all notification are received or not and found that after sometime (in this case it was nearly ~ 2 hours 45 min ) no notification were received, I repeated this twice and both case it stops getting notification after sometime.
Test code used
Streaming API client (using EMP connector)
public class SFPoc {
static Long count = 0L;
static Long Leadcount = 0L;
public static void main(String[] argv) throws Exception {
String userName = "<user_name>";
String password = "<pwd>";
String pushTopicName = "/topic/AccountPT";
String pushTopicNameLead = "/topic/Leadwhere";
long replayFrom = EmpConnector.REPLAY_FROM_EARLIEST;
String securityToken = "<token>";
BayeuxParameters custom = getBayeuxParamWithSpecifiedAPIVersion("37.0");
BayeuxParameters params = null;
try {
params = login(userName, password + securityToken, custom);
} catch (Exception e) {
e.printStackTrace();
}
Consumer<Map<String, Object>> consumer = event -> System.out.println(String.format("Received:\n%s ** Recieved at %s, event count total %s", event, LocalDateTime.now() , ++count));
Consumer<Map<String, Object>> consumerLead = event -> System.out.println(String.format("****** LEADS ***** Received:\n%s ** Recieved at %s, event count total %s", event, LocalDateTime.now() , ++Leadcount));
EmpConnector connector = new EmpConnector(params);
connector.start().get(10, TimeUnit.SECONDS);
TopicSubscription subscription = connector.subscribe(pushTopicName, replayFrom, consumer).get(10, TimeUnit.SECONDS);
TopicSubscription subscriptionLead = connector.subscribe(pushTopicNameLead, replayFrom, consumerLead).get(10, TimeUnit.SECONDS);
System.out.println(String.format("Subscribed: %s", subscription));
System.out.println(String.format("Subscribed: %s", subscriptionLead));
}
private static BayeuxParameters getBayeuxParamWithSpecifiedAPIVersion(String apiVersion) {
BayeuxParameters params = new BayeuxParameters() {
#Override
public String version() {
return apiVersion;
}
#Override
public String bearerToken() {
return null;
}
};
return params;
}
}
Code which is doing record create/update/delete periodically to generate events
import com.sforce.soap.enterprise.*;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Contact;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import java.time.LocalDateTime;
public class SFDCDataAdjustment {
static final String USERNAME = "<username>";
static final String PASSWORD = "<pwd&securitytoken>";
static EnterpriseConnection connection;
static Long count = 0L;
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
config.setPassword(PASSWORD);
//config.setTraceMessage(true);
try {
connection = Connector.newConnection(config);
// display some current settings
System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
System.out.println("Service EndPoint: "+config.getServiceEndpoint());
System.out.println("Username: "+config.getUsername());
System.out.println("SessionId: "+config.getSessionId());
// run the different examples
while (true) {
createAccounts();
updateAccounts();
deleteAccounts();
Thread.sleep(1 * 10 * 60 * 1000);
}
} catch (ConnectionException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// queries and displays the 5 newest contacts
private static void queryContacts() {
System.out.println("Querying for the 5 newest Contacts...");
try {
// query for the 5 newest contacts
QueryResult queryResults = connection.query("SELECT Id, FirstName, LastName, Account.Name " +
"FROM Contact WHERE AccountId != NULL ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Contact
Contact c = (Contact)queryResults.getRecords()[i];
System.out.println("Id: " + c.getId() + " - Name: "+c.getFirstName()+" "+
c.getLastName()+" - Account: "+c.getAccount().getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// create 5 test Accounts
private static void createAccounts() {
System.out.println("Creating a new test Account...");
Account[] records = new Account[1];
try {
// create 5 test accounts
for (int i=0;i<1;i++) {
Account a = new Account();
a.setName("OptyAccount "+i);
records[i] = a;
}
// create the records in Salesforce.com
SaveResult[] saveResults = connection.create(records);
// check the returned results for any errors
for (int i=0; i< saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i+". Successfully created record - Id: " + saveResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = saveResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR creating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// updates the 5 newly created Accounts
private static void updateAccounts() {
System.out.println("Update a new test Accounts...");
Account[] records = new Account[1];
try {
QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
"CreatedDate DESC LIMIT 1");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account)queryResults.getRecords()[i];
System.out.println("Updating Id: " + a.getId() + " - Name: "+a.getName());
// modify the name of the Account
a.setName(a.getName()+" -- UPDATED");
records[i] = a;
}
}
// update the records in Salesforce.com
SaveResult[] saveResults = connection.update(records);
// check the returned results for any errors
for (int i=0; i< saveResults.length; i++) {
if (saveResults[i].isSuccess()) {
System.out.println(i+". Successfully updated record - Id: " + saveResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = saveResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR updating record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// delete the 5 newly created Account
private static void deleteAccounts() {
System.out.println("Deleting new test Accounts...");
String[] ids = new String[1];
try {
QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
"CreatedDate DESC LIMIT 1");
if (queryResults.getSize() > 0) {
for (int i=0;i<queryResults.getRecords().length;i++) {
// cast the SObject to a strongly-typed Account
Account a = (Account)queryResults.getRecords()[i];
// add the Account Id to the array to be deleted
ids[i] = a.getId();
System.out.println("Deleting Id: " + a.getId() + " - Name: "+a.getName());
}
}
// delete the records in Salesforce.com by passing an array of Ids
DeleteResult[] deleteResults = connection.delete(ids);
// check the results for any errors
for (int i=0; i< deleteResults.length; i++) {
if (deleteResults[i].isSuccess()) {
System.out.println(i+". Successfully deleted record - Id: " + deleteResults[i].getId() + "At " + LocalDateTime.now());
System.out.println("************Event Count************" + ++count);
} else {
Error[] errors = deleteResults[i].getErrors();
for (int j=0; j< errors.length; j++) {
System.out.println("ERROR deleting record: " + errors[j].getMessage());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Further updates got below mentioned error after which notification were
2017-03-09T19:30:28.346 ERROR [com.salesforce.emp.connector.EmpConnector] - connection failure, reconnecting
org.cometd.common.TransportException: {httpCode=503}
at org.cometd.client.transport.LongPollingTransport$2.onComplete(LongPollingTransport.java:278)
at org.eclipse.jetty.client.ResponseNotifier.notifyComplete(ResponseNotifier.java:193)
After this reconnect also happened and handshake also happened but error seems to be in resubscribe() EMP connector seems to be not able to resubscribe for some reason
Note I am using "resubscribe-on-disconnect" branch of EMP connetor
We have determined there was a bug on the server side in a 403 case. The Streaming API uses a session routing cookie and this cookie periodically expires. When it expires, the session is routed to another server, and this responds with a 403. In the current version, this 403 response does not include connect advice, and the client does not attempt to reconnect. This has been fixed and the fix is currently live. My understanding is that this should fix the reconnect problem exhibited by the clients.

how to over come System out memory exception in windows phone 8?

I'm Developing windows phone 8 application.
In my application i'm using listbox.I bind listbox value form Webservice. Webservice return json format data's.
The webservice return 40 to 50 records.I bind all the values into listbox.
Everthing work fine.Only on first time run.
For example:-
My project page structure.
1.welcomepage
2.Menu Page (it contain six buttons. click on any one particular button it's redirect to sub-menupage)
3.Sub-menupage(Six different page present)
In menu page Hotels button is present . if hotels button is clicked it's navigate to Hotels Page.
Now my problem is:-
First Time - welcomepage -> Menu Page -> HotelSubmenu [List of hotels is bind in listbox from webservice]
Now I goback to Menupage by click on hardwareback button.Now it's in Menu page
If i click again the same Hotels button
It show me the error
e.ExceptionObject {system.OutofMemoryException:Insufficient memory to continue the execution of the program.
[System.outofmemoryException]
Data {system.Collections.ListDictionaryInternal}
HelpLink null
Hresult -2147024882
Message "insufficient memory to continue the execution of the program"
My C# code for bind values in listbox
public void commonbind()
{
try
{
this.loadimg.Visibility = System.Windows.Visibility.Visible;
loadcheck();
string common_url = "http://xxxxxx.com/Service/bussinesscitynamesub.php?bcatid=" + businessid + "&cityname=" + cityname + "&bsubid=" + filterid;
WebClient common_wc = new WebClient();
common_wc.DownloadStringAsync(new Uri(common_url), UriKind.Relative);
common_wc.DownloadStringCompleted += common_wc_DownloadStringCompleted;
}
catch (Exception ex)
{
}
}
void common_wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
lbbusiness.Items.Clear();
var common_val = e.Result;
if (common_val != "null\n\n\n\n")
{
lbopen = 2;
var jsonconvertvalue = JsonConvert.DeserializeObject<List<common_bindclass>>(common_val);
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
this.loadimg.Visibility = System.Windows.Visibility.Collapsed;
loadcheck();
}
else
{
if (lbopen == 0)
{
MessageBoxResult resultmsg = MessageBox.Show("No Result present based on your current Location! " + System.Environment.NewLine + "Now showing result without Location based", "Sorry!", MessageBoxButton.OK);
if (resultmsg == MessageBoxResult.OK)
{
lbbusiness.Items.Clear();
cityname = "";
**commonbind();**
}
else
{
NavigationService.GoBack();
}
}
else if (lbopen == 1)
{
MessageBox.Show("No Result Present In this Categories");
LPfilter.Open();
}
else if (lbopen == 2)
{
MessageBox.Show("No Result Present In this City");
Lpcity.Open();
}
}
}
catch (Exception ex)
{
}
}
I try with following method for solve the memory exception
Try1:-
Clear the List box value before bind every time.
Try2:-
Create the new list every time
common_bindclass bind = new common_bindclass();
foreach (common_bindclass bind in jsonconvertvalue)
{
lbbusiness.Items.Add(bind);
}
I change the above code to
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
MY Output For single List
But my try's not help for me .
any one tell me how to solve it. or alternate way .
How to find in which line the error occur .[I try with break point but it's not help me]

Are File.isFile and File.isDirectory not working properly in Appcelerator Titanium?

I am working on an iPad app using appcelarator titanium and need to iterate over the content of a directory and determine the type of the contained items, whether it is a file or directory.
This is what I have so far:
dirFullPath = '/full/path/to/directory';
var dir = Titanium.Filesystem.getFile(dirFullPath);
var dirItems = dir.getDirectoryListing();
for ( var i=0; i<dir.length; i++ ) {
itemFullPath = dirFullPath
+ Titanium.Filesystem.getSeparator()
+ dir[i].toString();
testItem = Titanium.Filesystem.getFile(itemFullPath);
if ( testItem.exists() ) {
alert(itemFullPath + ' exists.'); // item exists, alert box appears
if ( testItem.isDirectory ) {
alert(itemFullPath + ' is a directory.'); // this code is never executed
}
else if ( testItem.isFile ) {
alert(itemFullPath + ' is a file.'); // this code is never executed
}
else {
alert(itemFullPath + ' is an unknown object.'); // this alert is always shown
}
}
}
I always get the alert box saying " is an unknown object.". It seems, that isFile and isDirectory are not working properly, or did I miss something? Does anybody else had the same problem?
Thanks for any advice!
The following should work:
var isDirectory = function(f){
return f.exists() && f.getDirectoryListing() != null;
}
var isFile = function(f){
return f.exists() && f.getDirectoryListing() == null;
}