Display .mht file on android - android

How to display .mht(MHTML) file on android webview. I tried to open the .mht file on default android browser but that didn't open but i am able to open same on opera mobile browser. So i tried with MHTUnpack java library. I didn't succeed in that.
Here's a link!
Please if anybody has used this MHTUnpack let me how can i use that in android. And also let me know if there is any other library.
Thanks

Found this unknown google project which appears to be working.
This utility decodes the mhtml file and save it on given path(internal or external). After saving it returns the html file path which could be loaded into webview.
Try it.

After overcoming frustration about WebView.saveWebArchive() format change in Android 4.4, I tried the "unknown google project" Chitranshu Asthana mentioned in his answer, but code provided there is slow (~10s for 1MB *.mht file with a dozen of pictures) and doesn't handle attached file names correctly.
MHT Unpack library combined with Java Mail for Android (not the one provided by Oracle) worked perfectly for me.
EDIT: Fixed the link to MHT Unpack library. Also, here's usage example:
// contentPath - path to input .mht file
public static String unpackMht(String contentPath) throws IOException {
// dstPath - path where file will be unpacked
String dstPath = openTempDir(null) + File.separator;
String indexFileName = dstPath + new File(contentPath).getName();
try {
Collection<Attachment> attachments = MHTUnpack.unpack(new File(contentPath));
for (Attachment attachment : attachments) {
String filename = attachment.getFileName();
String path = filename == null ? indexFileName : dstPath + filename;
File newFile = new File(path);
if (newFile.exists()) {
newFile.delete();
}
attachment.saveFile(path);
}
return indexFileName;
} catch (MessagingException e) {
throw new IOException(e);
}
}

Related

Why does the Android version contain robot artifacts?

For a robot simulation I use a csv file with data. I read data as follows:
string dbPath = ""; string realPath; // Android string oriPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Data.csv");
// Android only use WWW to read file
WWW reader = new WWW(oriPath);
while (!reader.isDone) { }
realPath = Application.persistentDataPath + "/db";
System.IO.File.WriteAllBytes(realPath, reader.bytes);
dbPath = realPath;
using (StreamReader sr = new StreamReader(dbPath))
{...}
In the Unity Editor version the simulation works as expected but on Android the arm ofthe robot moves in a strange way as you can see in the videos. I compared the two db files (on the Windows and Android paths) and the content is identical. What could be the reason of the strange movemenz?
Editor https://streamable.com/7z4qob Android https://streamable.com/rv4nm2
Thank you!
To get StreamingAssets WWW you need to add prefix jar:file:///
To get Application.persistentDataPath you need to add prefix file:///
If files are identical then problem is not in getFile code, why did you provide it?

Kotlin: How to create/append file (and share)

I have a list of arrays of data in my app that I would now like to write to a file (csv) and use a 3rd party app (such as email) to share this csv file. I have had no luck finding any helpful resources for creating, finding the file path for, and appending to a file in Kotlin. Does anyone have experience with this or have examples to point to? Just to get started I'm trying to write the header and close the file so I can see that it is correctly writing.
This is what I have for now:
val HEADER = "ID, time, PSI1, PSI2, PSI3, speed1, speed2, temp1, temp2"
val filename = "export.csv"
var fileOutStream : FileOutputStream = openFileOutput(filename,Context.MODE_PRIVATE)
try {
fileOutStream.write(HEADER.toByteArray())
fileOutStream.close()
}catch(e: Exception){
Log.i("TAG", e.toString())
}
It doesn't throw the exception, but I cannot find the file in the file system. I'm using a physical tablet for testing/debug. I've checked the com.... folder for my app.
I cannot find the file in the file system
Use Android Studio's Device File Explorer and look in /data/data/.../files/, where ... is your application ID.
Also, you can write your code a bit more concisely as:
try {
PrintWriter(openFileOutput(filename,Context.MODE_PRIVATE)).use {
it.println(HEADER)
}
} catch(e: Exception) {
Log.e("TAG", e.toString())
}
use() will automatically close the PrintWriter, and PrintWriter gives you a more natural API for writing out text.
It appears there are many ways to create a file and append to it, depending on the minimum API version you are developing for. I am using minimum Android API 22. The code to create/append a file is below:
val HEADER = "DATE,NAME,AMOUNT_DUE,AMOUNT_PAID"
var filename = "export.csv"
var path = getExternalFilesDir(null) //get file directory for this package
//(Android/data/.../files | ... is your app package)
//create fileOut object
var fileOut = File(path, filename)
//delete any file object with path and filename that already exists
fileOut.delete()
//create a new file
fileOut.createNewFile()
//append the header and a newline
fileOut.appendText(HEADER)
fileOut.appendText("\n")
/*
write other data to file
*/
openFileOutput() creates a private file, likely inside of app storage. These files are not browsable by default. If you want to create a file that can be browsed to, you'll need the WRITE_EXTERNAL_STORAGE permission, and will want to create files into a directory such as is provided by getExternalFilesDir()

Android Doesn't Recognize Image Downloaded by Flutter App

Android Flutter app downloads an image from a server on another Android phone. After downloading, the file is unable to be opened or viewed by the phones gallery or file explorer. However, when examined by a hex editor, the downloaded file and the original file are exact copies, and when imported to windows, the "corrupt" downloaded file is view able by the Image Viewer. The only difference I could find between the files was the metadata examined by Windows. What could be the cause of this?
Original File on Android Server:
Downloaded File On Android Client:
Here's the code I'm using to create the file from a Uint8list:
Future<File> downloadFileAndroid(Uint8List fileBytes, String fileName) async{
var dir = await getExternalStorageDirectory();
File photoFile;
var photoDirectory = await Directory(dir.path + "/Downloader").create(recursive: true);
photoFile = await new File(photoDirectory.path + "/" + fileName).create();
if(await photoFile.exists()){
await photoFile.writeAsBytes(fileBytes);// also tried flush: true
print("Created file and it exists");
} else {
print("Error: tried to create file but it doesnt exist");
}
}
I faced this problem when downloading an image from the internet and setting a png extention to it. Using an extention on the file name usually causes this error. Consider using https://pub.dev/packages/image_downloader to download the image using the default function in the example code. With the default option, the extension is not determined by the coder but instead by itself.

File path for Sparsitiy Sparksee file/database

I am using Sparksee database, which requires to provide a path for the database file. Comparing it with sqlite, I simply wrote the filename without any path.
try
{ gdb = sparksee.create("filepath", "alias"); }
catch (FileNotFoundException e) {
{ e.printStackTrace(); }
It gives an FileNotFoundException on running.
java.io.FileNotFoundException: File cannot be created
The documentation/API does not specify any special path requirements, it simply says to provide a path for the file. I tried using the default database path :
/data/data/com.example.sparksee/databases/file
But it does not work as well.
What path should be provided in such a scenario?
I used this code to get a file path :
in Activity :
String path = this.getFileDirs().getPath();
in DatabaseCode :
gdb = sparksee.create(path + "/filepath", "alias");
The file was created in the /data/data/package/file/ folder. The application ran perfectly well without any hiccups.

How to add a file to an Android project, deploy it to the device, and then open it?

I have an Android (2.2) project in Eclipse (Helios). I want to add an MP3 file to the project so that the MP3 file is deployed to the device along with the application.
I then would like to open the file as a File object, which means I'd need to know the full path (?) to the file on the device, but I don't know how paths are specified in Android.
Apparently there is a bug in Froyo that prevents WAV playback.
Audio files should be placed in the "res/raw" directory of your project. Then use the id to play it (or attempt to play it)
MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();
Info: http://developer.android.com/guide/topics/media/index.html
Example (mp3): http://www.helloandroid.com/tutorials/musicdroid-audio-player-part-i
Ok, I saw this on the source of another projet, so I didn't really come up with it, but it works.
To add any file to a project, and later be able to use it, you need to put the file (binary, xml, or whatever) on the assets folder of your project.
In this example I will just copy the asset to the filesystem, so I can later access it as any other user file. You can access the assets directly too, take a look at Resources on the documentation.
public void copyfile(String fileName)
{
if (!new File(fileName).exists()){
try
{
InputStream localInputStream = getAssets().open(fileName);
FileOutputStream localFileOutputStream = getBaseContext().openFileOutput(fileName, MODE_PRIVATE);
byte[] arrayOfByte = new byte[1024];
int offset;
while ((offset = localInputStream.read(arrayOfByte))>0)
{
localFileOutputStream.write(arrayOfByte, 0, offset);
}
localFileOutputStream.close();
localInputStream.close();
// The next 3 lines are because I'm copying a binary that I plan
// to execute, so I need it to have execute permission.
StringBuilder command = new StringBuilder("chmod 700 ");
command.append(basedir + "/" + paramString);
Runtime.getRuntime().exec(command.toString());
Log.d(TAG, "File " + paramString + " copied successfully.");
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
return;
}
}
else
Log.d(TAG, "No need to copy file " + paramString);
}
I believe there is probably a better way to copy the file, but this one works, and does not slow down my app even if it's called from onCreate (all files I copy are below 100kb though, so for bigger files, you probably want a separate thread)
Here is how to get the path to your files:
String path = getBaseContext().getFilesDir().getAbsolutePath();
If you want to write the file to another path, say "/sdcard/DCIM/appPictures", I believe you can use this code:
FileOutputStream outFile = FileOutputStream("/sdcard/DCIM/appPictures/" + fileName);
and then copy it byte by byte like in the example above.

Categories

Resources