Android New relic track non Network error - android

are there any way to track handled errors on New Relic?
Documentation says that we can track with
NewRelic.noticeNetworkFailure(...)
however I've tried to track errors which aren't from any network call and with a fake URL but I got this:
'java.lang.String com.newrelic.agent.android.api.common.TransactionData.getUrl()' on a null object reference
Other platforms like JAVA have this
NewRelic.noticeError(e);
but the android platform does not have a method to notice a simple error.
do you know how we can send handled errors?

At the end, there is way to track an error however it won't appear in you crashList.
The notice methods that New Relic has allow you to notice error. With a method like the below one you can send a notice that will appear in your Network --> error page
public static void reportLoggedException(String message, Throwable tr) {
long time = new Date().getTime();
try {
if (message.isEmpty()) {
message = "none";
}
NewRelic.noticeNetworkFailure("http://" + URLEncoder.encode(message, "utf-8")+".com", "GET", time, time, new Exception(tr));
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Confused about handling errors and exceptions in RxJava

I'm just starting to learn RxJava and I've read and watched quite a few tutorials, but some things are not clicking just yet. I've dived in from the deep end and started by modifying one of my app's API calls to return an Observable. Currently the API call is used by an AsyncTaskLoader which returns cached data from a local database, then does the call, merges the data and returns it again. This pattern sounded like a perfect subject for my RxJava experiments, but starting small, I want to return an observable from my API call.
This is my original call:
public static ArrayList<Stuff> getStuffForId(String id)
throws IOException, UserNotAuthenticatedException {
Profile profile = getProfile();
HashMap<String,ArrayList<Stuff>> map = profile.getStuff();
if (map == null) {
throw new IOException("error processing - map cannot be null");
}
return map.get(id);
}
private static Profile getProfile()
throws IOException, UserNotAuthenticatedException {
// <.. getting url, auth tokens and other stuff to prepare the Request ..>
Response response = sHttpClient.newCall(request).execute();
if (response.code() == ERR_AUTH_REJECTED) {
throw new UserNotAuthenticatedException(response.body().string());
}
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
Gson gson = new Gson();
String result = response.body().string();
response.body().close();
return gson.fromJson(result, Profile.class);
}
And in RxJava world I'm thinking something along the lines of:
public static Observable<ArrayList<Stuff>> getStuffForId(String id) {
return getProfile().map(
Profile::getStuff).map(
map -> {
if (map == null) {
Observable.error(new IOException("error processing - map cannot be null"));
}
return map.get(id);
});
}
private static Observable<Profile> getProfile() {
return Observable.fromCallable(() -> {
// <.. getting url, auth tokens and other stuff to prepare the Request ..>
Response response = sHttpClient.newCall(request).execute();
if (response.code() == ERR_AUTH_REJECTED) {
throw new UserNotAuthenticatedException(response.body().string(),
authToken);
}
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
Gson gson = new Gson();
String result = response.body().string();
response.body().close();
return gson.fromJson(result, Profile.class);
});
}
Does this look anything like what one would expect? I'm still not sure of the difference between fromCallable() and defer() and where you use one or another. Also not sure where do the exceptions go once thrown inside the fromCallable() method - will they automagically end up in onError of my subscriber or do I need to handle them in my getStuffForId method? And finally, Android Studio is warning me that return map.get(id) might throw a nullPointer. Is that just because the IDE doesn't understand that Observable.error will terminate the execution, or is it that I don't understand what will happen on Observable.error?
1) Difference b/w fromCallable() and defer()?
Well defer() does not create the Observable until some subscriber subscribes and it creates new Obervable each time the user subscribes. Refer this link for why you would want to use defer().
2) Where do exceptions go once thrown inside the fromCallable() method?
Exceptions are caught inside the Observer and then passed as a Throwable object to Subscriber's onError() method.
3) Android Studio is warning me that return map.get(id) might throw a nullPointer.
Its because when it is actually null you are not returning anything in the if statement. The code will run beyond if statement, thus causing nullPointerException. Observable.error()); returns an Observable and it doesn't throw anything, in order to do that you have to explicitly throw a RuntimeException.
4) Does this look anything like what one would expect.
Apart from the above error, there is nothing wrong but you can search online for the rxJava patterns to code better structurally.
Does this look anything like what one would expect
Yes, but please have a look at libraries, which will do the plumbing for you: https://github.com/square/retrofit
If you throw any exception in fromCallable you would use defer and return Observable.error(new Exception("error"))
Difference fromCallable / defer
Both methods are factories for creating observables. From callable asks you to return a value as in string etc. Defer like you to return a observable of something. You would use fromCallable if you would like to wrap some non-observable-method-call which returns a certain type. Furthermore fromCallable will handle exceptions for your and pass them down the chain. In contrast you would use defer if you would like to handle your own exception/ observable. You may return a observable which emits a value and then finishes or not finishes. 'fromCallable' will alsways finish with a value(s) and onComplete or onError. With defer you may produce a observable, which will never end as in Observable.never().
will they automagically end up in onError
Yes, exception will be caught and passed along as onError. You may handle the error with a operator right away in the chain or you may provide a onError handle (overload) on subscription.
return map.get(id) might throw a nullPointer
If you are using RxJava1.x you may encounter null values in the stream, because passing values with onNext(null) are valid. Therefor you would need a null check, due to the possibility of a NPE. Instead of the null-check you could filter-out null values with filter-operator as in:
Observable.just("1", "2", null, "3")
.filter(s -> s != null)
.map(s -> s.getBytes())
.subscribe(bytes -> {
//...
});
In this case you will get a warning about a possible NPE at s.getBytes(). But due to the filter-operation you can be sure, that s is never null.

Sony QX100 return 403 error for supported methods

I am trying to set the Exposure mode and Focus mode for my QX100 device. Each time I make the API call I get a 403 error. However, these two methods setExposureMode and setFocusMode are supported by the QX100 as it clearly states in the API docs. In addition, I can set the focus mode through Playmemories. This same problem also occurs with setBeepMode, which is also supported. Any ideas about why this could be occurring?
There are some supported methods that are working, such as actTakePicture and setPostviewImageSize
An example call:
public JSONObject setFocusMode() throws IOException {
String service = "camera";
try {
JSONObject requestJson =
new JSONObject().put("method", "setFocusMode").put("params", new JSONArray().put("MF")) //
.put("id", id()).put("version", "1.0");
String url = findActionListUrl(service) + "/" + service;
log("Request: " + requestJson.toString());
JSONObject responseJson = SimpleHttpClient.httpPost(url, requestJson, null);
log("Response: " + responseJson.toString());
return responseJson;
} catch (JSONException e) {
throw new IOException(e);
}
}
Is your QX100 updated to the latest firmware? On old one, most of APIs are restricted.
Or they may be temporary disabled. You can use getAvailableApiList to know that.

Billing API v3 IabHelper NullPointerException

edit 4/15: Catching nullpointer in IabHelper appears to have stopped this problem. I am no longer seeing the exceptions being thrown, I'm going to accept this as an answer.
edit 4/04: A little bit of a deeper dive. There are try catch blocks that handle RemoteExceptions and JSONExceptions for the queryPurchases method, but no NullPointerException handling. What I am going to try is include NullPointer Exception handling so IabHelper looks like this when trying to querySkuDetails:
catch (NullPointerException e) {
throw new IabException(IABHELPER_UNKNOWN_ERROR, "NullPointer while refreshing inventory.", e);
}
I just filed a bug on this:
https://code.google.com/p/marketbilling/issues/detail?id=114
edit 3/25: well, still receiving this crash... now it happens while trying to get a context at line 3 of the following excerpt from IabHelper:
int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException {
logDebug("Querying owned items, item type: " + itemType);
logDebug("Package name: " + mContext.getPackageName());
This is frustrating because in my manifest I always use the full path name of my app for "name".
Example "com.myappname.blah.ClassName"
I've also tried passing this, MyClass.this, getApplicationContext() to mHelper. However they all produce the same NullPointer results randomly from devices in the wild. I also tried name=".MyClass" in the manifest. This is what it looks like currently:
mHelper = new IabHelper(MyClass.this, myKey);
edit 3/18/13: I am still receiving exceptions, even with the new IabHelper version deployed on 3/17.
I am starting to see a pattern here, that the crashes are all when trying to get a context when executing mContext.getPackageName(). I'm curious why this works on all of my test devices, and I can't reproduce this crash, and only seems to be on a small number of devices.
Here is the new crash:
java.lang.NullPointerException
at com.myapp.util.IabHelper.queryPurchases(SourceFile:836)
at com.myapp.util.IabHelper.queryInventory(SourceFile:558)
at com.myapp.util.IabHelper.queryInventory(SourceFile:522)
at com.myapp.util.IabHelper$2.run(SourceFile:617)
at java.lang.Thread.run(Thread.java:1019)
Caused by IabHelper...
line 836: logDebug("Package name: " + mContext.getPackageName());
edit 3/17/13: I see that there have been many bug fixes published over the past several months, I will try the latest code available here and see if this resolves the problem:
https://code.google.com/p/marketbilling/source/browse/v3/src/com/example/android/trivialdrivesample/util
In one of my apps, I am using the billing API and the boilerplate code included with it.
I am using the latest version of billing API available via the SDK manager as of 3/16/2013.
In my activity, I query the inventory using the following:
final List<String> skuList = new ArrayList<String>();
skuList.add("sku1");
skuList.add("sku2");
skuList.add("sku3");
if (skuList != null) {
if (skuList.size() > 0) {
try {
mHelper.queryInventoryAsync(true, skuList, mGotInventoryListener);
} catch (Exception e) {
ACRA.getErrorReporter().handleException(e);
}
}
}
I am receiving multiple NullPointerException reports in the wild from the IabHelper class for the following devices. I can't reproduce the issue and can't find any information regarding these crashes, and is the reason why I am posting this question.
I have countless other checks for nulls and try/catch blocks in the "developer facing" part of the billing API, including within onQueryInventoryFinished, so I know this exception is not being thrown from "my code" (because I'm not capturing crashes from any of my app's classes), but instead is being thrown from within the IabHelper itself. I have not modified the IabHelper other than this recommended fix: https://stackoverflow.com/a/14737699
Crash #1 Galaxy Nexus
java.lang.NullPointerException
at com.myapp.util.IabHelper.querySkuDetails(SourceFile:802)
at com.myapp.util.IabHelper.queryInventory(SourceFile:471)
at com.myapp.util.IabHelper$2.run(SourceFile:521)
at java.lang.Thread.run(Thread.java:856)
Caused by IabHelper...
line 802: Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), ITEM_TYPE_INAPP, querySkus);
Crash #2 Samsung GT-S5570L
java.lang.NullPointerException
at com.myapp.util.IabHelper.queryPurchases(SourceFile:735)
at com.myapp.util.IabHelper.queryInventory(SourceFile:465)
at com.myapp.util.IabHelper$2.run(SourceFile:521)
at java.lang.Thread.run(Thread.java:1019)
Caused by IabHelper...
line 735: Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), ITEM_TYPE_INAPP, continueToken);
edit 4/15: Catching nullpointer in IabHelper appears to have stopped this problem. I am no longer seeing the exceptions being thrown, I'm going to accept this as an answer.
edit 4/04: A little bit of a deeper dive. There are try catch blocks that handle RemoteExceptions and JSONExceptions for the queryPurchases method, but no NullPointerException handling. What I am going to try is include NullPointer Exception handling so IabHelper looks like this when trying to querySkuDetails:
catch (NullPointerException e) {
throw new IabException(IABHELPER_UNKNOWN_ERROR, "NullPointer while refreshing inventory.", e);
}
I just filed a bug on this:
https://code.google.com/p/marketbilling/issues/detail?id=114
Change
if (querySkuDetails) {
r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of items).");
}
}
to
if (querySkuDetails) {
try {
r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of items).");
}
} catch (NullPointerException e) {
throw new IabException(IABHELPER_UNKNOWN_ERROR, "NPE while refreshing inventory.", e);
}
}
Change
if (querySkuDetails) {
r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreSubsSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions).");
}
}
to
if (querySkuDetails) {
try {
r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreSubsSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions).");
}
} catch (NullPointerException e) {
throw new IabException(IABHELPER_UNKNOWN_ERROR, "NPE while refreshing inventory.", e);
}
}
You are probably using async operations. The current IabHelper is not safe in case you use the ...async methods. The problem is that in any moment an async operation is running dispose can be called on the main thread. In this case you will get NullPointerExceptions and IllegalStateExceptions.
Here is the patch fixing it:
Index: src/com/evotegra/aCoDriver/iabUtil/IabHelper.java
===================================================================
--- src/com/evotegra/aCoDriver/iabUtil/IabHelper.java (revision 1162)
+++ src/com/evotegra/aCoDriver/iabUtil/IabHelper.java (working copy)
## -86,7 +86,10 ##
// Is an asynchronous operation in progress?
// (only one at a time can be in progress)
- boolean mAsyncInProgress = false;
+ volatile boolean mAsyncInProgress = false;
+
+ // is set to true if dispose is called while a thread is running. Allows graceful shutdown
+ volatile boolean mDisposeRequested = false;
// (for logging/debugging)
// if mAsyncInProgress == true, what asynchronous operation is in progress?
## -285,6 +288,12 ##
* disposed of, it can't be used again.
*/
public void dispose() {
+ // do not dispose while an async Thread is running. Will cause all kinds of exceptions.
+ // In this case dispose must be called from thread after setting mAsyncInProgress to true
+ if (mAsyncInProgress) {
+ mDisposeRequested = true;
+ return;
+ }
logDebug("Disposing.");
mSetupDone = false;
if (mServiceConn != null) {
## -827,6 +836,7 ##
logDebug("Ending async operation: " + mAsyncOperation);
mAsyncOperation = "";
mAsyncInProgress = false;
+ if (mDisposeRequested) IabHelper.this.dispose();
}
Or download the patch here.
http://code.google.com/p/marketbilling/issues/detail?id=139&thanks=139&ts=1375614409
Slightly modify the beginning of the queryPurchases method to look like this:
int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException {
// Query purchases
//logDebug("Querying owned items, item type: " + itemType);
//logDebug("Package name: " + mContext.getPackageName());
boolean verificationFailed = false;
String continueToken = null;
do {
// logDebug("Calling getPurchases with continuation token: " + continueToken);
if(mDisposed || mService==null) return IABHELPER_UNKNOWN_ERROR;
Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(),
itemType, continueToken);
Thanks to sebastie for pointing out the cause of this.
tmanthey patch also requires
mDisposeRequested = false;
after the disposing takes place
If you're getting this error on the emulator, it may be a very simple thing which happens in more than a half cases.
Check that you're using Google API SDK and not regular SDK!!!
The IabHelper is obsolete and has been replaced by the BillingClient.
See https://developer.android.com/google/play/billing/billing_library.html

How to update tweets using Twitter 4J?

I am using Twitter4J (2.1.0) to try to update tweets. I can't figure out what is wrong with my code.
In particular my problems are:
(a) Not all tweets post successfully. I often get the error code of -1. According to a google group post...
You get code -1 when the internal http component fails to connect to
or read from the API. You may also get code -1 when the API is
unreachable from the JVM due to the DNS related issues.
Strangely I seemed to be getting this pretty much every second post. To deal with this whenever I received the -1 error code I would try to update again. While I realise this is not a very good solution. this fixed the probem 95% of the time
(b) I get a duplication errors (error code 403) whenever the new tweet matches any old tweet
Error code 403 occurs even if the duplicate is now outdated (eg. post "Hello there", post a variety of status updates, then post "Hello there" again throws a TwitterException with error code 403)
My current code...
My code is in an AsyncTask which is in turn in a Service (rather than activity). I have included the Asynctask code and another method below....
class SendTwitAsyncTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String tokenTwit = params[0];
String tokenSecretTwit = params[1];
String strMessageBody = params[2];
AccessToken aToken = new AccessToken(tokenTwit, tokenSecretTwit);
// initialize Twitter4J
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(aToken);
// create a tweet
// strMessageBody varies
String tweet = strMessageBody;
boolean bool = twitter.isOAuthEnabled();
if (twitter.isOAuthEnabled()) {
GeoLocation geolocation = new GeoLocation(-33.91, 151.25);
try {
twitter.updateStatus(tweet, geolocation);
showNotification("Twitter One" , TWIT_SUCCESS);
} catch (TwitterException te) {
if (te.getStatusCode() == -1) {
//try again
try {
twitter.updateStatus(tweet, geolocation);
showNotification("Twitter Two ", TWIT_SUCCESS);
}
catch (TwitterException tetwo) {
describeTwitException(tetwo.getStatusCode());
}
} //end if
//else exception other than -1
else {
describeTwitException(te.getStatusCode());
} //end else
}// end outer catch
} //end if
else {
showNotification("Unable to authenticate" , TWIT_FAIL);
}//
return null;
}
} //end class SendTwitAsyncTask
public void describeTwitException(int twitExceptionCode) {
switch (twitExceptionCode) {
case (-1):
showNotification("Twitter (unable to connect)", TWIT_FAIL);
break;
case(403):
showNotification("Twitter (duplicate tweet)", TWIT_FAIL);
break;
default:
showNotification("Twitter", TWIT_FAIL);
} //end switch
} //end describeTwitException method
The twitter API will reject any tweet that matches a tweet that you've already made. I don't think the old tweet ever 'expires.'

Android OpenErp Search Request XMLRPC

I am working on an android application which is able to connect with an openerp server and retrive the userid and also the individual fields of the different contacts of that user.
below is the code on the things i have done so far
public int Search()
{
searchClient = new XMLRPCClient("http://"+lp.HOST+":"+lp.IN_PORT+lp.URL_XML+lp.URL_OBJECT);
try
{
record = (Array[]) searchClient.call("search",lp.DB_NAME, lp.uid1, lp.PASSWORD, "res.partnet.contact","execute", arguments);
}
catch(Exception e)
{
Log.i("------------------ CONNECTION FAILED Search", e.toString());
}
return 0;
}
i appreciate the help given
Thank you,
try to interchange the position of method search and execute.The method execute must be given before search.Also try searchClient.callEx instead call only like you do it above!
record = (Array[]) searchClient.callEx("execute",lp.DB_NAME, lp.uid1, lp.PASSWORD, "res.partnet.contact","search", arguments);

Categories

Resources