Retrofit not returning any response - android

I am trying to use RetroFit Synchronus call to connect and fetch data to one of my APIs.
try{
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(finalUri.toString()).build();
IGooglePlacesApi iGPlaceApi = restAdapter.create(IGooglePlacesApi.class);
mGooglePlacesApiResponse googlePlacesObj = iGPlaceApi.getStreams();
RetrofitError retrofitError;
} catch (IOException e) {
serverResponse = e.getMessage();
} catch (IllegalArgumentException e) {
serverResponse = e.getMessage();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Log.d("serverResponse:", serverResponse);
}
Which is declared here as:
public interface IGooglePlacesApi {
#GET("/stream/list.json")
mGooglePlacesApiResponse getStreams();
}
Issue is when i call iGPlaceApi.getStreams(); i dont get a result neither any error. But my code just directly goes to the finally block?
Why this is happening, no result, no catch. How can i correct this?

Retrofit wraps all internal exceptions into a RetrofitError exception and throws that. In your case you're not catching that exception therefore only the finally block is executed.
Try modifying your code this way,
try {
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(finalUri.toString()).build();
IGooglePlacesApi iGPlaceApi = restAdapter.create(IGooglePlacesApi.class);
mGooglePlacesApiResponse googlePlacesObj = iGPlaceApi.getStreams();
} catch (RetrofitError e) {
serverResponse = e.getMessage();
} finally {
Log.d("serverResponse:", serverResponse);
}
The RetrofitError thrown depending on the failure will contain the exception cause or the status reported by the server. You can then apply the necessary logic from there.
For more general purposes error handling you can set an ErrorHandler when creating your RestAdapter. This ErrorHandler will be executed before you catch the RetrofitError in your try/catch.

Related

is it possible to catch Exception in Android?

Recently I modified my Android code for Android-12.
I was not having android-12 related bluetooth connect permissions for my API. So I handled as below :
public List<BluetoothDevice> getHfpDevices() {
List<BluetoothDevice> hfpConnectedDevs = new ArrayList<>();
try {
if (mHeadsetService != null) {
hfpConnectedDevs = mHeadsetService.getConnectedDevices();
}
} catch (SecurityException ex) {
Log.e(TAG, "Security Exception in Android-12", ex);
}
return hfpConnectedDevs;
}
Does this catch the securityException thrown when this API is accessed ? or do I need to handle the Exception itself ?
catch (Exception ex) {
PS : I don't want to add the requestPermission flow as of now. I just need to solve the exception raised when this API is called

how to implement smack for xmpp

I'm trying to have my android app to be able to send and receive xmpp message using smack but it does not work and the connect command does not return. I have seen several code example but Smack has new versions and the syntax has changed so I might be doing something wrong :
in my build.graddle file I use :
compile "org.igniterealtime.smack:smack-android-extensions:4.3.0"
compile "org.igniterealtime.smack:smack-tcp:4.3.0"
I'm trying to send a message from myaccount321#xabber.org to myaccount456#xabber.org
I'm trying to connect using hot-chilli.net (Idon't mind using some other server))
everything seems to go well until connection.connect() after which the script does not return without triggering any exception.
Please tell me what I'm doing wrong
TIA
public void sendxmpp(){
XMPPTCPConnectionConfiguration config = null;
try {
XMPPTCPConnectionConfiguration.Builder configbuilder = XMPPTCPConnectionConfiguration.builder();
configbuilder.setUsernameAndPassword("myaccount321","myaccount321pw");
DomainBareJid serviceName = JidCreate.domainBareFrom("hot-chilli.net");
configbuilder.setServiceName(serviceName);
configbuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
configbuilder.setHost("jabber.hot-chilli.net");
configbuilder.setPort(8222);
config=configbuilder.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect();
}
catch (SmackException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (XMPPException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
connection.login();
ChatManager chatManager = ChatManager.getInstanceFor(connection);
EntityBareJid jid = JidCreate.entityBareFrom("myaccount321pw#xabber.org");
Chat chat = chatManager.createChat(jid);
chat.sendMessage("Hello");
}
catch (Exception e) {
}
}
OK I got it, the connection process has to be done in its own thread.

Ad SDKs can't seem to get the Advertising info from the device

This is what we see from Mopub and other ad networks:
java.io.IOException: Connection failure
com.google.android.gms.ads.identifier.AdvertisingIdClient.g(Unknown
Source)
com.google.android.gms.ads.identifier.AdvertisingIdClient.getAdvertisingIdInfo(Unknown
Source)
They all seem to have the same problem.
The weird thing is that we have no problem getting the advertising id from our app whatsoever with the following source. We get the right advertising id and we have no error logs.
All the SDKs are hitting the same issue (Connection failure).
Any help appreciated.
private void getAdvertisingId(AdvertisingIdHolder receiver) {
AdvertisingIdClient.Info adInfo = null;
String id = null;
boolean isLAT = false;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(App.getCtx());
id = adInfo.getId();
isLAT = adInfo.isLimitAdTrackingEnabled();
} catch (IOException e) {
SLog.e("error", e);
// Unrecoverable error connecting to Google Play services (e.g.,
// the old version of the service doesn't support getting AdvertisingId).
} catch (GooglePlayServicesNotAvailableException e) {
SLog.e("error", e);
// Google Play services is not available entirely.
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
}
receiver.receive(id, isLAT);
}
I went through trials and errors these days on getting advertising id. Finally I got it!
The connection error can be solved if we pass in getApplicationContext() instead of the context of current activity. Below is my working code:
private void getGaid() {
new Thread(new Runnable() {
#Override
public void run() {
try {
String gaid = AdvertisingIdClient.getAdvertisingIdInfo(
getApplicationContext()).getId();
if (gaid != null) {
Log.d("DEBUG", gaid);
// gaid get!
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}).start();
}
getGaid() can be put in onCreate(), onResume(), or onClick() of a view, as long as the thread is called by the main ui thread.
Another thing you may need is to update google play services library to latest version. As the official document here mentioned, IOException is probably caused because the old version of the service doesn't support getting AdvertisingId.
Feel free to comment if there is any other questions.

Android application is freezed - Socket Exception

I made android application that connects to remote server and send some data.
Remote server is Windows application.
Connection method:
private void ConnectToMonitor() {
try {
s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This works perfectly if server is online. Application is sending data and server is receiving. But if server is offline android app. is blocked. My question is how to handle this? How to continue with application and avoid error even the server is down?
Remember to call this outside the UIThread.
Follow this tutorial. In android all connections need to be managed outside the UIThread, in the tutorial I linked you will find easy ways to post your results back to the UI (handlers, asynctasks...)
Of course we don't know if the problem is about the thread with just the given code, but it is the most usual error.
First remember to set the socket timeout :
mSocket.setSoTimeout(timeout); //in milliseconds
You can however specify different timeout for connection and for all other I/O operations through the socket:
private void connectToMonitor() {
try {
socket = new Socket();
InetAddress[] iNetAddress = InetAddress.getAllByName(SERVER_ADDRESS);
SocketAddress address = new InetSocketAddress(iNetAddress[0], TCP_SERVER_PORT);
socket.setSoTimeout(10000); //timeout for all other I/O operations, 10s for example
socket.connect(address, 20000); //timeout for attempting connection, 20 s
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Second, in Android, you should perform any network I/O in separate threads!
As an example, using regular Java Threads :
String threadName = getClass().getName() + "::connect";
new Thread(new Runnable() {
#Override
public void run() {
connectToMonitor();
}
}, threadName).start();
You can set A timeout for the socket. Use Socket.setSoTimeout method
socket.setSoTimeout(timesinmilis);
by using this your socket will throw a socket timout exception. You can catch that and do what you want

Why am I getting warnings Serialize ArrayList

I'm getting odd warnings in my reading of a ArrayList of Serializable objects. Here is the code:
public void loadBoard() {
FileInputStream fis = null;
ObjectInputStream is;
try {
fis = this.openFileInput(saveFile);
is = new ObjectInputStream(fis);
// Build up sample vision board
if (mVisionBoard == null) {
mVisionBoard = new ArrayList<VisionObject>();
} else {
mVisionBoard.clear();
}
ArrayList<VisionObject> readObject = (ArrayList<VisionObject>) is.readObject();
mVisionBoard = readObject;
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (StreamCorruptedException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
}
}
and the warning I'm getting is (on readObject line):
"Type safety: unchecked cast from Object to ArrayList"
The few examples I've read indicate that this is the correct code for reading an ArrayList of serializable objects. The code I made to write the arraylist isn't giving me any warnings. Am I doing something wrong here?
kind of late but it will help someone...
the reason of the warning is because of the return of the method readObject...
see:
public final Object readObject()
it returns actually an object
and if you just by mistake read and deserialize a lets say String object ant try to cast that into an array list then you will get a runtime execption (the reason must be obvious)
in order to avoid that predictable failure you can check the type of the returned object before the cast...
that is why you get the warning:
"Type safety: unchecked cast from Object to ArrayList<VisionObject>"

Categories

Resources