Passing an image from webview to application (IOS and Android) - android

I'm building hybrid applications that rely on 2-way communication between javascript in a webview and the hosting application.
Attitudes differ somewhat as in IOS the JS can send a message to swift (using WKWebView), that listens through
userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage)
when implementing the WKScriptMessageHandler protocol,
whereas in Android the JS can actually call an Android method that has #JavascriptInterface annotation, after calling addJavascriptInterface().
Both approaches are OK for me, as I'm passing around data using JSON strings. Question is, what if I need to pass a media file, say an image or video, from the web page to the application? should I just pass a bitmap inside the json? Seems a little naive... recommendations?
edit: when passing an image from the application to the webpage I save the file to the file system and send the filename to the webview. Can it be done the other way around? Can javascript save to the hosting mobile device file system?

You have to host(in case of webapp) or store(in case of mobile app) the image and pass the image url, not exactly the image.
Almost all api that uses images bitmap also takes image url.
regards
Ashish

To answer your second question which is there are comments, use the following code.
Here the html content is your binary content:
FileWriter imageFileWriter = null;
BufferedWriter imageBufferedWriter = null;
ABOUtil.createDir(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
File imageFileDir = new File(InMemoryDataStructure.FILE_PATH.getFileDirForimage());
String imageName = "/finalimage"+ filename + jpg
File mimageFile = new File(imageFileDir, imageName);
try {
imageFileWriter = new FileWriter(mimageFile, false);
imageBufferedWriter = new BufferedWriter(imageFileWriter);
StringBuilder sb = new StringBuilder();
sb.append(htmlContent);
sb.append(scriptInjectJavascript(lstimageNameValue));
imageBufferedWriter.write(sb.toString());
imageBufferedWriter.close();
return mimageFile;
}
catch (IOException e) {
MAFLogger.e("", "", e);
}
finally{
if(imageFileWriter!=null)
try {
imageFileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
if(imageBufferedWriter!=null)
try {
imageBufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
MAFLogger.e("","",e);
}
}

Related

IPFS read data from network

I am working on one application, where I am using IPFS for storing and getting files.
I am using the following API for Android,
https://github.com/ligi/ipfs-api-kotlin
As per the doc, I can get data from IPFS using following code,
ipfs.get.cat("hash code of IPFS file")
but here it returns everything in string format, even if the uploaded file is Image.
How Can I know the content type of the file and download the same format?
IPFS doesn't allow to store metadata such as the content type alongside the content itself.
Something you could do in Java that worked for me:
private static String guessContentType(InputStream content) {
try {
String guessedContentType = URLConnection.guessContentTypeFromStream(content);
if (!StringUtils.isEmpty(guessedContentType)) {
return guessedContentType;
} else {
return MediaType.APPLICATION_OCTET_STREAM_VALUE;
}
} catch (IOException e) {
throw new RuntimeException("Unable to guess content type", e);
}
}

How to use getClassLoader() correctly?

Here I try to use getClassLoader().getResources() to get my .model file, however it returns null. I'm not sure where goes wrong!
And when I try to print out the urls, it gives me java.lang.TwoEnumerationsInOne#5fd1900, what does this means?
public Activity(MainActivity activity) {
MainActivity activity = new MainActivity();
try {
// Open stream to read trained model from file
InputStream is = null;
// this .model file is save under my /project/app/src/main/res/
Enumeration<URL> urls = Activity.class.getClassLoader().getResources("file.model");
// System.out.println("url:"+urls);
if (urls.hasMoreElements()) {
URL element = urls.nextElement();
is = element.openStream();
}
// deserialize the model
classifier = (J48) SerializationHelper.read(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
In Android, resources put under src/main/res are not visible in the class path and can only be accessed via the android resources API. Try to put the file into src/main/resources.

Send XML file to FTP/HTTPS server

I create small tracking app which get coordinates write them to xml file and then send this file with that data to ftp server. I am using function "SendFileGPS" to send that file but apk all the time crashes and it doesn't work. This function is using additional library common net 1.4 and it is quite strange because all the time when I start Android Studio I must download this library from web by Android Studio. And I got some additional questions.
I was thinking that maybe not only this function is a problem, how should look this server I mean how proper this server to get file from this app?
There is a another way to send this file without using additional libs ?
How it should look if I want send this file to another type of server (HTTPS)?
public void SendFileGPS()
{
FTPClient mFTP = new FTPClient();
try {
// Connect to FTP Server
mFTP.connect("here I put adress IP");
mFTP.login("here I put login", "here I put pass");
mFTP.setFileType(FTP.BINARY_FILE_TYPE);
mFTP.enterLocalPassiveMode();
// Prepare file to be uploaded to FTP Server
File file = new File("/path/to/MyXmlFileName.xml");
FileInputStream ifile = new FileInputStream(file);
// Upload file to FTP Server
mFTP.storeFile("filetotranfer",ifile);
mFTP.disconnect();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

How to set a background template to a pdf using iText library in android?

I wanna set a background Template(image) in my pdf that generated by iText Library,something like this:
Click too see the image
I tried to use something like the code below:
PdfReader reader = new PdfReader("./assets/sarbargandroid.pdf");
PdfImportedPage page = writer.getImportedPage(reader, 1);
PdfContentByte cb = writer.getDirectContent();
cb.addTemplate(page, 0.0, 0.0);
but it did not work in android because .addtemplate() methode needs some awt library!
and I tried addimage stuff like this:
private void setBackground(Chapter document) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.sarbarg);
bitmap.compress(Bitmap.CompressFormat.JPEG , 100, stream);
Image img;
try {
img = Image.getInstance(stream.toByteArray());
img.setAbsolutePosition(0, 0);
document.add(img);
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But it did't work correctly because the image does not fit the page and it create a pdf like this:
Click too see image
How can I do this correctly? anyone help me??
There are several things wrong with your question and that may explain why nobody answers. I'll tell you what's wrong and then maybe you can create a new question.
You say:
it did not work in android because .addtemplate() methode needs some awt library!
If the addTemplate() method needs an AWT library, then you are using iText. When working on Android, you should use iTextG: http://itextpdf.com/product/itextg
You are using PdfReader which makes people assume that you want to add a background image to an existing document. This would imply that you use PdfStamper, yet your code looks like you're using PdfWriter. That's a contradiction.
Your setBackground() method takes a Chapter as parameter to which you add an image. This is counter-intuitive:
- If you'd want to add a background image to an existing document, you'd never use the Chapter object.
- If you'd want to add a background image to every page of a PDF that is created from scratch, you'd use a page event.
Another major problem is that you create the image and add it as-is. You didn't scale it to fit the page.
Also: if you add an image in the background of an existing PDF. Parts of that image may be covered by opaque shapes that are present in the original document.

Writing to and Reading from a file in Android

I am having a hard time figuring out how to write to and read from files on an Android device. The file will be formatted as XML and I already have parsers and data structures built that can format the XML into objects and objects into XML, but the last hurdle is reading the XML from a non-resource file (I know the data structures work because I it works when reading from a resource file) and also writing to a non-resource file. I am terrible at using tools to debug (not sure how to print a stack trace) but I know for a fact the problem is that I cannot read from or write to this files. I have no experience writing to files in Java which may be why I am having a rough time with this.
Write code:
File scoresFile = new File(getExternalFilesDir(null), "scores.xml");
if (!scoresFile.exists())
{
scoresFile.createNewFile();
}
OutputStream os = new FileOutputStream(scoresFile);
os.write(writer.toString().getBytes());
os.flush();
os.close();
Read Code:
XmlPullParserFactory xmlFac = XmlPullParserFactory.newInstance();
XmlPullParser qXML = xmlFac.newPullParser();
InputStream is = null;
File scoresFile = new File(c.getExternalFilesDir(null), "scores.xml");
if (!scoresFile.exists())
{
try {
scoresFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
is = new FileInputStream(scoresFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (is != null)
qXML.setInput(is,null);
else
qXML = c.getResources().getXml(R.xml.scores);
UPDATE: The last if clause in the read section always evaluates to false. So, the InputStream is null... that appears to be the root of my problem.
I would take a look at these two links: Using Internal Storage and Using External Storage
Both link to the same page, just different portions. Really, it depends on whether or not you want to save this file to the devices memory, or to an external medium (such as an SDcard).
Internal - Sandboxed, so that only your app can access it.
External - Anyone can access it.

Categories

Resources