how will refresh controller in ionic while loading a page - android

here is the controller - its a tabs moving page data are loaded first time itself . but only display while reload?
.controller('TestCntrl', function($scope, $state, $route, $window, Chats, $rootScope, $cordovaToast, $location, $ionicSlideBoxDelegate, $window, $ionicGesture, WebService, $localStorage) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.Height = $window.innerHeight - 30;
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
$scope.nextSlide = function() {
$ionicSlideBoxDelegate.next();
};
//controller for category types for products.
$route.reload();
WebService.invokeService('home', 'POST', 'http://' + $rootScope.ip + 'php/products_category.php')
.success(function(data) {
$route.reload();
$scope.productCategories = data.productCategories;
console.log("PRODUCT CATEGORIES ", $scope.productCategories);
var data = {
category_id: $localStorage.category.c_id,
product_category: $scope.productCategories[0].product_category
}
var jsonStr = angular.toJson(data);
WebService.invokeService('home', 'POST', 'http://' + $rootScope.ip + 'php/productsList.php', jsonStr)
.success(function(data) {
// $scope.productsList = data.productsList;
$scope.productsListd = data.productsList;
console.log($scope.productsListd);
// $window.location.reload();
// location.reload(true);
$route.reload();
})
.error(function(data) {
$cordovaToast.showLongCenter('Please Check Your Data Connection!');
});
})
.error(function(data) {
$cordovaToast.showLongCenter('Please Check Your Data Connection!');
});
$scope.myActiveSlide = 0;
$scope.reportSlideChanged = function(slideNum) {
console.log('SlideNum = ' + slideNum);
// switch(slideNum) {
// case 0:
var data = {
category_id: $localStorage.category.c_id,
product_category: $scope.productCategories[slideNum].product_category
}
var jsonStr = angular.toJson(data);
WebService.invokeService('home', 'POST', 'http://' + $rootScope.ip + 'php/productsList.php', jsonStr)
.success(function(data) {
$scope.productsList = data.productsList;
console.log($scope.productsList);
// $window.location.reload();
// window.location.reload(true);
$route.reload();
})
.error(function(data) {
$cordovaToast.showLongCenter('Please Check Your Data Connection!');
});
}
$scope.productDetailsPage = function(product) {
$localStorage.product_Details = product;
$state.go('productDesc');
}
})

Related

Xamarin.Forms Help optimize load times

I am making an application in Xamarin Forms and I have a Login when loading the application. The case is that when I put the data, I make a call to an API and it returns a series of data in a json.
Then I go through the json, checking that each data exists in my local database (sqlite), if it exists, I update it, if it does not exist, I insert it.
Once it has gone through all the json it loads the following activity, or screen ...
The problem is that it easily takes 10 to 15 seconds to move on to the next activity.
Any idea how to optimize this process? Or, should I modify the API to get less data?
CODE:
Login.xaml.cs
namespace WorkersApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Login : ContentPage
{
public Login()
{
InitializeComponent();
}
public string user = "";
public string password = "";
private async void btnEncript_Clicked(object sender, EventArgs e)
{
if (userEntry.Text != null && passwordEntry.Text != null)
{
user = userEntry.Text;
password = EncriptarMD5.MD5Hash(passwordEntry.Text);
string url = "https://api.com/?f=login&u=" + user + "&pw=" + password;
await GetDataFromApi(url);
}
}
public async Task GetDataFromApi(string url)
{
HttpClient myClient = new HttpClient();
try
{
var response = await myClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
//ERRORES
var error = JsonConvert.DeserializeObject<Errores>(content);
List<string> errror = new List<string>();
foreach (var item in error.error)
{
errror.Add(item.Value);
}
//Tiro error.
if (errror[0] != "0")
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
return;
}
else
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
}
//HOTELES
var hoteles = JsonConvert.DeserializeObject<Hoteles>(content);
List<Model.Hoteles> lista_hoteles = await App.Database.GetHotelesAsync();
List<Model.Bloques> lista_bloques = await App.Database.GetBloquesAsync();
foreach (var item in hoteles.hoteles)
{
Model.Hoteles h = new Model.Hoteles();
h = JsonConvert.DeserializeObject<Model.Hoteles>(item.Value.ToString());
h.ID = item.Key.ToString();
var bloques = JsonConvert.DeserializeObject<Bloques>(item.Value.ToString());
bool existe = false;
foreach (var bloque in bloques.bloques)
{
existe = false;
Model.Bloques b = new Model.Bloques();
b.ID = bloque.Key.ToString();
b.Nombre = bloque.Value.ToString();
b.IDHotel = item.Key.ToString();
foreach (var iLista in lista_bloques)
{
if (b.ID == iLista.ID)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateBloquesAsync(b);
}
else
{
await App.Database.SaveBloquesAsync(b);
}
}
existe = false;
//if exists
foreach (var iLista in lista_hoteles)
{
if (h.ID == iLista.ID)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateHotelesAsync(h);
}
else
{
await App.Database.SaveHotelesAsync(h);
}
}
//SECCIONES
var secciones = JsonConvert.DeserializeObject<Secciones>(content);
List<Model.Seccion> lista_secciones = await App.Database.GetSeccionesAsync();
foreach (var item in secciones.secciones)
{
Model.Seccion s = new Model.Seccion
{
ID = item.Key.ToString(),
Nombre = item.Value
};
bool existe = false;
//if exists
foreach (var iLista in lista_secciones)
{
if (s.ID == iLista.ID)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateSeccionAsync(s);
}
else{
await App.Database.SaveSeccionAsync(s);
}
}
string data = Preferences.Get("IdError", "");
if (data == "0")
{
Application.Current.MainPage = new HomePage();
}
else
{
await DisplayAlert("Error", Preferences.Get("Nombre", ""), "Cerrar");
}
}
}
catch (Exception exc)
{
Console.WriteLine("EXCEPTION:::: " + exc);
await DisplayAlert("Error", exc.ToString(), "Cerrar");
}
}
}
}
HomePage.xaml.cs
namespace WorkersApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HomePage : Shell
{
public IList<Seccion> Secciones { get; set; }
public HomePage()
{
InitializeComponent();
Task.Run(async () =>
Secciones = await App.Database.GetSeccionesAsync()).Wait();
foreach(var item in Secciones)
{
Console.WriteLine(item.Nombre);
switch (item.Nombre)
{
case "Partes":
FlyPartes.IsVisible = true;
//Meter Partes en Parte
string url = "https://api.com/?f=partes.getList";
Task task = GetPartesFromApi(url);
break;
case "Auditorias":
FlyAuditorias.IsVisible = true;
break;
case "Maquinas":
FlyMaquinaria.IsVisible = true;
break;
case "Pisos":
FlyPisos.IsVisible = true;
break;
}
}
}
public async Task GetPartesFromApi(string url)
{
HttpClient myClient = new HttpClient();
try
{
var response = await myClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var error = JsonConvert.DeserializeObject<Errores>(content);
List<string> errror = new List<string>();
foreach (var item in error.error)
{
errror.Add(item.Value);
}
if (errror[0] != "0")
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
return;
}
else
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
}
var partes = JsonConvert.DeserializeObject<Objetos.Partes>(content);
List<Model.Partes> lista = await App.Database.GetPartesAsync();
foreach (var item in partes.partes)
{
Model.Partes p = new Model.Partes();
p = JsonConvert.DeserializeObject<Model.Partes>(item.Value.ToString());
p.ID = item.Key.ToString();
bool existe = false;
//if exists
foreach (var iLista in lista)
{
if (p.ID == iLista.ID)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdatePartesAsync(p);
}
else
{
await App.Database.SavePartesAsync(p);
}
}
}
}
catch (Exception exc)
{
Console.WriteLine("EXCEPTION:::: " + exc);
await DisplayAlert("Error", exc.ToString(), "Cerrar");
}
}
}
}
Partes.xaml.cs
namespace WorkersApp.Pageviews
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Partes : ContentPage
{
public IList<Model.Partes> Partess { get; set; }
public Partes()
{
InitializeComponent();
Task.Run(async () =>
Partess = await App.Database.GetPartesAsync()).Wait();
int contador = 0;
foreach (var item in Partess)
{
Color c = Color.Black;
if (contador % 2 == 0)
{
c = Color.FromRgb(64, 64, 64);
}
var partesBoxClick = new BoxView()
{
WidthRequest = 900,
HeightRequest = 120,
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Start,
BackgroundColor = c,
ClassId = item.ID
};
var partesBoxClick_tap = new TapGestureRecognizer();
partesBoxClick_tap.Tapped += (s, e) =>
{
//OPEN PARTE
GetDatosParteFromApi("https://api.com/?f=partes.get&id= " + partesBoxClick.ClassId, partesBoxClick.ClassId);
};
partesBoxClick.GestureRecognizers.Add(partesBoxClick_tap);
PartesListaView.Children.Add(partesBoxClick, 0, contador);
Color color = Color.Red;
Console.WriteLine("COLOR:::: " + item.Operacion);
switch (item.Operacion)
{
case "nuevo":
color = Color.Red;
break;
case "asignado":
color = Color.GreenYellow;
break;
case "en progreso":
color = Color.Orange;
break;
case "anulado":
color = Color.Gray;
break;
case "en ejecucion":
color = Color.DeepSkyBlue;
break;
case "cerrado":
color = Color.Green;
break;
case "terceros":
color = Color.Firebrick;
break;
}
PartesListaView.Children.Add(new BoxView() { BackgroundColor = color, WidthRequest = 5, HeightRequest = 120, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Start }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Titulo, FontSize=16, FontAttributes=FontAttributes.Bold, Padding = new Thickness(10, 0, 0, 0), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Start }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Departamento, Padding = new Thickness(10, 0, 10, 18), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.End }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Hotel, Padding = new Thickness(10, 0, 10, 0), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.End }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Fecha, Padding = new Thickness(10, 0, 10, 18), HorizontalOptions = LayoutOptions.End, VerticalOptions = LayoutOptions.End }, 0, contador);
PartesListaView.Children.Add(new Label { Text = item.Prioridad, Padding = new Thickness(10, 0, 10, 0), HorizontalOptions = LayoutOptions.End, VerticalOptions = LayoutOptions.End }, 0, contador);
contador++;
}
}
public async Task GetDatosParteFromApi(string url, string id)
{
HttpClient myClient = new HttpClient();
try
{
var response = await myClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
//GET ERROR
var error = JsonConvert.DeserializeObject<Errores>(content);
List<string> errror = new List<string>();
foreach (var item in error.error)
{
errror.Add(item.Value);
}
if (errror[0] != "0")
{
Preferences.Set("IdError", errror[0]);
Preferences.Set("Nombre", errror[1]);
return;
}
//GET DATOS
List<string> ids = new List<string>();
List<string> idsh = new List<string>();
var Datos = JsonConvert.DeserializeObject<Parte>(content);
string parte_datos = "";
string parte_fotos = "";
string parte_historico = "";
foreach (var item in Datos.parte)
{
if (item.Key.ToString() == "datos")
{
List<Model.Parte> datosParte = await App.Database.GetDatosParteAsync();
parte_datos = item.Value.ToString();
Model.Parte parte = new Model.Parte();
parte = JsonConvert.DeserializeObject<Model.Parte>(parte_datos);
parte.ID_Parte = id;
bool existe = false;
foreach (var iLista in datosParte)
{
if (parte.ID_Parte == iLista.ID_Parte)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateDatosParteAsync(parte);
}
else
{
await App.Database.SaveDatosParteAsync(parte);
}
}
else if (item.Key.ToString() == "fotos")
{
parte_fotos = item.Value.ToString();
List<Model.Fotos> fotos = await App.Database.GetFotosAsync();
List<Model.Fotos> FotoList = new List<Model.Fotos>();
//foto = JsonConvert.DeserializeObject<Model.Fotos>(parte_fotos);
FotoList = JsonConvert.DeserializeObject<List<Model.Fotos>>(parte_fotos);
foreach(var fotoI in FotoList)
{
Model.Fotos foto = new Model.Fotos();
foto = fotoI;
foto.ID_Parte = id;
bool existe = false;
ids.Add(foto.ID_Foto);
foreach (var iLista in fotos)
{
if (foto.ID_Foto == iLista.ID_Foto)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateFotoAsync(foto);
}
else
{
await App.Database.SaveFotoAsync(foto);
}
}
}
else if (item.Key.ToString() == "historico")
{
parte_historico = item.Value.ToString();
List<Model.Historico> historicos = await App.Database.GetHistoricoAsync();
List<Model.Historico> HistoricoList = new List<Model.Historico>();
HistoricoList = JsonConvert.DeserializeObject<List<Model.Historico>>(parte_historico);
foreach (var historicoI in HistoricoList)
{
Model.Historico historico = new Model.Historico();
historico = historicoI;
historico.idHistorico = id + historico.fechaEvento;
bool existe = false;
idsh.Add(historico.idHistorico);
foreach (var iLista in historicos)
{
if (historico.idHistorico == iLista.idHistorico)
{
existe = true;
}
}
if (existe)
{
await App.Database.UpdateHistoricoAsync(historico);
}
else
{
await App.Database.SaveHistoricoAsync(historico);
}
}
}
}
string data = Preferences.Get("IdError", "");
if (data == "0")
{
await Navigation.PushAsync(new DatosParte(id, ids, idsh));
}
else
{
await DisplayAlert("Error", Preferences.Get("Nombre", ""), "Cerrar");
}
}
}
catch (Exception exc)
{
Console.WriteLine("EXCEPTION:::: " + exc);
await DisplayAlert("Error", exc.ToString(), "Cerrar");
}
}
private void Filter_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new FiltroPartes());
}
}
}
Thanks for reading.
EDIT:::::
After cleaning the API, now i get fewer Tickes to check if update or save indo local sqlite.
But I just notice I still need to check the whole BBDD to login.
The API now check tickets from last 30 days from curdate and with
operation_state <> "Closed"
I think I'm login (1 call to API to check if user is good)
Then in the HomePage im getting all the tickets (1 call to API to get tickets)
AND THEN. When I click in the Tickets Menu, it loads into the listview. (So another 15 seconds).
I believe i need to remove the API call in HomePage. and add it when I click in Ticket Menu.
Will check in some time. Or tomorrow.
EDIT:
So i checked and i was right, I changed the app to get all the tickets when I tap the Tickets menu.
Thanks for reading.
Cristian, it's normal in mobile app development. According to the amount of data we are getting it takes time to load.
Though as you have mentioned that you are calling service and inserting data if not exist and update if exist, so this data are dynamic and getting changed every time when you call? If not than instead of updating or calling service again, use the data from local database.
If not than You can use monkey cache, that will help you to improve your app performance. But use it only in case of static data.
Another thing instead of getting all data at once from service, try to get only the data that is required and will come in your use, this will also improve your app's performance. And also decrease the amount of internet data it uses.
Refer this for more details: https://heartbeat.fritz.ai/techniques-for-improving-performance-in-a-xamarin-forms-application-b439f2f04156
Also you can remove the images from app and use FontAwesome icons for that.
Hope this will help you in some or other way!

Xamarin.forms - Background color changes when activity is about to load

I have a activity with a listView that got items which drive us to another activity called Main Chat. The problem resides when I touch one of those items. Before it loads the respective activity, the background color of the main activity changes to green. I've inspected my code but I can't find any sample of code that does that type of behavior. Here's the video of what happen and the following code:
Video: https://files.fm/u/7nt2szdy#/view/20200213_115056.mp4;play
Sample code of the "click item"
async void OnListItemClicked(object o, ItemTappedEventArgs e)
{
try
{
((ListView)o).SelectedItem = null;
var vListItem = e.Item as Classes.ClassConversation.ResultadoConversation;
var getResposta = await Servicos.Servicos.Token(vListItem.institutionId);
if (getResposta)
await Navigation.PushAsync(new Chat.MainChat(vListItem, user2, true));
}
catch (Exception)
{
await DisplayAlert(Languages.AppResources.Notifications, Languages.AppResources.ErrorOccurred, "Ok");
}
}
Sample code of the Main Chat"
public MainChat (Classes.ClassConversation.ResultadoConversation conversation, Classes.ClassUser.Result user, bool Resposta)
{
InitializeComponent();
//Muda a cor do texto e o local da tab no android
UnselectedTabColor = Color.FromHex("#80FFFFFF");
SelectedTabColor = Color.White;
//Muda a cor do toolbar e texto
if (Resposta == true)
{
((NavigationPage)Xamarin.Forms.Application.Current.MainPage).BackgroundColor = (Color)App.Current.Resources["colorPrimary"];
((NavigationPage)Xamarin.Forms.Application.Current.MainPage).BarBackgroundColor = (Color)App.Current.Resources["colorPrimary"];
((NavigationPage)Xamarin.Forms.Application.Current.MainPage).BarTextColor = (Color)App.Current.Resources["white"];
}
if (conversation.OtherUser == null)
{
conversation.OtherUser = new Classes.ClassConversation.User();
if(conversation.user_From.rowKey == user.rowKey)
{
conversation.OtherUser = conversation.user_To;
}
else
{
conversation.OtherUser = conversation.user_From;
}
}
//Set Name and image of the other user and chat title
if (conversation.OtherUser.photoUri != null)
ImageUser.Source = new UriImageSource { CachingEnabled = true, Uri = conversation.OtherUser.photoUri, CacheValidity = new TimeSpan(800000, 0, 0, 0) };
TitleChat.Text = conversation.title;
NameOtherUser.Text = conversation.OtherUser.name;
if(Device.RuntimePlatform != Device.iOS)
Children.Add(new ChatPage(conversation, user));
else
Children.Add(new ChatPageIos(conversation, user));
Children.Add(new Report(conversation, user));
result = conversation;
}

Sending a post html request using iOS Swift not working

I have set up a payment system for my app through PayPal using both Android and IOS.
With the click of a button, the method 'payoutRequest' is called and sends the necessary information to PayPal through Firebase Functions.
The code I have works perfectly with Android but not so much with iOS.
Android's method: payoutRequest
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
ProgressDialog progress;
private void payoutRequest() {
progress = new ProgressDialog(this);
progress.setTitle("Processing your payout ...");
progress.setMessage("Please Wait .....");
progress.setCancelable(false);
progress.show();
// HTTP Request ....
final OkHttpClient client = new OkHttpClient();
// in json - we need variables for the hardcoded uid and Email
JSONObject postData = new JSONObject();
try {
postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
postData.put("email", mPayoutEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
// Request body ...
RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());
// Build Request ...
final Request request = new Request.Builder()
.url("https://us-central1-myapp.cloudfunctions.net/payout")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("Authorization", "Your Token")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// something went wrong right off the bat
progress.dismiss();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// response successful ....
// refers to response.status('200') or ('500')
int responseCode = response.code();
if (response.isSuccessful()) {
switch(responseCode) {
case 200:
Snackbar.make(findViewById(R.id.layout),
"Payout Successful!", Snackbar.LENGTH_LONG)
.show();
break;
case 500:
Snackbar.make(findViewById(R.id.layout),
"Error: no payout available", Snackbar
.LENGTH_LONG).show();
break;
default:
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
break;
}
} else {
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
}
progress.dismiss();
}
});
}
The above method sends the html request to PayPal through the Firebase Function created, see below (firebase function):
index.js - JavaScript file used with Firebase Functions**
'use strict';
const functions = require('firebase-functions');
const paypal = require('paypal-rest-sdk');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
paypal.configure({
mode: 'sandbox',
client_id: functions.config().paypal.client_id,
client_secret: functions.config().paypal.client_secret
})
exports.newRequest = functions.database.ref('/history/{pushId}').onCreate((snapshot, context) => {
var requestSnapshot = snapshot.val();
var price = snapshot.child('ridePrice').val();
var pushId = context.params.pushId;
return snapshot.ref.parent.child(pushId).child('price').set(price);
});
function getPayoutsPending(uid) {
return admin.database().ref('Users/Drivers/' + uid + '/history').once('value').then((snap) => {
if(snap === null){
throw new Error("profile doesn't exist");
}
var array = [];
if(snap.hasChildren()){
snap.forEach(element => {
if (element.val() === true) {
array.push(element.key);
}
});
}
return array;
}).catch((error) => {
return console.error(error);
});
}
function getPayoutsAmount(array) {
return admin.database().ref('history').once('value').then((snap) => {
var value = 0.0;
if(snap.hasChildren()){
snap.forEach(element => {
if(array.indexOf(element.key) > -1) {
if(element.child('price').val() !== null){
value += element.child('price').val();
}
}
});
return value;
}
return value;
}).catch((error) => {
return console.error(error);
});
}
function updatePaymentsPending(uid, paymentId) {
return admin.database().ref('Users/Drivers/' + uid + '/history').once('value').then((snap) => {
if(snap === null){
throw new Error("profile doesn't exist");
}
if(snap.hasChildren()){
snap.forEach(element => {
if(element.val() === true) {
admin.database().ref('Users/Drivers/' + uid + '/history/' + element.key).set( {
timestamp: admin.database.ServerValue.TIMESTAMP,
paymentId: paymentId
});
admin.database().ref('history/' + element.key + '/driverPaidOut').set(true);
}
});
}
return null;
}).catch((error) => {
return console.error(error);
});
}
exports.payout = functions.https.onRequest((request, response) => {
return getPayoutsPending(request.body.uid)
.then(array => getPayoutsAmount(array))
.then(value => {
var valueTrunc = parseFloat(Math.round((value * 0.75) * 100) / 100).toFixed(2);
const sender_batch_id = Math.random().toString(36).substring(9);
const sync_mode = 'false';
const payReq = JSON.stringify({
sender_batch_header: {
sender_batch_id: sender_batch_id,
email_subject: "You have a payment"
},
items: [
{
recipient_type: "EMAIL",
amount: {
value: valueTrunc,
currency: "CAD"
},
receiver: request.body.email,
note: "Thank you.",
sender_item_id: "Ryyde Payment"
}
]
});
return paypal.payout.create(payReq, sync_mode, (error, payout) => {
if (error) {
console.warn(error.response);
response.status('500').end();
throw error;
}
console.info("payout created");
console.info(payout);
return updatePaymentsPending(request.body.uid, sender_batch_id)
});
}).then(() => {
response.status('200').end();
return null;
}).catch(error => {
console.error(error);
});
});
When I run the above code in Android, it works and does all it should but the below method isn't working for IOS (same index.js file used for both platforms).
iOS's method: payoutRequest:
func payoutRequest() {
print("payoutRequest")
// Progress View
self.progress.progress = value
self.perform(#selector(updateProgressView), with: nil, afterDelay: 1.0)
let email = txtPayoutEmail.text!
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let params : Parameters = [
"uid": self.uid! as String,
"email": email
]
let headers : HTTPHeaders = [
"Content-Type": "application/json",
"Authorization": "Your Token",
"cache-control": "no-cache"
]
let myData = try? JSONSerialization.data(withJSONObject: params, options: [])
print("data: \(String(describing: myData))")
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData(completionHandler: { (response) in
//print("Request: \(String(describing: response.request))") // original url request
//print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
switch response.result {
case .success:
print("Validation Successful")
let parsedObject = try! JSONSerialization.jsonObject(with: myData!, options: .allowFragments)
print("parsed: \(parsedObject)")
case .failure(let error):
print(error)
}
})
}
Also the following url is not completely accurate for privacy concerns.
https://us-central1-myapp.cloudfunctions.net/payout (myapp) is not name of the app
I have narrowed down the issue to the actual method in iOS - payoutRequest is not sending the post html request as it should.
What could I be doing wrong?
EDIT
After running the code (payoutRequest()) below is the print() statement:
** name of app is blacked out **
Also, if I go to my PayPal developer account, go into the Dashboard and click on Notifications, I should get a notification for the following:
payment received in the main account (ok)
payment received from the riders email account (ok)
payment paid out to the driver (none)
mass payment to driver (none)
see:

Node.js- Comapring items from AWS DynamoDB- only lowercases

I want to get Items from my AWS DynamoDB, via Lambda, which satisfy condition:
if (typeof event.keyWord != "undefined") {
var str = event.keyWord;
str = str.toLowerCase();
params.ExpressionAttributeValues[":keyWord"] = {"S": str};
params.FilterExpression = "contains (#nm, :keyWord)";
}
I send string (keyWord) from my android app, then call toLowerCase function on it and compare it with #nm from DB. My question is, how can I call similar function (toLowerCase) on #nm before comparing them? My whole code:
var AWS = require('aws-sdk');
var db = new AWS.DynamoDB();
exports.handler = function(event, context) {
var params = {
TableName: "Events", //"StreamsLambdaTable",
// ProjectionExpression: "locationLat, locationLon",
ProjectionExpression: "ID, description, endDate, imagePath, locationLat, locationLon, #nm, #tp" //specifies the attributes you want in the scan result.
ExpressionAttributeNames: {
"#nm": "name",
"#tp": "type",
},
ExpressionAttributeValues: {
":lower_lon": {"N": event.low_lon},
":higher_lon": {"N": event.high_lon},
":lower_lat": {"N": event.low_lat},
":higher_lat": {"N": event.high_lat}
}
};
if (typeof event.keyWord != "undefined") {
var str = event.keyWord;
str = str.toLowerCase();
params.ExpressionAttributeValues[":keyWord"] = {"S": str};
params.FilterExpression = params.FilterExpression + " and contains (#nm, :keyWord)";
}
db.scan(params, function(err, data) {
if (err) {
console.log(err); // an error occurred
}
else {
data.Items.forEach(function(record) {
console.log(
record.name.S + "");
});
context.succeed(data.Items); // data.Items
}
});
};

JQM Click event doesn't work in Android Webview

I have an anchor which has three elements. Each element will has to respond for a click event.
I have this as and Android web view app.
Surprisingly click event works in android browser, but when I try that android webview app, nothing happens. Please refer the code below.
I don't know what I am missing so the click events doesn't work in android webview app.
$("#cont2 li a").live('click', function (e) {
//e.preventDefault();
this.blur();
var name = $(this).attr("name");
var staffid = $(this).attr("staffid");
var recordid = $(this).attr("recordid");
var primary = $(this).attr("primary");
if (name == "deletestaff") {
// delete sales staff
var dretVal = confirm("Delete contact staff " + $(this).attr("staffname") + "?");
if (dretVal == false) {
return false;
} else {
var txtprimaryrecordid = $("#txtprimaryrecordid").val();
var txtprimarystaffid = $("#txtprimarystaffid").val();
if (txtprimaryrecordid == 'undefined') {
txtprimaryrecordid = "";
}
if (txtprimarystaffid == 'undefined') {
txtprimarystaffid = "";
}
if (txtprimaryrecordid == recordid) {
$("#txtprimaryrecordid").val("");
}
if (txtprimarystaffid == staffid) {
$("#txtprimarystaffid").val("");
}
$(this).parents('li').remove();
// show deleted item
$('#staffs input[type=checkbox]').each(function () {
var delstaffid = $(this).attr("staffid");
if (staffid == delstaffid) {
$(this).attr("checked", false).checkboxradio("refresh");
}
});
}
}
Got it. Just had to implement WebChromeClient...
private class WebChromeClient extends WebChromeClient{
#Override
public boolean onJsAlert(WebView view, String url, String message,JsResult result)
{
Log.e("alert triggered", message);
return false;
}
}

Categories

Resources