Search code examples
javaandroidandroid-studioandroid-4.4-kitkat

How to create a .txt file on Android KitKat and send it with an email intent


So i've been trying for a day now to create a .txt file on the SD card only to find out it wasnt my code that was wrong but KitKat no longer allows devs to store files on the external SD card; is there away around this such as a temporary .txt file, or some new code to create a file then send it? this is my current code that doesnt work

 String DataIn = PhoneNumber + "," + dataLong + "," + dataLat;
        try
        {
        File storageDirectory = new File ("/sdcard/LocationData.txt");
            storageDirectory.createNewFile();
            FileOutputStream fout = new FileOutputStream(storageDirectory);
            OutputStreamWriter myoutwriter = new OutputStreamWriter(fout);
            myoutwriter.append(DataIn);
            myoutwriter.close();Toast.makeText(getBaseContext(),"Saved", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        Intent emailintent = new Intent(Intent.ACTION_SEND);
        emailintent.setType("text/plain");
        emailintent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
        emailintent.putExtra(Intent.EXTRA_SUBJECT, "Data");
        emailintent.putExtra(Intent.EXTRA_TEXT, "Hello World!");
        File root = Environment.getRootDirectory();
        String DataAttachment = "/sdcard/LocationData.txt";
        File filer = new File(root, DataAttachment);
        if (!filer.exists() || filer.canRead())
        {
            return;
        }
        Uri uri = Uri.fromFile(filer);
        emailintent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(emailintent, "Choose an Email provider"));

Solution

  •         File dirs[] = ContextCompat.getExternalFilesDirs(getApplicationContext(),null);
    
            String Info = "getExternalFilesDirs()\ndirs.length: " + dirs.length;
            int nr = -1;            
            while ( ++nr < dirs.length )
                Info += "\n"+  dirs[nr].getAbsolutePath();
    
            Toast.makeText(this, Info, Toast.LENGTH_LONG).show();
    

    You need /Project/libs/android-support-v4.jar file.