user1878350
user1878350

Reputation: 11

Android Intent to save email attachment

I am receiving emails with a custom file extension (actually zip files).

When I try to open the attachment from e.g. K9 email app and save it to my app's cache dir, the zip file gets corrupted e.g. it doesn't open with a file manager

private void importData(Uri data) {
    Log.d(TAG, data.toString());
      final String scheme = data.getScheme();

      if(ContentResolver.SCHEME_CONTENT.equals(scheme)) {
        try {
          ContentResolver cr = getApplicationContext().getContentResolver();
          InputStream is = cr.openInputStream(data);
          if(is == null) return;

          StringBuffer buf = new StringBuffer();            
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
          String str;
          if (is!=null) {                           
              while ((str = reader.readLine()) != null) {   
                  buf.append(str);
              }             
          }     
          is.close();

          File outputDir = getApplicationContext().getCacheDir(); // context being the Activity pointer
          Log.d(TAG, "outputDir: " + outputDir.getAbsolutePath());

          String fileName = "test_seed.zip";
          Log.d(TAG, "fileName: " + fileName);

          File zipFile = new File(outputDir, fileName);
          FileWriter writer = new FileWriter(zipFile);
          try {
              writer.append(buf.toString());
              writer.flush();
              writer.close();
          } catch (IOException e) {
              Log.d(TAG, "Can't write to " + fileName, e);
          } finally {
              Toast.makeText(getApplicationContext(), "Zip key file saved to SDCard.", Toast.LENGTH_LONG).show();
          }
          // perform your data import here…

        } catch(Exception e) {
            Log.d("Import", e.getMessage(), e);
        }
    }
}

The Uri string is

content://com.fsck.k9.attachmentprovider/668da879-32c8-4143-a3ec-e135d901c443/31/VIEW

This is my intent filter:

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<category android:name="android.intent.category.DEFAULT" />
<data
    android:mimeType="application/*"
    android:host="*" 
    android:pathPattern=".*\\.odks" />
</intent-filter>

Upvotes: 0

Views: 437

Answers (1)

Theodore Sternberg
Theodore Sternberg

Reputation: 161

Your BufferedReader.readLine() is the problem; it assumes your file is a nice human-readable text file with \n indicating ends of lines. Zip files aren't like that. So instead, call the read() and write() methods of your InputStream and your FileOutputStream.

Something along these lines:

byte[] buffer = new byte[1024];
int n = 0;
while ((n = infile.read(buffer)) != -1) {
    outfile.write(buffer, 0, n);
}

Upvotes: 1

Related Questions