How to save the Instance State in Android applications developed with Titanium? - android

I'm working with Titanium 3.1 and developing for Android 3.0 and greater.
My app has a view that when clicked asks you if you want to take a picture or select an image from gallery. When I choose to take a picture from the camera, the camera shows with no problem and I can take the picture, the problem is that after I take the picture and choose to use it, my app resume from the beginning, not returning to the previous state it was showing before choosing to take a picture.
When I checked logcat I saw this line:
I/TiRootActivity(24120): (main) [0,0] checkpoint, on root activity create, savedInstanceState: null
It seems the state of my app is not being saved, but I don't know why. I'll be honest, this is my first time working on an app that goes to the camera app, takes a picture and returns to the app. Previously I've worked with Intents in Titanium and I've been able to return to the correct state of my app after exiting the application that was opened with the Intent using the back button.
This is the code I use to open the camera:
var globalBabyPicture = Titanium.UI.createImageView({
image:imagesPath + "kinedu_0027_ic_camara.png",
width:75,
});
var photoOptionsViewFromCamera = Ti.UI.createView({
width:Ti.Platform.displayCaps.platformWidth,
height:44,
left:0,
top:1*44,
backgroundColor:"transparent"
});
var photoOptionsViewFromCameraLabel = Ti.UI.createLabel({
text:"from camera",
font:{fontSize:14, fontFamily:"Arial Rounded MT Bold"},
color:"#368cd6"
});
photoOptionsViewFromCamera.add(photoOptionsViewFromCameraLabel);
photoOptionsViewFromCamera.addEventListener("touchstart", function(e){
var animateTouchStart = Ti.UI.createAnimation({backgroundColor:"#AFD1DE", duration:150});
photoOptionsViewFromCamera.animate(animateTouchStart);
});
//********* this is the code that triggers the camera to take the picture
photoOptionsViewFromCamera.addEventListener("touchend", function(e){
var animateTouchEnd = Ti.UI.createAnimation({backgroundColor:"transparent", duration:150});
photoOptionsViewFromCamera.animate(animateTouchEnd);
animateTouchEnd.addEventListener("complete", function(e){
Ti.Media.showCamera({
success : function(event) {
var tmp = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory, ('baby_temp.png'));
tmp.write(event.media);
var blob = tmp.read();
Ti.App.fireEvent("changePicture");
},
cancel : function() {
},
error : function(error) {
var message;
if (error.code == Ti.Media.NO_CAMERA) {
message = 'Device does not have camera capabilities';
} else {
message = 'Unexpected error: ' + error.code;
}
Ti.UI.createAlertDialog({
title : 'Camera',
message : message
}).show();
},
saveToPhotoGallery : false,
allowEditing : true,
mediaTypes : [Ti.Media.MEDIA_TYPE_PHOTO]
});
});
});
Ti.App.addEventListener("changePicture", function(e){
var tmp = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory, ('baby_temp.png'));
var blob = tmp.read();
var animationChange = Ti.UI.createAnimation({opacity:0, duration:200});
babyImage.animate(animationChange);
var animationChangeCompleted = Ti.UI.createAnimation({opacity:1, duration:200});
animationChange.addEventListener("complete", function(e){
babyImage.setWidth(100);
var image = blob.imageAsThumbnail(150);
babyImage.setImage(image);
babyImage.animate(animationChangeCompleted);
});
});
I've checked and the success callback is never made, I think it's because the application resumes from the beginning, showing the application splash screen.
How can I ensure that after taking the picture, the application returns to the previous view without resuming the application from the beginning?

I think allowEditing should be allowImageEditing

Related

How to redirect to app from WebBrowser in Expo

I am currently working on a project on Android using the Expo client for react native. I am trying to open a webpage using WebBrowser, passing my app development URI to the website. The website basically just redirects to the given URI after 5 seconds. However it never seems to open anything. I've used almost the exact same code as here: https://github.com/expo/examples/tree/master/with-webbrowser-redirect. When I load this project into expo and run, it redirects fine. However, when I copy the code for the website and app into my own project, website opens and displays, but redirect does nothing. It just stays there. Here is the code for opening the browser.
_openBrowserAsync = async () => {
try {
this._addLinkingListener();
let result = await WebBrowser.openBrowserAsync(
'https://wexley-auth.firebaseapp.com/?linkingUri=exp://192.168.1.2:19000'
);
this._removeLinkingListener();
this.setState({ result });
} catch (error) {
alert(error);
console.log(error);
}
};
The linking listener never fires the callback which should dismiss the browser. My app URI should be exp://192.168.1.2:19000 as expo developer tools shows me this when I connect over LAN. Ive also tried using Linking.makeUrl() instead of sending URI in string manually. Neither method works for me. Relevant website code:
document.addEventListener("DOMContentLoaded", function(event) {
var links = document.querySelectorAll('a');
var baseUri='';
// Take the uri from the params
var qs = decodeURIComponent(document.location.search);
if (qs) {
baseUri = qs.split('?linkingUri=')[1];
}
var redirectInterval = setInterval(function() {
var countdown = document.querySelector('.countdown');
var t = parseInt(countdown.innerText, 10);
t -= 1;
if (t === 0) {
clearInterval(redirectInterval);
window.location.href = baseUri;
}
}, 1000);
});
Am I missing a step? Do I need to setup a scheme for opening my app or should this work out of the box? Am I using the wrong URI? I noticed that in the example code, the app.json has the following fields that my app.json doesn't have:
"scheme": "expo.examples.with-webbrowser-redirect",
"platforms": [
"android",
"ios"
]

Android InAppBrowser virtual keyboard closes on executeScript(). [phonegap]

I copied my code from the following link. It's a workaround for Passing Data From an InAppBrowser back to the app.
blogs.telerik.com/appbuilder/posts/13-12-23/cross-window-communication-with-cordova's-inappbrowser
The problem is that after each executescript() the Keyboard disappears.
This issue status here is "won't fix". So I'm wondering if there is an alternative solution. I only see a reference to KitKat users, but that would only represent a limited amount.
https://issues.apache.org/jira/browse/CB-5449
Suggestions?
setName: function() {
var win = window.open( "http://jsfiddle.net/tj_vantoll/K2yqc/show", "_blank",
"EnableViewPortScale=yes" );
win.addEventListener( "loadstop", function() {
win.executeScript({ code: "localStorage.setItem( 'name', '' );" });
var loop = setInterval(function() {
win.executeScript(
{
code: "localStorage.getItem( 'name' )"
},
function( values ) {
var name = values[ 0 ];
if ( name ) {
clearInterval( loop );
win.close();
$( "h1" ).html( "Welcome " + name + "!" );
}
}
);
});
});
}
Depending on your use case, it might be a feasible workaround to check if the keyboard is currently visible and avoid calling executeScript in that case.
Try using the com.ionic.keyboard plugin to get cordova.plugins.Keyboard.isVisible and use that in your setInterval function.

appcelerator titanium map error

I've been tasked with adding a map to my appcelerator project. I have tried the alloy way (since I'm using alloy in the project). That apparently doesn't work and its been suggested that I create the map in the controller. I have done that below and the call to the map is triggered by an onclick function attached to an icon on the primary window. This seems to work on iOS but causes the app to crash on Android (using a samsung note)
function openMap(){
alert(alertString);
//var map = Alloy.createController('map');
//$.map.show();
//add alert location here -- get the data from the push message that comes in
var payload = Ti.App.Properties.getString("latest_buddy_alert","empty");
if (payload != "empty"){
var messageDetails = parsePushMessage(payload);
}
opera = mapview.createAnnotation({
latitude: messageDetails['lat'], // 43.7000,
longitude: messageDetails['lng'], // 79.4000,
title: alert,
pincolor:Map.ANNOTATION_RED,
});
var winMap = Titanium.UI.createWindow({
title:'Buddy Location',
BackgroundColor:'#fff'
});
var mapview = Titanium.Map.createView({
mapType: Titanium.Map.STANDARD_TYPE,
region: {latitude:lat, longitude:lon, latitudeDelta:0.01, longitudeDelta:0.01},
animate:true,
regionFit:true,
userLocation:true
,annotations: [opera]
});
winMap.add(mapview);
winMap.open();
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
Ti.API.log('error: ' + JSON.stringify(e.error) );
return;
}
var region = {
latitude:e.coords.latitude,
longitude:e.coords.longitude,
animate:true,
latitudeDelta:0.04,
longitudeDelta:0.04
};
mapview.setLocation(region);
});
}
As mentioned above, this creates an error which crashes the app:
Location[1,1] undefined
uncaught syntaxerror: unexpected token u
source: undefined
This is totally unhelpful, since I don't use a token 'u' or variable 'u' anywhere in my code. I have used several variations on the code above, all giving the same error.
I have had some small success moving to a webview, which shows the map on apple, but not on android.
Any ideas?

Phonegap FileTransfer .upload never fires successCallback

I'm trying to submit an image (either taken from camera, or selected from gallery) to my upload server by using cordova file-transfer plugin.
The camera plugin works fine, I can see the image -- taken with camera or selected from gallery -- being displayed on screen (by using <img /> tag).
When trying to implement the FileTransfer.Upload, the docs states that the upload method has some arguments, including success/error callback functions.
This is my portion of code:
function uploadPhoto() {
var imageURI = document.getElementById('ImageSource').getAttribute("src");
if (!imageURI) {
alert('Please select an image first.');
return;
}
console.log("imageURI = " + imageURI);
var url=encodeURI("http://my.server.path/upload.php");
var options = new FileUploadOptions();
options.fileKey = "file";
options.mimeType = "multipart/form-data";
options.chunkedMode = false;
console.log("Starting Transfer...");
var ft = new FileTransfer();
ft.upload(imageURI, url,
function (r) {
alert('Finished upload!');
}, function (error) {
console.log(error);
alert('Error uploading image with code: ' + error.code)
},
options
);
console.log("Finishing Transfer...");
}
The Callbacks are not firing
Running the app on an Android Emulator, I get no alert. I can't tell whether it was a success or a failure. But the strange thing is: the image file get uploaded to my server, and I can see these two lines delievered on the log:
D/CordovaLog( 2487): file:///android_asset/www/js/app.js: Line 123 : imageURI = content://media/external/images/media/24
D/CordovaLog( 2487): file:///android_asset/www/js/app.js: Line 147 : Starting Transfer...
D/CordovaLog( 2487): file:///android_asset/www/js/app.js: Line 163 : Finishing Transfer...
Can somebody kindly point me out, where should I look? Because I can't handle the response. I need to get the server response, and display a processed image back to the screen.

Titanium: navigation from one screen to other

On the click of my button, I want to navigate to another screen. How would I achieve this in Titanium?
var TrialButton = Titanium.UI.createButton({
color:'black',
backgroundColor:'#FFFFFF',
title:'Trial Mode',
top:55,
width:300,
height:50,
borderRadius:5,
font:{fontSize:18, fontFamily :'Helvetica', fontWeight:'bold'}
});
TrialButton.addEventListener('click', function() {
var newWindow = Titanium.UI.createWindow({
background : "#fff",
title : "Trial Demo",
url:"nextScreen.js"
});
newWindow.open();
});
TrialButton.addEventListener('click', function()
{
var newWindow = Ti.UI.createWindow({
background : "#000",
title : "Image View",
url:"nextScreen.js"
});
newWindow.open();
)};
should checkout examples here https://github.com/appcelerator/KitchenSink
here are some posts from my blog http://blog.clearlyinnovative.com/tagged/Appcelerator
If you're using Alloy, You can also navigate to another screen using the Alloy.createController method.
function sample(e) {
var nextScreen = Alloy.createController('nameOfNextScreen').getView();
nextScreen.open();
}
If you wish, you can also pass data to the next screen by passing it in as an argument eg,
var nextScreen = Alloy.createController('nameOfNextScreen', {sushi: "california roll" }).getView();
and retrieving the argument in the next screen with the following
var args = $.args;
var value = args.sushi;
TrialButton.addEventListener('click', function()
{
var newWindow = Ti.UI.createWindow({
background : "#000",
title : "Image View",
url:"nextScreen.js"
});
newWindow.open();
//close your current window of this page and also in your nextScreen.js page, the window must be set to current window
)};
Because its written wrong. Theres an error in code at the last line. The ")" has to follow after "}". Not opposite ast written here. So the closing tag is right like this: "});". Use following code instead:
TrialButton.addEventListener('click', function()
{
var newWindow = Ti.UI.createWindow({
background : "#000",
title : "Image View",
url:"nextScreen.js"
});
newWindow.open();
//close your current window of this page and also in your nextScreen.js page, the window must be set to current window
});

Categories

Resources