Debugging a OperationApplicationException insert failed - android

I am going to try to simplify this situation as much as possible.
Observe the following code:
//...
ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
while(recordsToProcess){
//... Grabbing data
//... built a ContentProviderOperation variable named operation
batch.add(operation);
//... setting recordsToProcess to true or false
}
try {
mContext.getContentResolver().applyBatch(Contract.CONTENT_AUTHORITY, batch);
} catch (RemoteException e) {
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
throw new RuntimeException("Problem applying batch operation", e);
}
}
During this process, an OperationApplicationException is thrown, which looks like:
... Problem applying batch operation
... android.content.OperationApplicationException: insert failed
... Stack Trace ....
I understand that this exception is "thrown if either the insert fails or if the number of rows affected didn't match the expected count" and/or "Thrown when an application of a ContentProviderOperation fails due the specified constraints."
My database schema has hardly any constraints and the data going in the operation is valid.
Is there any way to get more information to why the exception is thrown? What constraint failed? etc...?

For debugging I would start with something like this
{
.........
int i = 0;
for (ContentProviderOperation op : ops) {
applySingle(WorkoutProvider.AUTHORITY, op);
Log.e(getTag(), Integer.toString(i));
i++;
}
}
protected synchronized void applySingle(String authority, ContentProviderOperation op) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(op);
try {
App.getInstance().getContentResolver().applyBatch(authority, ops);
} catch (RemoteException e) {
Log.e(getTag(), "Error updating workout id to server's", e);
e.printStackTrace();
} catch (OperationApplicationException e) {
Log.e(getTag(), "Error updating workout id to server's", e);
e.printStackTrace();
}
}
Then I would recommend debugging before that for loop and taking a look at what operation failed.

Related

How to display SQLException while insert or update operation

I am working with SQLite android where I am using an sqLiteDatabase.insert function to insert customers and sqLiteDatabase.update to update customers and getting the result which is always a long variable, When result is -1, I know the database operation was not successful but I want to display the actual SQLException that occurred. As the return type of these methods is long so they only print the exception in log. Is there any way to get the message of SQLException and display in Toast etc.
I tried to use try catch to catch the exception and show message but when exception occurs it doesnt go to catch block. Below is my code
public void insertData(SQLiteDatabase sqLiteDatabase, Context context, ContentValues values, DatabaseOperation dbOperation, DatabaseOperationCallback dbOperationCallback) {
JSONObject resultObj = new JSONObject();
try {
if (dbOperation != null) {
sqLiteDatabase.insert(dbOperation.getTableName(), null, values);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
//showing in toast; this is not triggered
} catch (Exception ex) {
ex.printStackTrace();
//showing in toast; this is not triggered
}
}
Please see below picture for reference. Any help will be appreciated
You can use
e.printStackTrace(); // (directly to the log)
or
e.getMessage(); // returns message as a String
or others as per the Java Exception Class.
However, using the insertOrThrow method, is probably the method that you want to use.

Android Background Runnable not working on older devices

I have the following running at startup inside of an IntentService
threadManager.postBackgroundRunnableDelayed(() -> {
try {
// Calling getToken and getId must be on separate thread. Otherwise, it blocks UI thread.
String token = instanceID.getToken(SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
String id = instanceID.getId();
Timber.d("id: " + id);
Timber.d("token: " + token);
lazyRestQueue.get().sendGcmToken(new GcmPushRequest(id, token), getSendGcmTokenCallback());
setupAnalytics(token);
} catch (IOException e) {
Timber.e(e, "Exception during registration");
Crashlytics.logException(e);
setHasToken(false);
} catch (RuntimeException e) {
// This will be thrown if Localytics was not properly setup
Timber.e(e, "Exception during registration");
}
});
When I run it on anything below API 18 it causes the app to close (not crash oddly, just close)
can someone give me advice on this? I know it probably has to do with the service or something not timing properly

Window Azure Mobile Service select Query issue. how to make query on same column of multiple value instead only single?

I am working on android to access window azure database..
My qtn is How to make an query to access data based on single column but multiple values.?
Here is my code :
try {
mClient = new MobileServiceClient(Constant.AZURE_URL, Constant.AZURE_API_KEY, getApplicationContext());
mUsersTable = mClient.getTable(Users.class);
MobileServiceTable<Users> table = mClient.getTable(Constant.TABLE_USERS, Users.class);
table.where().field("id").eq(11)
.execute(new TableQueryCallback<Users>() {
#Override
public void onCompleted(List<Users> result, int count,
Exception exception, ServiceFilterResponse response) {
if (exception != null) {
Log.d("Exception at complete::",""+exception.getCause().getMessage());
} else {
StringBuffer sb = new StringBuffer();
for (Users users_obj : result) {
System.out.println("NAMESS::::"+users_obj.getFirstName());
// userID_arr.add(users_obj.getFirstName());
}
//System.out.println("User Array"+userID_arr);
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e("Error Mobile Service Authentication", "There was an error creating the Mobile Service. Verify the URL");
}
catch (Exception e) {
e.printStackTrace();
}
There for I am able to get complete row on the basis of single parameter in table.where().feilds.eq(11)................... so instead 11 i want to add dynamic values on .eq() ....what is approach in Android auzre to get values on multiple id request ?

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>"

Android - print full exception backtrace to log

I have a try/catch block that throws an exception and I would like to see information about the exception in the Android device log.
I read the log of the mobile device with this command from my development computer:
/home/dan/android-sdk-linux_x86/tools/adb shell logcat
I tried this first:
try {
// code buggy code
} catch (Exception e)
{
e.printStackTrace();
}
but that doesn't print anything to the log. That's a pity because it would have helped a lot.
The best I have achieved is:
try {
// code buggy code
} catch (Exception e)
{
Log.e("MYAPP", "exception: " + e.getMessage());
Log.e("MYAPP", "exception: " + e.toString());
}
Better than nothing but not very satisfying.
Do you know how to print the full backtrace to the log?
Thanks.
try {
// code that might throw an exception
} catch (Exception e) {
Log.e("MYAPP", "exception", e);
}
More Explicitly with Further Info
(Since this is the oldest question about this.)
The three-argument Android log methods will print the stack trace for an Exception that is provided as the third parameter. For example
Log.d(String tag, String msg, Throwable tr)
where tr is the Exception.
According to this comment those Log methods "use the getStackTraceString() method ... behind the scenes" to do that.
This helper function also works nice since Exception is also a Throwable.
try{
//bugtastic code here
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
catch (Exception e) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream stream = new PrintStream( baos );
e.printStackTrace(stream);
stream.flush();
Log.e("MYAPP", new String( baos.toByteArray() );
}
Or... ya know... what EboMike said.
public String getStackTrace(Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
e.printStackTrace() prints it to me. I don't think you're running the logcat correctly. Don't run it in a shell, just run
/home/dan/android-sdk-linux_x86/tools/adb logcat
The standard output and error output are directed to /dev/null by default so it is all lost. If you want to log this output then you need to follow the instructions "Viewing stdout and stderr" shown here
try{
...
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e.getCause());
}
if you want to print out stack trace without exception, you can create it by following command
(new Throwable()).printStackTrace();
In the context of Android, I had to cast the Exception to a String:
try {
url = new URL(REGISTRATION_PATH);
urlConnection = (HttpURLConnection) url.openConnection();
} catch(MalformedURLException e) {
Log.i("MALFORMED URL", String.valueOf(e));
} catch(IOException e) {
Log.i("IOException", String.valueOf(e));
}
KOTLIN SOLUTION:
You can make use of the helper function getStackTraceString() belonging to the android.util.Log class to print the entire error message on console.
Example:
try {
// your code here
} catch (e: Exception) {
Log.e("TAG", "Exception occurred, stack trace: " + e.getStackTraceString());
}
Kotlin extension. Returns the detailed description of this throwable with its stack trace.
e.stackTraceToString()

Categories

Resources