I'm am getting a NULL pointer message on getfilesdir().  I'm sure it has something to do with my implementation but I'm not really sure what it is.  Ad I'm extremely new to android development.       public class MainActivity extends AppCompatActivity {  String appFileDirectory = getFilesDir().getPath(); String executableFilePath = appFileDirectory + "/iperf3";  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     copyFile("iperf3"); }  private static final String TAG = "MainActivity";  //This function is used to copy the iperf3 executable to a directory which execute permissions for this application, and then gives it execute permissions. //It runs on every initiation of an iperf3 test, but copies the file only if it's needed. public void copyFile(String filename) {     AssetManager assetManager = getAssets();     try {         InputStream in = assetManager.open(filename);         File outFile = new File(appFileDirectory, filename);         OutputStream out = new FileOutputStream(outFile);          Log.d(TAG, "Attempting to copy this file: " + filename); // + " to: " +       assetCopyDestination);          int read;         byte[] buffer = new byte[4096];         while ((read = in.read(buffer)) &gt; 0) {             out.write(buffer, 0, read);         }         out.flush();         out.close();         in.close();          //After the copy operation is finished we give execute permissions to iPerf3         File execFile = new File(executableFilePath);         execFile.setExecutable(true);      } catch (IOException e) {         Log.e(TAG, "Failed to copy asset file: " + filename, e);     } }  public static void executeIperf3() {  }
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
14419
My below test fails because of Run Failures: TestRangehoodObjectionSheet.RangehoodObjectionSheetTest Methods defined as TestMethod do not support getContent call. I added the Blob thinking it might resolve but it doesn't work. What could be the problem here? Have I used the Blob correctly?  @isTest public with sharing class TestRangehoodObjectionSheet {      static testMethod void RangehoodObjectionSheetTest() {             String Build                = NBATRecords.getIdFromDeveloperName('Plan_Reviews__c','Building_Plan_Review');             Account a = new Account(Name = 'Test1' ,Type = 'Lead Acct',BillingState = 'CA',Industry = 'Business Services');             insert a;              Establishment_Record__c er = new Establishment_Record__c(Account__c=a.Id ,Project_Name__c = 'TestPreet',PremiseStreet__c='Manhattan ave',PremiseBorough__c='Manhattan',PremiseState__c='NY',PremisePostalCode__c='11102',Referral_Source__c='311',Data_Source__c='CAMIS',Phase__c='Initiate',Business_Status__c='Open' );             insert er;              Application__c ap = new Application__c(Establishment_Record__c=er.Id,Job_Number__c='222222222');             insert ap;              Plan_Reviews__c pr = new Plan_Reviews__c(Application__c =ap.Id ,DOB_Job_Number__c='222222222',RecordTypeId =Build,Objections__c='Pipe size not indicated');             insert pr;             PageReference pageRef = Page.RangehoodObjectionSheet;              Test.setCurrentPage(pageRef);               Blob content = Test.isRunningTest() ? Blob.valueOf('UNIT.TEST') : pageRef.getContent();              Plan_Reviews__c              p   = new Plan_Reviews__c(id=pr.Id);                ApexPages.StandardController sc  = new ApexPages.standardController(p);             System.assertNotEquals(sc,null);             RangehoodObjectionExtention    ext = new RangehoodObjectionExtention(sc);              ext.Savecopy();       } }   Actual class for the test:  public with sharing class RangehoodObjectionExtention { private final ApexPages.StandardController controller; private final Id                           planreviewID; public String imageURL{get;set;} public List&lt;String&gt; objlist {get;set;}  public string currentdate {get; set;}    public RangehoodObjectionExtention (ApexPages.StandardController stdController) {         controller   = stdController;         planreviewID = (Id)controller.getRecord().get('Id');         Date dt = Date.today();         currentdate = dt.format();         list&lt;Plan_Reviews__c&gt; prlist = [select FDNY_Objections__c from Plan_Reviews__c where id = :planreviewID limit 1];         string obj;         for(Plan_Reviews__c pr: prlist){            obj = pr.FDNY_Objections__c;             }         if(obj!=null){            list&lt;string&gt; objections = obj.split(';');             integer i =1;            objlist = new list&lt;string&gt;();            for(string o : objections){               objlist.add(i++ +'. '+o);            }         }         imageURL='/servlet/servlet.FileDownload?file=';         List&lt; document &gt; documentList=[select name from document where Name='RangehoodObjectionLogo'];         if(documentList.size()&gt;0)         {            imageURL=imageURL+documentList[0].id;         }       }          public PageReference Savecopy(){       PageReference p = Page.RangehoodObjectionSheet;       blob b = ApexPages.currentPage().getContentAsPDF ();       Attachment a = new Attachment();       a.body = b;       a.name = 'Rangehood Objection sheet Issued '+currentdate+'.pdf';       a.parentid = planreviewID;        insert a;        PageReference pref = new PageReference('/'+planreviewID);       return pref;    } }
2516
I am trying to get a FileInputStream object on an image that the user selects from the picture gallery. This is the android URI returned by android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI  content://media/external/images/media/3   When I try to construct a java URI object from this object, I get an IllegalArgumentException with the exception description Expected file scheme in URI: content://media/external/images/media/3 whereas the android URI shows the scheme as content  Update: Never found a solution for the original question. But if you want the byte stream of an image in the pictures gallery, this piece of code will do that.  Bitmap bitmap = Media.getBitmap(getContentResolver(), imageUri); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes); ByteArrayInputStream fileInputStream = new ByteArrayInputStream(bytes.toByteArray());
101639
How can I copy the path to a folder or a file? The Info Dialog doesn't allow me to copy the information that stands there ...    Is there an easy way to do this?
30205
I want to check for empty arrays. Google gave me varied solutions but nothing worked. Maybe I am not applying them correctly.  Function GetBoiler(ByVal sFile As String) As String 'Email Signature     Dim fso As Object     Dim ts As Object     Set fso = CreateObject("Scripting.FileSystemObject")     Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)     GetBoiler = ts.ReadAll     ts.Close End Function  Dim FileNamesList As Variant, i As Integer ' activate the desired startfolder for the filesearch FileNamesList = CreateFileList("*.*", False) ' Returns File names ' performs the filesearch, includes any subfolders ' present the result ' If there are Signatures then populate SigString Range("A:A").ClearContents For i = 1 To UBound(FileNamesList)     Cells(i + 1, 1).Formula = FileNamesList(i) Next i  SigString = FileNamesList(3)  If Dir(SigString) &lt;&gt; "" Then     Signature = GetBoiler(SigString) Else     Signature = "" End If   Here if FileNamesList array is empty, GetBoiler(SigString) should not get called at all. When FileNamesList array is empty, SigString is also empty and this calls GetBoiler() function with empty string. I get an error at line   Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)   since sFile is empty. Any way to avoid that?
28359
I'm trying to build an Android test application integrated to the SalesForce platform. I have downloaded the SDK from , and imported it to my workspace. Everything works fine except my test app, even the  they have provided along with the SDK work without problem. As a first step, what I tried was to clone the basic features (just login as of now) from the RestExplorer app. The following are my important files.  public class Home extends Activity {  private PasscodeManager passcodeManager; private RestClient client; private TokenRevocationReceiver tokenRevocationReceiver;  RestClient getClient() {     return client; }  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);      passcodeManager = SalesforceSDKManager.getInstance().getPasscodeManager();     tokenRevocationReceiver = new TokenRevocationReceiver(this);     setContentView(R.layout.activity_home);  }  @Override  public void onResume() {     super.onResume();     registerReceiver(tokenRevocationReceiver, new IntentFilter(ClientManager.ACCESS_TOKEN_REVOKE_INTENT));           if (passcodeManager.onResume(this)) {   // Bring up passcode screen if needed         String accountType = SalesforceSDKManager.getInstance().getAccountType();   // Login options         new ClientManager(this, accountType, SalesforceSDKManager.getInstance().getLoginOptions(), SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked()).getRestClient(this, new RestClientCallback() {    // Get a rest client             @Override             public void authenticatedRestClient(RestClient client) {                 if (client == null) {                     SalesforceSDKManager.getInstance().logout(Home.this);                     return;                 }                 Home.this.client = client;                           }         });     } }  @Override protected void onPause() {     passcodeManager.onPause(this);     unregisterReceiver(tokenRevocationReceiver);     super.onPause(); } }   I have added the permissions as required  &lt;permission android:name="com.salesforce.samples.restexplorer.C2D_MESSAGE"     android:protectionLevel="signature" /&gt;  &lt;uses-permission android:name="com.salesforce.samples.restexplorer.C2D_MESSAGE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt; &lt;uses-permission android:name="android.permission.GET_ACCOUNTS"/&gt; &lt;uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/&gt; &lt;uses-permission android:name="android.permission.ACCOUNT_MANAGER"/&gt;   And extended the application object to give a call to init();  public class MyApp extends Application { @Override public void onCreate() {     super.onCreate();     SalesforceSDKManager.initNative(getApplicationContext(), new KeyImpl(), Home.class); } }   Now, I'm getting the error in my Android debug log. The log as I see is attached below. It keep the activity restarting till I forcefully kill the application.  11-08 15:56:23.883: I/ClientManager:getRestClient(9334): No account of type com.salesforce.androisdk found 11-08 15:56:23.898: W/AccMgrCallback:run(9334): android.accounts.AuthenticatorException: bind failure 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager.convertErrorToException(AccountManager.java:1726) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager.access$400(AccountManager.java:144) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager$AmsTask$Response.onError(AccountManager.java:1572) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.IAccountManagerResponse$Stub.onTransact(IAccountManagerResponse.java:69) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.os.Binder.execTransact(Binder.java:388) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at dalvik.system.NativeStart.run(Native Method)   Do anyone have any idea about this isse? It is such a basic app, I was not expecting anything unusual. Did I do anything wrong in my app?
23361
I have the following code in Visual Studio 2005.      Dim OutFile As System.IO.StreamWriter     Try         OutFile = New System.IO.StreamWriter(Filename)        // Do stuff with OutFile     Catch Ex As Exception        // Handle Exception     Finally        If OutFile IsNot Nothing Then OutFile.Close()     End Try   But VS2005 brings up the warning for the line "If OutFile IsNot.." that      Variable 'OutFile' is used before it has been assigned a value. A null reference exception could result at runtime.   Is there some way of removing this warning by subtly altering the code or is there just a better way of doing what I'm trying to do?  Thanks  Rob
65020
I am able to backup my app's data from the root/data/data/you.package.name directory by just moving it to SD card manually. however, when i reverse the process,                                                                                                               AKA paste the data back to simulate a restore, the app just force closes, i have tried it with a bunch of apps and noticed the same reaction. Where am i wrong?
61126
I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets  LoginPageObjec.java  public class LoginPageObjects {      @FindBy(xpath=".//*[@id='userName']")     private WebElement email;      @FindBy(xpath=".//*[@id='password']")     private WebElement password;      @FindBy(xpath=".//*[@id='loginFormSubmit']")     private WebElement loginBtn;      public void EnterUserName(String userName)     {         email.sendKeys(userName);     }      public void EnterPassword(String pass)     {         password.sendKeys(pass);     }      public void clickLogin()     {         loginBtn.click();     }   }   LoginTC.java  public class LoginTC extends BasePage{     private WebDriver driver;      @Test     public void login()     {         LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);         loginPage.EnterUserName("test.hr@domin.com.pk");         loginPage.EnterPassword("test");         loginPage.clickLogin();     } public void login1()         {             LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);             loginPage.EnterUserName("test.hr@domin.com.pk");             loginPage.EnterPassword("test");             loginPage.clickLogin();         }  }   BasePage.java  public class BasePage {     private WebDriver driver;      @BeforeMethod       public void initializeBrowser() {      driver=new FirefoxDriver();      driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");      driver.manage().window().maximize();      }     @AfterMethod     public void closeBrowser()     {         driver.close();     }  }   I've extended BasePage class to utilize the (initialBrowser &amp; closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser &amp; closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser &amp; closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception
49090
I wish to recursively go through the folders of a directory structure and copy any .jpg I find into another directory.  I think I had the wrong idea with:  cp -R photos/*.jpg /cpjpg   How can I do this from the command line in Ubuntu?
27910
I'm using .NET 3.5, trying to recursively delete a directory using:  Directory.Delete(myPath, true);   My understanding is that this should throw if files are in use or there is a permissions problem, but otherwise it should delete the directory and all of its contents.  However, I occasionally get this:  System.IO.IOException: The directory is not empty.     at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)     at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)     at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)     ...   I'm not surprised that the method sometimes throws, but I'm surprised to get this particular message when recursive is true.  (I know the directory is not empty.)  Is there a reason I'd see this instead of AccessViolationException?
67508
I would like to create a "/dev/null" directory (or a "blackhole" directory) such that any files written to it are not really written, but just disappear.   I have an application that writes out large temporary files to a directory. I have no control over the name of the files and I don't really care about the content of these files. I could write a script that periodically clobbers these files, but the files are written out very quickly and fill my disk. I'm looking for something cleverer. I want the application to "think" that it is writing out these files, when in fact, the writes are just being discarded at the other end.  Also see  old related thread.
112290
This code throws a NullReferenceException when it calls ExecuteScalar:  selectedPassengerID = 0;  //SqlCommand command = GenericDataAccess.CreateCommand();   // 2nd test string connectionString = ""; SqlConnection conn;  connectionString = ConfigurationManager.     ConnectionStrings["ConnST-MHM"].ConnectionString; conn = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(); command.CommandType = CommandType.StoredProcedure ; command.Connection = conn; command.CommandText = "SearchForPassenger";  SqlParameter param;  param = command.CreateParameter(); param.ParameterName = "@name"; param.Value = pName; // Session[""]; param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@flightDate"; param.Value = date;  param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@ticketNo"; param.Value = ticketNumber;  param.DbType = DbType.Int32; command.Parameters.Add(param);  int item;  command.Connection.Open(); item = (int)command.ExecuteScalar();
2343
I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.  Is there a better/different way to read a file into a string in Java?  private String readFile(String file) throws IOException {     BufferedReader reader = new BufferedReader(new FileReader (file));     String         line = null;     StringBuilder  stringBuilder = new StringBuilder();     String         ls = System.getProperty("line.separator");      try {         while((line = reader.readLine()) != null) {             stringBuilder.append(line);             stringBuilder.append(ls);         }          return stringBuilder.toString();     } finally {         reader.close();     } }
30140
I want to get a list of files in a directory, but I want to sort it such that the oldest files are first.  My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.  Edit: My current solution, as suggested, is to use an anonymous Comparator:  File[] files = directory.listFiles();  Arrays.sort(files, new Comparator&lt;File&gt;(){     public int compare(File f1, File f2)     {         return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());     } });
50027
So, yesterday my phone took a serious tumble.  It is now essentially useless, as the screen either fails to turn on, or when it does, there is nothing useful to see (just lines of primary colors, mostly).  I believe (from the fact that it still chirps at me when emails come in, etc), that the phone is still functional, otherwise.  I would like to perform a full system dump, so that I can get off any files from the phone (a TMobile SGS2 (hercules) running slimrom 4.3 build 1).  The sdcard probably isn't important, as I can just pull it, but the phone's own internal storage I should like to get a copy of.  When I plug the phone into a usb port, it 'mounts' the usb via MTP, and I can see all the files.  Unfortunately, when I do a select all | copy | paste operation, the paste op dies before transferring all files.  I've tried a couple other ADB shell operations, in hope of flipping regular USB mounting on, but nothing has worked.  Any ideas how I can get a full dump of my poor phone's contents?  Edit  Currently running a adb pull /sdcard/ ... Its copying files presently, but its too early to tell if its going to get evertying I'm expecting.  Edit #2  looks like its going to work...its taking a rather long time, but it appears to be grabbing everything I was expecting it to.
57492
I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command?  Instead of this:  string filePath = @"C:\somepath\file.txt";   I want to do this:  string filePath = @helper.getFilePath(); //getFilePath returns a string   This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something?