Why can't I connect to an API when I generate the APK? - android

I have a problem with a login that I am doing, in my emulator it works correctly but when I generate the apk and test it on the phone, the API does not work.
I already assigned the Internet permission in the .xml and made tests to use Internet images and everything fine, so I discarded the permissions.
I do not know if it gives me an error because I use an http and not an https, or if someone has an idea of ​​what is happening here they tell me, I attach my code
Code:
void _login(BuildContext context) async {
if (!_loading) {
setState(() {
_loading = true;
});
}
//print(_username.value.text);
//print(_password.value.text);
var url = Uri.parse(
"http://taquillamedicina.mdgsystem.com/index.php?route=api/loginapp");
String var1 = 'vipmedico';
String var2 =
'xxxxx';
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
Map data = {
'username': var1,
'password': var2,
'usernameapp': _username.value.text,
'passwordapp': _password.value.text
};
var jsonResponse = null;
var response = await http.post(url, body: data);
//print(response);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
// print(jsonResponse);
if (jsonResponse != null) {
setState(() {
_loading = false;
});
sharedPreferences.setString("client_id", jsonResponse['client_id']);
if (jsonResponse['error'] == '1') {
Navigator.of(context).pushReplacementNamed("/list");
}
}
} else {
setState(() {
_loading = false;
});
print(response.body);
}
}

To get over this, you will have add android:usesCleartextTraffic="true" to your AndroidManifest.XML file. But as advised, this isn't solving th eproblem, it's sweeping it under the carpet, but will get your task done for now.

After I upgrade the Flutter 2.0 my app is down and I add under Anroid>Src>Main>AndroidManifest.xml
android:usesCleartextTraffic="true"
API and app is worked

Related

APIs won't load when published on Google Playstore

So this is my first time publishing a Flutter app to the Google Play Store. I wanted to create something simple so I could learn the entire process. So I created a simple Trivia App.
When I run the app from my phone or emulator (Android or iPhone) the free API that I'm using here loads the categories without any issues.
The issue I'm having is when I publish the app to the Play Store, the API doesn't load and I don't even get an error message. Just a blank screen.
Here is the API service call in my app:
static Future<List<Category>> fetchCategories() async {
const url = "https://opentdb.com/api_category.php";
var response;
try {
response = await http.get(url);
if (response.statusCode == 200) {
var jsonString = response.body;
final Map<String, dynamic> responseData = json.decode(jsonString);
var list = responseData['trivia_categories'] as List;
var _items = list.map((i) => Category.fromJson(i)).toList();
return _items;
} else {
return null;
}
} on Exception {
throw response.statusCode;
}
}
And this is the code in the controller that calls the API's method.
void fetchCategories() async {
// flag as loading.
isLoading(true);
try {
//get categories from API server
var categories = await ApiServices.fetchCategories();
if (categories != null) {
categories.forEach((Category categoryItem) async {
// adjust data accordingly
categoryItem.totalQuestions =
await fetchCategoryCount(categoryItem.id);
if (userDataController.data.read(categoryItem.id.toString()) !=
null) {
// get a list of answered questions from the device and count them
List<dynamic> correctAnswers =
userDataController.data.read(categoryItem.id.toString());
categoryItem.correctAnswers = correctAnswers.length;
} else {
categoryItem.correctAnswers = 0;
}
categoryTiles.add(categoryItem);
});
}
} on Exception catch (e) {
throw new Exception("An error occured fetching the data");
} finally {
isLoading(false);
}
}
Has anyone else ran into this issue?

Flutter String is in Future null

I want to use a string in this function that has the phone number of the device.
I get the phone number with this:
Future<void> initMobilNumberState() async {
if (!await MobileNumber.hasPhonePermission) {
await MobileNumber.requestPhonePermission;
return;
}
String mobileNumber = '';
try {
mobileNumber = await MobileNumber.mobileNumber;
_simCard = await MobileNumber.getSimCards;
} on PlatformException catch (e) {
debugPrint("Failed to get mobile number because of '${e.message}'");
}
if (!mounted) return;
setState(() {
var re = RegExp(r'\+[^]*');
_mobileNumber = mobileNumber.replaceRange(0, 3, ''.replaceAll(re, '+'));
});
}
My problem is that if I want to print _mobileNumber or use it in http.get I get null or a error with "Invalid Arguments"
Future<http.Response> _fetchSampleData() async {
String s = _mobileNumber;
print(s);
return http.get('http://test.php?TestPhone=' + _mobileNumber);
}
Future<void> getDataFromServer() async {
final response = await _fetchSampleData();
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
_list = data.values.toList();
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
showAlertNoInternet(context);
print('Failed to load data from server');
}
}
Where is my mistake?
The problem is that I want to call the phone number before it has even been fetched. So this always resulted in null. I fixed this by fetching the number when I start the app with all the other data I need.

Xamarin why it hangs on permissions enabling?

I done this according to Xamarin documentation, just copy-pasted a code.
So, in App.xaml.cs I have a code like this:
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart()
{
if (!CheckPermisions())
{
AbortApp(3, "Missing required permissions!");
return ;
}
}
//[...]
public bool CheckPermisions()
{
Task<bool> v = performCheckPermisions();
if (v.Result)
initAppFolders();
return v.Result;
}
protected async Task<bool> performCheckPermisions()
{
// storage read
PermissionStatus status = await Xamarin.Essentials.Permissions.CheckStatusAsync<Permissions.StorageRead>();
if (status == PermissionStatus.Denied)
{
this.Context.ToLogger(EAppLogLevel.Warning, string.Format(" ! StorageRead: requesting..."));
status = await Permissions.RequestAsync<Permissions.StorageRead>();
}
if (status == PermissionStatus.Denied)
return false;
// storage write
status = await Xamarin.Essentials.Permissions.CheckStatusAsync<Permissions.StorageWrite>();
if (status == PermissionStatus.Denied)
{
this.Context.ToLogger(EAppLogLevel.Warning, string.Format(" ! StorageWrite: requesting..."));
status = await Permissions.RequestAsync<Permissions.StorageWrite>();
}
if (status == PermissionStatus.Denied)
return false;
return true; // Task.FromResult(true);
}
The problem is - when application started 1st time, so when the OS asks user for permissions it always hangs! :-(
And I do not understand - why?!
How to resolve this problem with hanging on 1st app run?
I tried to debug it but it never returns from await Permissions.RequestAsync<...>() back into debugger! :-
Of course - on OS request I clicked [Allow] in a UI prompt.
Unfortunately, I'm not sure - why it is not returning, it might be bug in VS2019 debugger or it might be bug in Xamarin... or maybe I'm doing something wrong.
Could you please advice?
Please note: I need exactly the blocking/synchronous call to permissions request! Application must stop and confirm if permissions granted. Without permissions - it must not even try to run.
Note: VS 2019 (16.6.5); Xamarin.Forms 4.7.0.1142; Xamarin.Essentials 1.5.3.2 - so, it seems all the latest.
Thanks.
PS.
Also I tried following variants:
Attempt# 1
Task<bool> tsk = performCheckPermisions();
bool result = false;
if (tsk.IsCompleted)
{
this.Context.ToLogger(EAppLogLevel.Info, string.Format(" . CheckPermisions: task completed without waiting..."));
result = tsk.Result;
}
else
{
TaskAwaiter<bool> aw = tsk.GetAwaiter();
int counter = 0;
while (!aw.IsCompleted)
{
Thread.Sleep(330);
counter++;
if ((counter % 10) == 0)
this.Context.ToLogger(EAppLogLevel.Info, string.Format(" . CheckPermisions: still waiting (#{0})...", counter));
if (counter > 100)
{
AbortApp(99, "Permissions were not comfirmed!");
return false;
}
}
result = aw.GetResult();
}
It simply hang because nor tsk.IsCompleted, nor aw.IsCompleted never became true despite user clicks to [Allow] button.
Attempt# 2
var task = Task.Run(async () => await performCheckPermisions());
if (task.IsFaulted && task.Exception != null)
{
throw task.Exception;
}
bool result = task.Result;
this.Context.ToLogger(EAppLogLevel.Info, string.Format(" ? CheckPermisions: {0}", result));
It reported System.AggregateException exception: Message=One or more errors occurred. (Permission request must be invoked on main thread.); Source=mscorlib.
Attempt# 3
bool result = false;
this.isCompleted = false;
MainThread.BeginInvokeOnMainThread(
async () => {
result = await performCheckPermisions();
this.isCompleted = true;
}
);
int counter = 0;
while (!this.isCompleted)
{
Thread.Sleep(330);
counter++;
if ((counter % 10) == 0)
this.Context.ToLogger(EAppLogLevel.Info, string.Format(" . CheckPermisions: still waiting (#{0})...", counter));
if (counter > 100)
{
AbortApp(99, "Permissions were not comfirmed within specified timeout!");
return false;
}
}
It simply hang. It seems there is bug in Xamarin - the await Permissions.RequestAsync<>() call never return back to application!
Below is the edited code. If you saw an earlier version then you saw it had problems. First entry so am new at this. *
I tried many things to get the permissions but it always hung the App, even with the awaits.
I wanted to put the permission requests as close to where the user required them (As recommended) and not abort the App. This is what I finally came up with:
Creating a permission interface in the Xamarin Forms project
Creating an Android implementation of the permissions in the Xamarin Forms Android project
Registered permission as dependency service in the Android Activity before loading the Forms App
In my WIFI Content page I created an async method that checks permission by calling the registered Dependency service
When I click on WIFI page scan button, it calls the async method to see if the user needs to give permission before continuing
Works like a charm.
The only caveat is that if the user selects 'Don't ask again' he will have to set location services manually. Not sure how I can tell the user since the permissions always only return Denied status. He will get a dialog informing him of insufficient permissions but no OS dialog allowing him to request permissions (Duh, because he said that that he did not want to see them)
The permissions Interface in the Xamarin Forms project
public interface ILocationWhileInUsePermission {
Task<PermissionStatus> CheckStatusAsync();
Task<PermissionStatus> RequestAsync();
}
Implementation on Xamarin Forms Android side
public class LocationWhileInUsePermission : Xamarin.Essentials.Permissions.BasePlatformPermission, ILocationWhileInUsePermission {
public override (string androidPermission, bool isRuntime)[]
RequiredPermissions => new List<(string androidPermission, bool isRuntime)> {
(Android.Manifest.Permission.AccessFineLocation, true),
(Android.Manifest.Permission.AccessCoarseLocation, true),
(Android.Manifest.Permission.AccessWifiState, true),
(Android.Manifest.Permission.ChangeWifiState, true)
}.ToArray();
}
Register in the Activity.cs OnCreate before load of the App
DependencyService.Register<ILocationWhileInUsePermission, LocationWhileInUsePermission>();
LoadApplication(new App(DI.Wrapper));
In the Wifi Page create functions to invoke permissions from DependencyService and to set results
private bool permissionsGranted = false;
private async Task SetAreGranted(bool granted) {
await Task.Run(() => this.permissionsGranted = granted);
}
public async Task<bool> GetIsGranted() {
return await Task<bool>.Run(() => { return this.permissionsGranted; });
}
public async Task<bool> ChkWifiPermissions() {
try {
await this.SetAreGranted(false);
var wifiPermissions =
DependencyService.Get<ILocationWhileInUsePermission>();
var status = await wifiPermissions.CheckStatusAsync();
if (status != PermissionStatus.Granted) {
status = await wifiPermissions.RequestAsync();
if (status != PermissionStatus.Granted) {
return await this.GetIsGranted();
}
}
await this.SetAreGranted(true);
}
catch (Exception) {
return await this.GetIsGranted();
}
return await this.GetIsGranted();
}
On my WIFI Content Page, on the button click event I call the async method
private void btnDiscover_Clicked(object sender, EventArgs e) {
Device.BeginInvokeOnMainThread(async () => {
if (await this.ChkWifiPermissions()) {
this.btnSelect.IsVisible = false;
this.ResetWifiList(new List<WifiNetworkInfo>());
this.activity.IsRunning = true;
App.Wrapper.WifiDiscoverAsync();
}
else {
this.OnErr("Insufficient permissions to continue");
}
});
}
Just to add a variance to my WIFI permissions check on WIFI scan button, here is a variance that aborts on App start. It works but I prefer the one that requests closer to the usage of the permission.
This works and never hangs the App. Still the problem if the user has requested not to be asked again.
Start by declaring service interfaces in the Xamarin Forms project to close the App, and another to check and request permissions
public interface ICloseApplication {
void CloseApp();
}
public interface ILocationWhileInUsePermission {
Task<PermissionStatus> CheckStatusAsync();
Task<PermissionStatus> RequestAsync();
}
Then add Android OS implmentations in the Xamarin Forms Android project
public class AndroidCloseApp : ICloseApplication {
public void CloseApp() {
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
}
}
public class LocationWhileInUsePermission : Xamarin.Essentials.Permissions.BasePlatformPermission, ILocationWhileInUsePermission {
public override (string androidPermission, bool isRuntime)[]
RequiredPermissions => new List<(string androidPermission, bool isRuntime)> {
(Android.Manifest.Permission.AccessFineLocation, true),
(Android.Manifest.Permission.AccessCoarseLocation, true),
(Android.Manifest.Permission.AccessWifiState, true),
(Android.Manifest.Permission.ChangeWifiState, true)
}.ToArray();
}
Register the Services in the Xamarin Forms Android project MainActivity.OnCreate(). BTW, the DI.Wrapper has the results from my dependency injector, with common and OS specific code
DependencyService.Register<ILocationWhileInUsePermission, LocationWhileInUsePermission>();
DependencyService.Register<ICloseApplication, AndroidCloseApp>();
LoadApplication(new App(DI.Wrapper));
Then in the Xamarin Forms project, in the App.OnStart() override method call an async method to request permissions and abort if necessary
protected override void OnStart() {
// This will abort the app at the start if the WIFI permissions are not given
Device.BeginInvokeOnMainThread(async () => {
if (!await this.CheckPermissions()) {
ICloseApplication closeApp = DependencyService.Get<ICloseApplication>();
await Application.Current.MainPage.DisplayAlert(
App.GetText(MsgCode.Error),
"Insufficient permissions",
App.GetText(MsgCode.Ok));
closeApp.CloseApp();
}
});
}
private async Task<bool> CheckPermissions() {
ILocationWhileInUsePermission wifiPermissions =
DependencyService.Get<ILocationWhileInUsePermission>();
PermissionStatus status = await wifiPermissions.CheckStatusAsync();
if (status != PermissionStatus.Granted) {
status = await wifiPermissions.RequestAsync();
}
return status == PermissionStatus.Granted;
}
As Cheesebaron mentioned, you always want to use await when dealing with a Task. You can modify your example like so:
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
protected override async void OnStart()
{
bool result = await CheckPermisions()
if (!result)
{
AbortApp(3, "Missing required permissions!");
return ;
}
}
//[...]
public async Task<bool> CheckPermisions()
{
bool v = await performCheckPermisions();
if (v)
initAppFolders();
return v;
}
protected async Task<bool> performCheckPermisions()
{
// storage read
PermissionStatus status = await Xamarin.Essentials.Permissions.CheckStatusAsync<Permissions.StorageRead>();
if (status == PermissionStatus.Denied)
{
this.Context.ToLogger(EAppLogLevel.Warning, string.Format(" ! StorageRead: requesting..."));
status = await Permissions.RequestAsync<Permissions.StorageRead>();
}
if (status == PermissionStatus.Denied)
return false;
// storage write
status = await Xamarin.Essentials.Permissions.CheckStatusAsync<Permissions.StorageWrite>();
if (status == PermissionStatus.Denied)
{
this.Context.ToLogger(EAppLogLevel.Warning, string.Format(" ! StorageWrite: requesting..."));
status = await Permissions.RequestAsync<Permissions.StorageWrite>();
}
if (status == PermissionStatus.Denied)
return false;
return true; // Task.FromResult(true);
}
}

React Native AsyncStorage stops working once app is offline

I have a relatively simple app (my first) that needs to display information that is retrieved from a GraphQL query and then stored in AsyncStorage. Everything works fine until you turnoff data/Wifi connections and relaunch the app - it will not load the same local data it did when networking is on. This is the same on a physical or emulated Android device.
There are no data calls except when the user initially sets their details. The app is built with version 2.7.1 of Expo & AWS Amplify. I have wasted several days with this final issue and gotten the same behaviour with Expo SecureStore & Amplify Cache and am loath to go down the route of learning and including Redux on such a simple app...
//import from react native not react
import { AsyncStorage } from 'react-native'
//calling a function as app loads
componentDidMount() {
this._loadInitialState();
}
//retrieving String from AsyncStorage
_loadInitialState = async () => {
try {
const policyNum = await AsyncStorage.getItem('policyNum')
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.state.policyNumSet = true
try {
await AsyncStorage.setItem('policyNum', policyNumber)
} catch (err) {
//...
}
}
}
You are using badly the fact of change the state.
Where you do this:
this.state.policyNumSet = true
You should change the state with the setState() function like this:
this.setState({ policyNumSet: true })
This was a conflict with an external API
Are you storing a string? asyncstorage only can store strings . try using JSON.stringify and JSON.parse
_loadInitialState = async () => {
try {
var policyNum = await AsyncStorage.getItem('policyNum')
policyNum = JSON.parse(policyNum) // converting to original
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.setState({ policyNumSet: true })
try {
var policyNumberString = JSON.stringify(policyNumber)
await AsyncStorage.setItem('policyNum', policyNumberString) //converting to string
} catch (err) {
//...
}
}
}

React native debug logging stucks

I have a link in the back-end, so I fetch a post request to that link and receive a response. When I alert that response it gives a body init and body text in which I receive datas I need. Everything is good. But..
When I enable remote debugging and console.log that response, it gives body init and body blob (and both are empty). It stucks when I eneble debugging..
Thanks for attention ))
My code:
logIn = async (username, password) => {
// alert(`username : ${username}\n password : ${password}`);
let loginFormData = new FormData();
loginFormData.append('LoginForm[username]', username);
loginFormData.append('LoginForm[password]', password);
loginFormData.append('MacAddress', '111');
loginFormData.append('loginType', 'mobile');
try {
fetch('http://192.168.2.115/araqich_client/general/default/logout', {
method: 'POST',
body: loginFormData
});
let request = fetch('http://192.168.2.115/araqich_client/general/default/login', {
method: 'POST',
body: loginFormData
});
let loginResponseJson = await request;
if (loginResponseJson && loginResponseJson != null ) {
// let loginResponse = JSON.parse(loginResponseJson._bodyInit);
alert(JSON.stringify(loginResponseJson._bodyInit));
let status = loginResponse.status;
if (status) {
let SyncFormData = new FormData();
let accessToken = loginResponse.ACCESS_TOKEN;
SyncFormData.append('ACCESS_TOKEN', accessToken);
SyncFormData.append('MacAddress', '111');
SyncFormData.append('loginType', 'mobile');
let syncRequest = fetch('http://192.168.2.115/araqich_client/mobile/defaultA/syncAndroid', {
method: 'POST',
body: SyncFormData
});
let syncResponseJson = await syncRequest;
if (syncResponseJson && syncResponseJson != null) {
let syncResponse = JSON.parse(syncResponseJson._bodyInit);
let status = syncResponse.status;
if (!status) {
alert('Sorry(( something went wrong...');
} else {
alert('Life is good)))');
}
}
} else {
alert('else1')
}
} else {
alert('else')
}
} catch (error) {
alert(error);
}
}
Instead of using console.log statements, I'd advise using your debugger.

Categories

Resources