I am using a ShareActionProvider to share a vcf file I created.
If I store the file in the external cache, I have absolutely no problems sharing the file, but if I store it in the internal cache, every app I try to share the vCard with says the file is corrupted or unsupported.
I read the file after creating it, and in both cases they are exactly the same.
This code works:
File dir = new File(getExternalCacheDir() + "/contact");
dir.mkdirs();
vcfFile = new File(dir, name.replace(' ', '+') + ".vcf");
However, if I use getCacheDir() instead, I get the problem.
Here's the code for creating the file:
FileWriter fw;
try {
fw = new FileWriter(vcfFile);
fw.write("BEGIN:VCARD\r\n");
fw.write("VERSION:2.1\r\n");
fw.write("N:" + codedName + "\r\n");
fw.write("FN:" + name + "\r\n");
fw.write("ORG:" + org + "\r\n");
fw.write("TITLE:" + position + "\r\n");
fw.write("TEL;PREF;WORK;VOICE;ENCODING=QUOTED-PRINTABLE:" + phone + "\r\n");
fw.write("TEL;PREF;WORK;FAX;ENCODING=QUOTED-PRINTABLE:" + fax + "\r\n");
fw.write("ADR;WORK;;ENCODING=QUOTED-PRINTABLE:" + codedAddr + "\r\n");
fw.write("EMAIL;INTERNET:" + email + "\r\n");
fw.write("URL;WORK:" + website + "\r\n");
fw.write("PHOTO;TYPE=JPEG;ENCODING=BASE64:" + codedImage + "\r\n");
fw.write("END:VCARD\r\n");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
And here's the code for the ShareActionProvider:
provider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
if (provider != null) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/vcard");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcfFile));
provider.setShareIntent(intent);
}
Any ideas of what I'm doing wrong?
Any ideas of what I'm doing wrong?
every app I try to share the vCard with says the file is corrupted or unsupported.
According with Using the Internal Storage
You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user)...
For this reason, it is advisable to use External Storage
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Code
```
public void sharePublicContact(View view){
String name = "Mickey Mouse";
String org = "Disney Corp.";
String note = "";
File dir = new File(getExternalCacheDir() + "/contact");
dir.mkdirs();
File vcfFile = new File(dir, name.replace(' ', '+') + ".vcf");
FileWriter fw;
try {
fw = new FileWriter(vcfFile);
fw.write("BEGIN:VCARD\r\n");
fw.write("VERSION:3.0\r\n");
fw.write("FN:" + name + "\r\n");
fw.write("ORG:" + org + "\r\n");
fw.write("NOTE:" + note + "\r\n");
fw.write("END:VCARD\r\n");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/vcard");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcfFile));
startActivity(sendIntent);
}
```
Related
Our team is creating a chatbot application this week. We finished coding the AIML files as well as the main codes in Android Studio. The only problem we have right now is the link between these two.
I've already placed the Ab.jar in the libs folder. Also, I've placed the AIML files in the assets folder.
Assets folder
The codes I think are relevant to linking are the following (from ChatActivity.class):
//checking SD card availability
boolean a = isSDCARDAvailable();
//receiving the assets from the app directory
AssetManager assets = getResources().getAssets();
File seedletDir = new File(Environment.getExternalStorageDirectory().toString() + "/bots/seedlet");
boolean b = seedletDir.mkdirs();
if (seedletDir.exists()) {
//Reading the file
try {
for (String dir : assets.list("seedlet")) {
File subdir = new File(seedletDir.getPath() + "/" + dir);
boolean subdir_check = subdir.mkdirs();
for (String file : assets.list("seedlet/" + dir)) {
File f = new File(seedletDir.getPath() + "/" + dir + "/" + file);
if (f.exists()) {
continue;
}
InputStream in = null;
OutputStream out = null;
in = assets.open("seedlet/" + dir + "/" + file);
out = new FileOutputStream(seedletDir.getPath() + "/" + dir + "/" + file);
//copy file from assets to the mobile's SD card or any secondary memory
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
//get the working directory
MagicStrings.root_path = Environment.getExternalStorageDirectory().toString() + "/seedlet";
System.out.println("Working Directory = " + MagicStrings.root_path);
AIMLProcessor.extension = new PCAIMLProcessorExtension();
//Assign the AIML files to bot for processing
bot = new Bot("seedlet", MagicStrings.root_path, "chat");
chat = new Chat(bot);
String[] args = null;
mainFunction(args);
}
When I ran the application and started to chat with the bot, the bot incorrectly replies "I have no answer for that"
Chat
How can I solve this problem?
Add these two permissions to manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
I create a txt-File with FileWriter:
try
{
fw = new FileWriter( filePath );
fw.write("Name: " + title);
fw.write("Publisher: " + publisher + System.getProperty("line.separator"));
fw.write("Author: " + author + System.getProperty("line.separator"));
fw.write("Book Version: " + version + System.getProperty("line.separator"));
fw.write("URL: " + url + System.getProperty("line.separator"));
fw.write("ThumbMD5: " + thumbMD5 + System.getProperty("line.separator"));
fw.write("FileMD5: " + fileMD5 + System.getProperty("line.separator"));
fw.write("Book Area Code: " + areaCode + System.getProperty("line.separator"));
fw.write("Type: " + type + System.getProperty("line.separator"));
fw.flush();
fw.close();
}
catch ( IOException e ) {
Log.e(TAG, "saveTxt: Couldn't create File: " + e.getMessage() );
}
finally {
if ( fw != null )
try { fw.close(); } catch ( IOException e ) { e.printStackTrace(); }
}
That file gets created correctly, with correct content. I can open the file when I connect my Smartphone with a windows PC.
But when I try
File dirTxt = new File(Helper.getExternalStorageDirectory() + Helper.getFileCache());
File[] txts = dirTxt.listFiles();
for (File txt : txts) {
Log.e(TAG, txt.getName());
}
all files in that directory are found, but my new txt file.
What's up with that? All help is appreciated!
Workaround: instead of looking for the new File and coping it, I just used
File f = new File(pathToNewFile);
Then i copied f.
I have created a simple application to take some user data and write it to a text file which gets saved on the external storage of my device. However, I am unable to access those files using my computer until after I have rebooted my device. Can anyone tell me why this is and if there is something I can do to fix it?
Here is the code I use to write data.
private void commitToFile(String worldOrApp, String xPos, String yPos, String orient) {
Intent intent = getIntent();
String filename = intent.getStringExtra(MainActivity.FILENAME) + ".txt";
final String position = worldOrApp + " - x: " + xPos + "; y: " + yPos + "; alpha: " + orient + "\r\n";
File myPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFolder = new File(myPath.getAbsolutePath()+"/test_folder");
if (!myFolder.exists()) {
myFolder.mkdirs();
}
File myFile = new File(myFolder, filename);
try {
FileOutputStream fileOutputStream = new FileOutputStream(myFile, true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.write(position);
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks to #CommonsWare for the direction. I found the following code at Android saving file to external storage
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
which I placed directly underneath the exception catch in my code, and updated file to myFile, which is the relevant File for my commitToFile method.
SOLVED:
ok so I am basically stupid. I couldn't open the file because I forgot to install winrar or 7zip since this pc is newly formatted... Everything works fine. Sorry to waste anyone's time.
In my app I programmatically generate a .zip file from photos and .csv files in a directory.
It creates the zip and then sends the email with the attachment without a hickup. The problem however is that on my pc I can't extract the .zip file because it says it's invalid, but on my device using "WinZip" I can check my .zip file and it has everything it is suppose to have. This is confusing me.
Here is my code:
Here I check for which checkboxes have been checked then do the zipping
for(int i = 0; i < cbStates.size(); ++i)
{
if(cbStates.get(i))
{
String zipFile = Environment.getExternalStorageDirectory() + "/ArcFlash/" + listItems.get(i) + ".zip";//ex: /storage/sdcard0/ArcFlash/study12.zip
String srcDir = Environment.getExternalStorageDirectory() + "/ArcFlash/" + listItems.get(i);
try
{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File srcFile = new File(srcDir);
Log.i("customException", "going to compress");
addDirToArchive(zos, srcFile);
// close the ZipOutputStream
zos.close();
}
catch (IOException ioe)
{
System.out.println("Error creating zip file: " + ioe);
}
//Send the email
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"jbasson#powercoreeng.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Test Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "From My App");
String folderPath = Environment.getExternalStorageDirectory() + "/ArcFlash/" + listItems.get(i) + ".zip";
//Uri u = Uri.fromFile(folderPath);
//Log.i("customException", "uri path: " + u.getPath());
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + folderPath));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Toast.makeText(context,"Case \"" + studyName + "\" has been sent", Toast.LENGTH_LONG).show();
//adapter.setElement(i, adapter.getStudy(i) + "(sent)");
}
}
and here is the zip function:
private static void addDirToArchive(ZipOutputStream zos, File srcFile)
{
File[] files = srcFile.listFiles();
Log.i("customException", "Adding directory: " + srcFile.getName());
for (int i = 0; i < files.length; i++)
{
// if the file is directory, use recursion
if (files[i].isDirectory())
{
addDirToArchive(zos, files[i]);
continue;
}
try
{
System.out.println("tAdding file: " + files[i].getName());
// create byte buffer
byte[] buffer = new byte[2048];//1024
FileInputStream fis = new FileInputStream(files[i]);
zos.putNextEntry(new ZipEntry(files[i].getAbsolutePath() + "/" + files[i].getName()));//files[i].getName()
int length;
while ((length = fis.read(buffer)) > 0)
{
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
catch (Exception ex)
{
Log.i("customException", "error zipping: " + ex.getMessage());
}
}
}
ok so I am basically stupid. I couldn't open the file because I forgot to install winrar or 7zip since this pc is newly formatted...
I am trying to write and then load a KML file using Google Maps via an Intent. I have tried both internal and external storage for the KML file - it seems to be writing correctly, but I keep getting the following error Toast in Google Maps:
No results found for:file:///data/data/[my app package path]/kml_to_view.kml
Writing To File
File dir = context.getFilesDir();
//File dir = Environment.getExternalStorageDirectory();
Log.d(TAG, "Writing to dir: " + dir);
File kmlFile = new File(dir, KML_FILE_NAME);
FileOutputStream fos;
try
{
kmlFile.createNewFile();
fos = context.openFileOutput(KML_FILE_NAME, Context.MODE_WORLD_READABLE);
//fos = new FileOutputStream(kmlFile);
fos.write(kmlData.getBytes());
fos.close();
isKMLPrepared = true;
Toast.makeText(context, "file write successful", Toast.LENGTH_LONG);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG);
e.printStackTrace();
}
As you can see I have the pieces necessary to write either to internal storage or external and I have tried both.
Sending KML To Maps
File dir = context.getFilesDir();
Log.d(TAG, "Local file path: " + dir);
readInternalStoragePrivate(KML_FILE_NAME);
mapsIntent = new Intent(Intent.ACTION_VIEW);//Uri.parse("http://maps.google.com/maps"));
//String uri = "geo:0,0?q=file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + KML_FILE_NAME;
String uri = "geo:0,0?q=file://" + context.getFilesDir().getAbsolutePath() + "/" + KML_FILE_NAME;
Log.d(TAG, "URI: " + uri);
mapsIntent.setData(Uri.parse(uri));
Again I have tried reading both internal and external locations when sending a path to the Maps app.
Any idea what I need to do to get the Maps app to read and process a locally stored KML file? I have read a number of other posts, but I have yet to find a solution to my problem.