PhoneGap Android cache app - android

I'm developing a app with PhoneGap/Cordova 2.5.0 and I'm making AJAX calls with jQuery 1.8.2 to retrieve datas from an external server. I'm doing a lot of requests and I can see my app cache growing up, and this is not pretty cool...
I've tested many things like :
$.ajaxSetup({
cache: false,
headers: {
"Cache-Control": "no-cache"
}
});
OR / AND
var ajaxRequests = {}; // Limit one AJAX call for each "data_id" to prevent numbers calls
if (vrbd.ajaxRequests[data_id] === undefined) {
ajaxRequests[data_id] = $.ajax({
type: 'GET',
dataType: 'xml' + data_id,
url: url,
data: {
_: new Date().getTime() + Math.random()
},
async: true,
timeout: (data_count >= 2 ? data_count * 800 : 2000),
cache: false,
headers: {
"Cache-Control": "no-cache"
}
})
.done(function(data, textStatus, jqXHR) { ... })
.fail(function(jqXHR, textStatus, errorThrown) { ... })
.always(function(jqXHR, textStatus) { delete ajaxRequests[data_id]; });
}
If I let my app running during a couple of hours, I can see my cache growing up from about 160kb to about 30Mb in Settings > Apps > MyApp > Cache (AVD and real device).
So, didn't I understand anything about the cache in Settings or did I forget something ?
Please, let me know if you need another informations, sorry for my english, and thanks in advance for your help.
Best regards
Alex

Clear cache:
// clear cache
super.clearCache();
super.loadUrl("file:///android_asset/www/index.html");
Source:
Adding a splash screen and clearing cache with PhoneGap and Android

Related

React Native download manager fails with status code 16 when downloading on Android

I have been trying to fix an issue with downloading a zip file from our service on our Android app. The iOS works fine, but on Android I get the following error:
ExceptionsManager.js:149 Error downloading file Error: Download manager failed to download from <download_urll> Status Code = 16
My download code looks like this. We are using react-native-blob-util:
const FILE_URL = uri;
const { config, fs } = ReactNativeBlobUtil;
const { dirs } = fs;
let writePath = dirs.DocumentDir;
if (Platform.OS === 'android') {
writePath = `${dirs.DownloadDir.split('Android')[0]}Download`;
}
const options = {
fileCache: true,
addAndroidDownloads: {
path: writePath + '/' + fileName + '.' + fileExtension,
description: `Downloading ${fileName}{}`,
notification: true,
useDownloadManager: true,
},
};
return await config(options)
.fetch('GET', FILE_URL, {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/zip',
})
.then(() => {
// Handle download success
})
.catch((e) => {
// Handle download failure
});
I have tried pretty much everything I found on the answers here, here, here and even here. And also several other places I found. I have checked the authentication too. It's not that.
Any idea what this might be? The issue is that this seems to occur only in the production variant of our Android app, and works just fine on the rest, including the production variant of our iOS app. A real head scratcher.
Any ideas are welcome. 🙏🏼

How to upload large files using react-native-image-crop-picker

I'm trying to upload small files using react-native-image-crop-picker it's working fine but when I tried uploading large video/image file using react-native-image-crop-picker I'm getting Network error.
Note : Backend is working fine I'm able to upload file using Postman.
It's happening with large files only. I'm able to upload files that are smaller than 1MB
Code
import ImagePicker from 'react-native-image-crop-picker';
import axios from "axios";
function uploadFile(){
ImagePicker.openCamera({
mediaType: 'any',
}).then(file=> {
const body = new FormData();
body.append('vurl', {
name: file.fileName,
type: file.mime,
uri: Platform.OS === 'ios' ? file.path.replace('file://', '') : file.path,
});
axios({
method:"post",
url:"Server url",
data:body,
headers: {
Accept: 'application/json',
'Content-Type': "multipart/form-data",
}
})
.then((res) => {
console.log(JSON.stringify(res));
})
.catch((err) => {
console.log(err.response);
});
});
}
//calling here
<TouchableOpacity onPress={uploadFile}>
<Text>upload file</Text>
<TouchableOpacity>
Please check that you have set or not client_max_body_size in your backend for the server.
For Nginx :- /etc/nginx/proxy.conf
client_max_body_size 100M;
For more: Increasing client_max_body_size in Nginx conf on AWS Elastic Beanstalk
Make sure that you don't have a default timeout defined in the code like:
.defaults.timeout = x
https://www.npmjs.com/package/react-native-axios#config-defaults
I produced my suggestions by following directly from react-native-image-crop-picker example app repo here:
Set max height and width of what you're recording on camera. Example :
ImagePicker.openCamera({
mediaType: 'any',
cropping: cropping,
width: 500,
height: 500,
}).then(file=> {
Compressing the quality of an image that you are picking
ImagePicker.openPicker({
mediaType: 'any',
compressImageMaxWidth: 1000,
compressImageMaxHeight: 1000,
compressImageQuality: 1, ----> you can set the value between 0 and 1 e.g. 0.6.
})
.then(file=> {.....
Set a max size should not exceed e.g. 1MB (whatever number you want) when you get the response before handling it further. Again I obtained file.size in the response section of the link above
ImagePicker.openCamera({
mediaType: 'any',
}).then(file=> {
if (file.size > xxx) {
Alert.alert('File size too large!')
//dont forget to import alert from react-native
}

Laravel API Rest doesn't work in device Android

I have an app in IONIC and in browser the call to API works but when I run on android device it shows this error:
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://192.168.1.***:8080/api/auth/login", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://192.168.1.***:8080/api/auth/login: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://192.168.1.***:8080/api/auth/login"
__proto__: HttpResponseBase
In IONIC I send like API_URL = 'http://192.168.1.***:8080/api/'; to use HttpClient, and in Laravel I run php artisan serve --host 192.168.1.*** --port 8080
Please, someone knows what I should do to work?
The issue is related to CORS. You don't have to do anything to your IONIC app. You can enable CORS request by adding required headers for that you can create your own middleware in Laravel to handle cors, A sample middleware would be:
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
}
}
Then use it, by editing app\Http\Kernel.php
protected $middlewareGroups = [
'web' => [
// middleware for your web routes
],
'api' => [
'throttle:60,1',
'bindings',
'cors',
],
]
protected $routeMiddleware = [
// other middleware code
'cors' => \EuroKids\Http\Middleware\Cors::class,
]
You can customize the above middleware as required.
However, if you don't want to do create your own middleware you can use this library:
https://github.com/barryvdh/laravel-cors

phonegap android ajax over ssl failes

I develope an App with Phonegap and Jquery Mobile. For some reasons I also need to get data from https domains. On IOS everything works perfect, but on Android I always get the following errors and the requests fails
06-17 17:16:33.890 6079-6154/de.sistecs.einlass E/chromium_net: external/chromium/net/socket/ssl_client_socket_openssl.cc:905:
[0617/171633:ERROR:ssl_client_socket_openssl.cc(905)] handshake failed; returned -1, SSL error code 1, net_error -107
Here is a simple sample code
$(document).on("pageinit", function (event, ui) {
$("#test").click(function () {
$.ajax({
type: "POST",
url: "https://test.sistecs.de/sismedia/test.php",
success: function (response) {
$("#testmsg").text(response);
}
});
});
});
I´ve read hundreds of posts, but didn´t find a solution to my problem.
The certificate of the server https://test.sistecs.de/sismedia/test.php is valide.
Can someone help me?
It seems like a Cross Origin problem.
With jQuery Mobile you should set $.mobile.allowCrossDomainPages and $.support.cors to true
<script>
$( document ).on( "mobileinit", function() {
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
Also be sure that your PHP page sets the headers accordingly. For example:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE');
header('Access-Control-Allow-Headers: Content-Type');
echo "test";
?>
Edit: I didn't test the code, it is an example. Adapt as you need to.
var myJson = {
'Par1': 'par'
};
$.ajax({
url: baseUrlAjaxServices + "/....",
data: JSON.stringify(myJson),
method: "POST",
crossDomain: true,
dataType: 'json',
contentType: 'application/json',
})
.done(function (data) {
//...
}).fail(function (error) {
console.log(error);
});

Use request module to download and get urls in mobile application

I made a small script that use request:
request({
url: "http://gdata.youtube.com/feeds/api/videos?alt=json&max-results=1&q=" + encodeURIComponent(trackName),
json: true
}, function (dataAndEvents, deepDataAndEvents, data) {
});
and now I want to port it to android using Ionic Framework. Is it possible to get and download easily urls?
Ionic is built on angular so you can use the $http method to request remote data.
$http({
url: 'http://gdata.youtube.com/feeds/api/videos',
params: {
alt: 'json',
max-results: 1,
q: trackName
}
})
.success(function(data, status) {
console.log(data);
})
.error(function(data, status) {
console.log('error');
});

Categories

Resources