React Native App crashes on Network error - android

I am developing one document upload app, using react native.
Documents get uploaded if the network is good, but suddenly the app crashes if the network goes down.
For instance - If I am uploading the documents on 4G network then i receive success from API but if the network speed suddenly goes down to 2G network i.e. 20KB/S then I get "NETWORK REQUEST FAILED / NETWORK ERROR" and the app crashes.
I have handled the error using catch block, but still the app crashes, what should I do to avoid this crashing even if the network is not available or if the speed goes down ?
Below is my code -
try{
var form = FormData();
form.append("user_id",this.state.userId);
form.append('file', {
uri: this.state.path,
type: 'image/jpg',
name: 'image.jpg',
});
axios({
method:"POST",
url:"http://xxxxx/xxxx",
timeout:50000,
data:form
})
.then(response => console.log(response))
.catch(error=>console.log(error));
}
catch(error){
console.log(error);
ToastAndroid.show("Internal error, please try again");
}
Note - I have used react-native-image-picker, as the document can be captured using camera OR it could be uploaded from the existing file present in the device.
Also have added all permissions in Manifest file for internet access.
Please help

Thats an Exception. I guess you need to catch the Exception
BadNetwork or Timeout You need to Catch it and App should not Crash just make sure
In the Catch You need to Show the Dialog box which says Can't connect to server.
OR You need to check if you have a Network connection then only Let the user send the Request show Non-cancelable Dialogbox
Hope that helps .

Related

Android app can not connect to internet, but other apps are fine

I have an app for android created with kotlin.
In general, it works fine. But one user reports he can not login and error is like no internet connection.
However, he says connection is fine. He can open api endpoint with the browser on same device .
What can be the reason for this?
The app has manifest record for network permissions. For other users it works fine
As you don't have given much information, I can give you some points to check:
Network permission in manifest file (that is already done).
Run time permission for Android 6.0 and above.
check if you done something like this code.
try{
//network code
}
catch(Exception e){
DialogBOXSHOW("Network error");
}
because Exception here can catch any type of error even NullPointerException

How to solve SocketException: Failed host lookup: 'www.xyz.com' (OS Error: No address associated with hostname, errno = 7)

Whenever I try to do an http call after about 20 seconds I get in the console the following error:
E/flutter ( 8274): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 8274): SocketException: Failed host lookup: 'flutter-project-xxxxx.firebaseio.com' (OS Error: No address associated with hostname, errno = 7)
This error happens for every method and every route I call through the app http package.
I'm developing a flutter app on Windows, using an AVD virtual device from Android Studio.
Versions:
http: ^0.12.0+1
flutter: 1.0
Cases:
From home or though tethering from my phone:
connectivity works fine on every part of the virtual device
From my work network (behind the firewall):
Only with Android Web View, I can browse the internet without any problem (i can even call the same url, I use in the code and it works).
I get a connection error when using any other application (Chrome, Google Play, ecc...) in the virtual device, and specifically the "SocketException", when testing my app.
What is the difference between the calls coming from that app?
Is there a way to route my app calls the same way as the ones in the webview?
Thanks!
Adding internet permission is not only a solution.
You also have to make sure that you are online whether it is mobile or emulator
Make sure you are online whether it is mobile or emulator
Make sure you have given internet permission in your app's android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Add <uses-permission android:name="android.permission.INTERNET" /> to your AndroidManifest.xml file.
I added <uses-permission android:name="android.permission.INTERNET" /> to
my manifest. I then had to restart the emulator for internet to work.
Make sure you have added the in android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
If you are using an emulator make sure that the mobile data is active
You should try following:
Try run application in debug mode if its working fine and not working in release mode then it might be related to permission issue so add permissions(INTERNET, ACCESS_NETWORK_STATE) in manifest file.
your_project_root_directory/android/app/src/debug/AndroidManifest.xml
your_project_root_directory/android/app/src/main/AndroidManifest.xml
your_project_root_directory/android/app/src/profile/AndroidManifest.xml
If not included then add permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If its not working in debug mode, then check either your url is correct by hitting in postman. If its working in postman then you should execute your webservice in this way:
Add dependency in pubspec.yaml:
dependencies:
flutter:
sdk: flutter
http: 0.13.3
After adding http:0.13.3 then click on Pub get button If its executed with code 0 then it means its successfully added to your project.
in your dart file import http.dart:
import 'package:http/http.dart';
Now write this code to execute webservice:
var url = Uri.parse('some-url-login?username=abc&&password=xyz');
var response = await get(url, headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods':
'GET,PUT,POST,DELETE'
});
if (response.statusCode == 200) {
// success
} else if(response.statusCode == 404){
// not found
} else if(response.statusCode == 500){
// server not responding.
} else {
// some other error or might be CORS policy error. you can add your url in CORS policy.
}
I hope it will help you. Chill!
Go for AVD manager, then choose your emulator, on Actions menu click down option sign, then choose wipe data, then restart your emulator. It works for me.
Even I had the same issue. I restarted my emulator and it worked!!
If you are getting this error while using the flutter_socket_io plugin, don't forget to initialize the socket i.e socketIO.init(); socketIO.connect(); before attempting to subscribe to it. I received the same error as that indicated above when I omitted it.
By enabling WIFI it works for me, and make sure you also added the internet permission in the android manifest it added automatically also but you have to make sure. if still not then invalidate caches and restart hope it works
In my case it was because my phone was not connected to internet
Just enable internet connexion
Make sure your Mobile device or Emulator is connected to the internet
In My case I opened the emulator before I connected to the WIFI to system.When network(WIFI) has connected to my system but unable to connect to emulator .
Due to no internet access to the Emulator,this issues occurs.I resolved this issues by this way.
Solutions:
Connected network access to the system then I Closed the emulator and re-open it. Install applications ,run application and open it .And Finally works every API works fine.
When i enabled wifi on my device, it worked fine.
Even after adding
<uses-permission android:name="android.permission.INTERNET"/>
in your android/app/src/main/AndroidManifest.xml, if you're still finding trouble then
There maybe an error with the website's server IP address like:
Server IP address could not be found
It's better to wait for some time and make sure to restart wifi, it worked for me.
Make sure your Emulator or your device connected to the internet.
if your Emulator could not connect to the internet use a VPN.
The problem for me was that I was using a VPN. The emulator didn't have internet access when connected to the VPN on my computer. It might help someone.
I'm using arch Linux.
Linux arch 5.14.7-arch1-1
And Flutter version
Flutter 2.2.1
Dart version
Dart 2.13.1
Code editor
1.58.0
In my case turning on wifi solved the problem.
Check if the wifi is connected or not. Mine worked after restarting the wifi.
Make sure the internet is on (both on the phone and the PC)
also, make sure the server is working properly
check your URL properly
Sometimes, other wifi can have interference with your connected wifi, which can cause this error as well. Try to set your connected wifi's channel to auto or away from other wifi's channels.
I had the same problem while running the app on an emulator.
My laptop was connected to the internet through my phone's mobile hotspot.
But apparently the emulator was unable to access the internet
Later, I switched to my Wi-Fi Router connection and the application proceeded smoothly as expected.
I'm not sure, but is there any special access to be granted?
Tip: Try googling something on the emulator to check internet connectivity
For me it was just bad url with function "Uri.https(...)" in Flutter.
Check if the address is correct with your browser
The DNS settings on my mac were invalid...just use 8.8.8.8 without any internal DNS routing addresses
The problem is basically coming when device is trying to access any internet resources,to fix add the
to AndroidManifest.xml file #android/app/src location.
Check if you have enabled offline work in the gradle settings.
File-> Settings -> Build -> Build Tools -> Offline work
If its enabled or checked then uncheck it.
Also, might good to look at the 'Proxy settings' inside the 'Extended controls' of the emulator.
The way it worked for me was to change to use the 'No Proxy' setting.
Double-check / make sure you have
<uses-permission android:name="android.permission.INTERNET" />
in your app's android/app/src/main/AndroidManifest.xml
if you're using vscode you would get gai_error=0 that's if the http is connected successfully
Here is the right place to place the internet permission because it was quite challenging to know the location
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.appName">
<uses-permission android:name="android.permission.INTERNET" />
run the flutter run command on cmd or visual studio code terminal
I deliberately disconnected my emulator wifi to see what would happen (as there could be cases where no internet is available). The error led me here, but, all I see are workarounds and not error handling. Really, the app should be able to handle the error gracefully and not crash out because of a lack of connection.
So far, all I have done is to catch the error and if the return code is -1 (or anything other than a 200), I know I have a problem and can make the app respond appropriately.
var request = new http.MultipartRequest("POST", uri);
// multipart that takes file
var multipartFile = new http.MultipartFile('file', stream, length,
filename: fileToUpload.path);
// add file to multipart
request.files.add(multipartFile);
// send
try {
var response = await request.send();
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
return response.statusCode;
}
catch (e)
{
return -1;
}

Android: Nearby api, No Connection

I am attempting to get Google Nearby API working on my handset (an s5).
I am building and running the stock project from github Google Nearby API GIT.
The app builds and runs, with no errors. Having exported the app onto two S5s (amongst other handsets I have attempted to test it with) and connecting to a WLAN from a D-Link DSL-3680. Multicasting is enabled and set to v3.
However the app refuses to connect with the neighbouring phone when corresponding 'advertise' and 'discover' instructions have been given.
Is there an effective way in which to debug this behaviour? If I can provide an effective information dump of information that might help someone identify the issue then please let me know how.
What do you mean by 'refuse to connect'?
are you getting connection status- 'Rejected'?
If you are able to advertise and discover other devices, I'm assuming all your base conditions (like connected to local network) are fulfilled
Now,
You can try logging your status in Connection call back when you try to connect
Nearby.Connections.sendConnectionRequest(mGoogleApiClient, myName,
remoteEndpointId, myPayload, new Connections.ConnectionResponseCallback() {//response conditions}
using--
inside connection callback function write
if(status.isSuccess()){
// Successful connection
} else {
// Failed connection
}
similarly, if you are not doing this, you need to accept the connection request
Nearby.Connections.acceptConnectionRequest(mGoogleApiClient, remoteEndpointId, myPayload, this)
and inside Onresult callback add-
if(status.isSuccess()){
// Successful connection
} else {
// Failed connection
}
Hope it helped

Getting socket.io working with phone gap

I have come across many posts on here and various other sites about how to get socket.io working in an android phonegap app, unfortunately I still seem to be having problems. If you've had any experience of getting this kind of thing set up, any pointers you could give would be greatly appreciated, having now spent several days tearing my hair out :P
So to get started I have a very simple socket.io server setup and running on my local machine:
var server = require('http').createServer();
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
console.log('socket connected');
socket.on('disconnect', function () {
console.log('socket disconnected');
});
socket.emit('text', 'wow. such event. very real time.');
});
server.listen(3000);
which I got from one of the tutorials that I found, and it seems to work ok.
Now in my phonegap app all the code I have is as follows:
var app = angular.module("MyApp", [
"MyCtrl"
]);
app.controller("AppCtrl", ["$scope", function ($scope) {
console.log("About to attempt a connection (" + socket + ")!");
var socket = io("10.0.5.159:3000");
socket.on("connect", function(data) {
console.log("Connected: " + data);
});
socket.on("error", function(err) {
console.log("Error: " + err);
});
}]);
Just a basic angular.js app with a single controller that attempts to connect to the server (the ip address provided is the correct one on my local network). My log gets hit so I know this code is executed, but I never get a connect event or an error event, and no errors come up in the console, it just seems to fail silently. I also get no connection event on the server.
As per another stackoverflow post I have ensured that my config.xml contains the appropriate
<access origin="10.0.5.159*" />
entry. But I still seem to be getting nowhere with it. The same line of code
var socket = io("10.0.5.159:3000");
when executed in a safari browser window works exactly as expected and my server logs a connection event, so I'm confident that the server and the connect code are valid.
Any ideas what I might be doing wrong?
Your code is not working because on the server side u have emit "text" event therefore on client side your are supposed to write socket.on("text")
On server side you haven't emit "connect" and "error" events then how you are supposed to get these events on client side. And I don't think that normal socket.js works with Angular js, You have to add Angular.js socket.io library.

Exception message not displayed

I have written an Android application in which I allow the user to select an image from the gallery and post it to an Internet server as a Base64 encoded String using HTTP REST-ful web-services upon click of a button.
When the server is up/ running and the phone has a good 3G connection, it works fine. However, if the phone has a bad connection or if the server is down for some reason, then the Android application crashes altogether (screen goes black and application quits).
Although I’ve given a catch block to catch any IO/ other exceptions, the catch block code doesn’t execute if there is an error while executing connection.connect () ; I have tried catching Throwable as well to no avail – the code in the catch block never executes and the application itself stops working.
Can somebody please help me in figuring out how to catch these exceptions which are occurring when the server is not reachable or if there is an error while transmitting the image?
if you check (ex as Exception) instead of IOException, maybe it helps

Categories

Resources