I need to read a .json that I have within my .APK. I have tried many times I've even spend more than 1 day in it.
I think the problem is that FLHAS PROFESSIONAL use, but not want to give surrendered.
Nor loaded pictures new URLRequest(pictURL) :
Here are some codes that do not work on your phone (Android):
var pictLdr:Loader = new Loader();
var pictURL:String = "basecon/avatar3d.jpg";
var pictURLReq:URLRequest = new URLRequest(pictURL);
pictLdr.load(pictURLReq);
this.addChild(pictLdr);
And so I read the JSON and does not work
var tempFiles:File = File.desktopDirectory;
tempFiles = tempFiles.resolvePath("basecon/conversaciones.json");
trace(tempFiles.url); // app-storage:/images
//file:///storage/sdcard1/basecon/conversaciones.json
Why? How Can I read my JSON ?
The PO has done his best to ask a question in English but it did end up being a little off. What he meant is "how to read a json file", it's not that he can't read it, it's that he doesn't know how.
A File object gives you information about a file but not about its contents so trying to read a file with a File object won't work. You simply need to load that file and read its contents.
var tempFiles:File = File.applicationDirectory;
var jsonFile:File = tempFiles.resolvePath("basecon/conversaciones.json");
var fileLoader:URLLoader = new URLLoader();
fileLoader.addEventListener(Event.COMPLETE, handleFile);
fileLoader.load(new URLRequest(jsonFile.url));
Then in the handleFile listener:
var jsonData:String = String(fileLoader.data);
var jsonObject:Object = JSON.parse(jsonData);
Pretty simple.
Related
in my App I print some parts to a pdf for the user. I do this by using a PrintedPdfDocument.
The code looks in short like this:
// create a new document
val printAttributes = PrintAttributes.Builder()
.setMediaSize(mediaSize)
.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
.build()
val document = PrintedPdfDocument(context, printAttributes)
// add pages
for ((n, pdfPageView) in pdfPages.withIndex()) {
val page = document.startPage(n)
Timber.d("Printing page " + (n + 1))
pdfPageView.draw(page.canvas)
document.finishPage(page)
}
// write the document content
try {
val out: OutputStream = FileOutputStream(outputFile)
document.writeTo(out)
out.close()
Timber.d("PDF written to $outputFile")
} catch (e: IOException) {
return
}
It all works fine. However now I want to add another page at the end. Only exception is that this will be a pre-generated pdf file from the assets. I only need to append it so no additional rendering etc. should be necessary.
Is there any way of doing this via the PdfDocument class from the Android SDK?
https://developer.android.com/reference/android/graphics/pdf/PdfDocument#finishPage(android.graphics.pdf.PdfDocument.Page)
I assumed it might be a similar question like this here: how can i combine multiple pdf to convert single pdf in android?
But is this true? The answer was not accepted and is 3 years old. Any suggestions?
Alright, I gonna answer my own question here.
It looks like there are not many options. At least I couldn't find anything native. There are some pdf libraries in the Android framework but they all seem to support only creating new pages but no operations on existing documents.
So this is what I did:
First of all there don't seem to be any good Android libraries. I found that one here which prepared the Apache PDF-Box for Android. Add this to your Gradle file:
implementation 'com.tom_roush:pdfbox-android:1.8.10.3'
In code you can now import
import com.tom_roush.pdfbox.multipdf.PDFMergerUtility
Where I added a method
val ut = PDFMergerUtility()
ut.addSource(file)
val assetManager: AssetManager = context.assets
var inputStream: InputStream? = null
try {
inputStream = assetManager.open("appendix.pdf")
ut.addSource(inputStream)
} catch (e: IOException) {
...
}
// Write the destination file over the original document
ut.destinationFileName = file.absolutePath
ut.mergeDocuments(true)
That way the appendix page is loaded from the assets and appended at the end of the document.
It then gets written back to the same file as it was before.
I´m trying to do an array to storage data with local storage. it works pretty well on google emulator. but isn´t working on my android device.
I found this code on the internet to put array in localstorage, and it works.
Storage.prototype.setArray = function (key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getArray = function (key) {
return JSON.parse(this.getItem(key))
}
then i create an function to get and set the data there.
function teste() {
var bd = [];
bd = window.localStorage.getArray("banco");
var nome = $('#name2').val();
alert(nome);
var area = $('#textarea2').val();
alert(area);
var meuservico = new servico(nome, area);
bd.push(meuservico);
alert(bd[0].nome);
window.localStorage.setArray("banco", bd);
}
and I also made an object called service.
function servico(nome,area){
this.nome = nome;
this.area = area;
}
this code work! but only on browser . how do I make it work on android? I don´t really wanna work with strings in localstorage. please help me!.
I tried with this too and didn´t work on device either.
localStorage.setItem('session', JSON.stringify(session));
var restoredSession = JSON.parse(localStorage.getItem('session'));
I am working on an android app where I wish to download swf files from an external server, save them to sdcard and load them later in the app. Downloading works fine and the swf is saved in the application directory. Here is my code that loads the swf from the sdcard :
var myloader:Loader = new Loader();
var myhomeButton:btnHome = new btnHome();
addChild(myloader);
var swfFilePath:File = File.applicationStorageDirectory.resolvePath("Android/data/myswffile.swf");
var inFileStream:FileStream = new FileStream();
inFileStream.open(swfFilePath, FileMode.READ);
var swfBytes:ByteArray = new ByteArray();
inFileStream.readBytes(swfBytes);
inFileStream.close();
var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
loaderContext.allowCodeImport = true;
myloader.contentLoaderInfo.addEventListener(Event.COMPLETE, mycompleteHandler);
myloader.loadBytes(swfBytes, loaderContext);
function mycompleteHandler(evt:Event):void
{
myloader.contentLoaderInfo.removeEventListener(Event.COMPLETE, mycompleteHandler);
addChild(myhomeButton);
myhomeButton.height = _height * 0.08;
myhomeButton.width = myhomeButton.height;
myhomeButton.x = 10;
myhomeButton.y = 10;
myhomeButton.addEventListener(MouseEvent.CLICK, myexitfftn);
}
function myexitftn(evt:Event):void
{
myloader.unloadAndStop(true);
removeChild(myhomeButton);
gotoAndStop(1, "SomeOtherFrame");
}
the problem is when I click the exit button the swf unloads but when I reload it, it starts from the second frame of the loaded swf, the third time from the third frame and so on... Where am I going wrong or what is an alternative solution, please guide.
Try, addChild(myloader) in Complete handler and removeChild and null while exiting, so that loaded swf is completely removed from the memory like so:
function mycompleteHandler(evt:Event):void
{
myloader.contentLoaderInfo.removeEventListener(Event.COMPLETE, mycompleteHandler);
addChild(myloader);
//... Rest of code remains same
}
function myexitftn(evt:Event):void
{
myloader.unloadAndStop();
removeChild(myloader);
myloader = null;
removeChild(myhomeButton);
gotoAndStop(1, "SomeOtherFrame");
}
This is my first time really getting my teeth into Air for Android so please forgive me if this issue has been covered already. If it has then I've been unable to find it.
So I have an application that loads and displays xml data.
In the app I've got code to check if wiFi or equivalent is available and if so then pull live xml file and if not then pull the local xml file that was packaged with the application.
The app works fine if I am pulling in the xml from the live url but not if pulling from local.
After doing some research I discovered that when pulling in local file then Air for Android works slightly differently. So I need to resolve the application directory.
I did this and still no joy.
After a bit more research I read some post's that said I should use fileStream()
Tried this and still nada :(
All the time whilst testing in Flash IDE it works as intended.
If I had any more hair left I would be pulling it out right now!
The local xml file is set in the "includes"
Sample code below I am using for testing
var subURL:String = "xml_feeds/myxmlfile.xml"
var fileStream:FileStream = new FileStream();
var file:File = File.applicationDirectory.resolvePath(subURL);
fileStream.addEventListener(Event.COMPLETE, processXMLData);
fileStream.openAsync(file, FileMode.READ);
MovieClip(parent).txStates.text = file.url+" - TRYING"
var prefsXML:XML = new XML()
function processXMLData(event:Event):void{
MovieClip(parent).txStates.text = file.url+" - OPEN"
prefsXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
var tempArr:Array = new Array();
var reportCount:Number = prefsXML.row.column.length()
for (var i = 0; i < reportCount; i++) {
var rName:String = prefsXML.row.column[i].#name.toString();
var rValue:String = prefsXML.row.column[i].toString();
var rTitle:String = prefsXML.row.column[i].#name.toString()
tempArr.push([rName, rValue, rTitle]);
}
showData()
fileStream.close();
}
Is there anything I've missed?
UPDATE: 21/08/12
No idea what is going on with this. Here is the code i now have to use in order to load in the local xml file. Seems rather long winded
function listing():void{
var folders:Array = new Array();
folders = File.applicationDirectory.getDirectoryListing();
for(var i:Number =0;i<folders.length;i++){
if(folders[i].isDirectory){
if(folders[i].name=="xml_feeds"){
var files:Array = new Array();
files = folders[i].getDirectoryListing();
for(var j:Number=0;j<files.length;j++){
if(files[j].name=="CTSection2.xml"){
fileStream.openAsync(files[j], FileMode.READ);
fileStream.addEventListener(Event.COMPLETE, processXMLData);
fileStream.addEventListener(IOErrorEvent.IO_ERROR, localXMLFailLoad);
}
}
}
}
}
}
I am currently developing an Android application using Flex 4.5.1 and I am having an issue when trying to pass data that I have stored in a SharedObject array to my Web Service for a Database query. the code below shows how I am storing the data in the SharedObject:
var so:SharedObject = SharedObject.getLocal("app");
public var prefsArray:ArrayCollection = new ArrayCollection(so.data.prefs);
protected function prefs_btn_click(event:MouseEvent):void
{
prefsArray.source.push(getFrsByIDResult.lastResult.id);
so.data.prefs = [prefsArray];
var flushStatus:String = so.flush();
if (flushStatus != null) {
switch(flushStatus) {
case SharedObjectFlushStatus.PENDING:
so.addEventListener(NetStatusEvent.NET_STATUS,
onFlushStatus);
break;
case SharedObjectFlushStatus.FLUSHED:
trace("success");
break;
}
}
}
protected function onFlushStatus(event:NetStatusEvent):void
{
trace(event.info.code);
}
I have tested the SharedObject to see if the information is being entered into it correctly and all seems fine. Now I have used the code below in order to retrieve the data from the SharedObject and try and send it to the PHP web Service to run the DB query.
var so:SharedObject = SharedObject.getLocal("app");
var arrCol:ArrayCollection = new ArrayCollection(so.data.prefs);
var str:String = new String(arrCol.toString());
protected function list_creationCompleteHandler(event:FlexEvent):void
{
getPrefsByprefIdsResult.token = prefsService.getPrefsByPrefIds(so.data.prefs);
}
I have tested the Webservice in Flex and have it configured to recieve an Array of Ints (int[]) and it works when i run a test operation on it with two dummy values. However when I try to use the code above to pass the Web Service the Shared Object data I get this error:
TypeError: Error #1034: Type Coercion failed: cannot convert []#97e97e1 to mx.collections.ArrayCollection.
at views::**************/list_creationCompleteHandler()[C:\Users\Jack\Adobe Flash Builder 4.5\****************\src\views\*******************.mxml:25]
at views::*********************/__list_creationComplete()[C:\Users\Jack\Adobe Flash Builder 4.5\****************\src\views\***************.mxml:94]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.core::UIComponent/dispatchEvent()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:13128]
at mx.core::UIComponent/set initialized()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:1818]
at mx.managers::LayoutManager/validateClient()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:1090]
at mx.core::UIComponent/validateNow()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:8067]
at spark.components::ViewNavigator/commitNavigatorAction()[E:\dev\4.5.1\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:1878]
at spark.components::ViewNavigator/commitProperties()[E:\dev\4.5.1\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:1236]
at mx.core::UIComponent/validateProperties()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\core\UIComponent.as:8209]
at mx.managers::LayoutManager/validateProperties()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:597]
at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:783]
at mx.managers::LayoutManager/doPhasedInstantiationCallback()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\LayoutManager.as:1180]
I have replaced certain filenames and locations with *'s to protect the work i am doing, but can someone please help me with this issues as I believe it has to be something simple???
Thanks
ok so let me explain in more detail. This is being designed for an Android app like I said, but image what I am trying to do is to store Bookmarks persistently using the Local Shared Object.
The first chunck of code you see above is designed to create the LSO attribute for the bookmark i want to create and imagine that there can be more than one bookmark set at different times like in a web browser. The only way i could find to do this was to store these items/details in an array which I retrieve and then update before saving back to the LSO and saving.
The second piece of code related to imagine a "Bookmarks Page" with a list of all the content that I have bookmarked. Now what I wanted to happen was thta I would be able to call up the LSO attribute which held the id's of the bookmarks and then load up thier details in a list format.
I have managed to create the LSO and store the bookmark deatils in and allow them to be updated and entries added. Also I have made sure that the PHP code that I have pulls back all the database objects relating to the array of id's and this has been tested using flex. The only thing that I cant seem to do is to pass the id's to the PHP web service file. The code in the Web Service file is below if that helps:
public function getPrefsByPrefIds($PrefIds) {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE $this->tablename.id IN(" .implode(",", $PrefIds). ")");
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->id, $row->name, $row->desc);
while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->id, $row->name, $row->desc);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $rows;
}
Yes I had already tried that but thanks. I have made some more progress on my own as I have been experimenting with the different types of objects that can be stored in SharedObjects. I have managed to get the solution part working with this code:
This code is designed to capture the boomark info and store it in an arrayCollection before transferring it to a bytesArray and saving
var so:SharedObject = SharedObject.getLocal("app");
public var prefArray:ArrayCollection = new ArrayCollection(so.data.prefs);
protected function prefs_btn_click(event:MouseEvent):void
{
prefArray.source.push(getCompaniesByIDResult.lastResult.id);
so.data.prefs = [prefArray];
var bytes:ByteArray = new ByteArray();
bytes.writeObject(prefArray);
so.data.ac = bytes;
var flushStatus:String = so.flush();
if (flushStatus != null) {
switch(flushStatus) {
case SharedObjectFlushStatus.PENDING:
so.addEventListener(NetStatusEvent.NET_STATUS,
onFlushStatus);
break;
case SharedObjectFlushStatus.FLUSHED:
trace("success");
break;
}
}
}
protected function onFlushStatus(event:NetStatusEvent):void
{
trace(event.info.code);
}
This next code is the designed to retrieve that information from the SahredObjects bytesArray and put it back into an Array Collection
var so:SharedObject = SharedObject.getLocal("app");
var ba:ByteArray = so.data.ac as ByteArray;
var ac:ArrayCollection;
protected function list_creationCompleteHandler(event:FlexEvent):void
{
ba.position = 0;
ac = ba.readObject() as ArrayCollection;
getPrefsByPrefIdsResult.token = prefsService.getPrefsByPrefIds(ac);
}
however as I have said this works in a small way only as if I store only one Bookmark (id) for an item and then go to the bookmarks list the details for that bookark are successfully retrieved, however if I save more than one Bookmark(2 or more id's) the page will not load the details, i do not get an error but I believe it is hanging because it is looking for say id's "1,2" instead of "1" and "2" but i dont know why this is or how to resolve this. I appreciate the advice I have been given but am finding it hard there is no one who can help me with this issue and I am having to do various experiemnts with the code. Can someone please help me with this I would really appreciate it :-) Thanks