I am getting the above error : System.AggregateException: One or more errors occurred.
With this line of code here:
List<tblDeviceIds> installIDs = KumulosHelper.Functions.Device.GetDeviceIDsOfUser(toUser);
The Method "GetDeviceIdsOfUser" looks like this:
public static List<tblDeviceIds> GetDeviceIDsOfUser(string username)
{
IDictionary<string, string> myDict = new Dictionary<string, string>();
myDict.Add("username", username);
return KumulosGeneral.getTblDeviceIds("getDeviceIDsOfUser", myDict);
}
So, there is really nothing fancy going on.
Sometimes, but only on CERTAIN users above error. So even when the user would be "null", which by the way he never is, the list would just return nothing. BUT instead it crashes. This itself is something I didnt quite understand, so what I did was:
List<tblDeviceIds> installIDs = null;
try
{
installIDs = KumulosHelper.Functions.Device.GetDeviceIDsOfUser(toUser);
}
catch
{
installIDs = null;
}
This would be a bullet prove workaround, but yet: It goes into try, it crashes, it never goes into catch, it is dead.
Would someone care to explain?
Thanks!
O, maybe this has something todo with doing this on another thread? This is the function that calls all that:
await Task.Run(() =>
{
Intermediate.SendMessageToUser(toUsername, temp);
});
As you can see, it is inside an async task... but that should not be a problem, right?
The reason you receive an AggregateException is because the exception is originating from within a Task (that is likely running on a separate thread). To determine the cause, walk the line of InnerException(s).
Regarding the catch not catching, my suggestions would be: Ensure the latest code is being used. Add Tracing instead of relying on breakpoints. And see if the inner exception is thrown from yet another thread (is GetDeviceIDsOfUser also using async?)
See also: Why is .NET exception not caught by try/catch block?
Related
I have spent days trying to work out the cause of this crash in the Google Play Services Saved Game code from a tester's device and have no idea what else to try as it works on all three of my devices. The crash that occurs is:
java.lang.NullPointerException: Must provide a previously opened Snapshot
when I try and call
snapshot.readFully();
even though the snapshot has been opened and return code checked, and checked to see if it is null. Here is the code path leading up to the crash, with non-executed sections removed for brevity:
public void LoadSnapshot()
{
AsyncTask<Void, Void, SNAPSHOT_ASYNC_RESULT> task = new AsyncTask<Void, Void, SNAPSHOT_ASYNC_RESULT>()
{
#Override
protected SNAPSHOT_ASYNC_RESULT doInBackground(Void... params)
{
if (isSignedIn())
{
Snapshots.OpenSnapshotResult result = Games.Snapshots.open(getApiClient(), "MySnapshot", true).await();
int status = result.getStatus().getStatusCode();
DebugLog("Snapshot Load Open result code: " + status);
if (status == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT)
{
Snapshot snapshot = result.getSnapshot();
Snapshot conflictSnapshot = result.getConflictingSnapshot();
//write both conflicted files so we can merge them
if (snapshot != null && conflictSnapshot != null)
{
byte[] ssdata = snapshot.readFully(); //CRASH HERE!
...
}
...
}
}
}
}
task.execute();
}
I get similar crashes from the same device when simply saving sometimes with .open() followed by .writebytes().
It is making the entire game unstable and I need to get this fixed somehow. Any help or ideas would be much appreciated.
All I can think is that because it's running on a background thread in an AsyncTask something bad has happened in between opening the snapshot and trying to read/write it on this device. According to the tester is crashes 'most' of the time.
I solved this eventually by only allowing one Async operation at a time, as I was previously allowing a concurrent save and load of the same snapshot.
I also wrapped the readFully() inside a try/catch for safety.
I'm working on this as well. I'm looking at the documentation now, and it has this to say about the function: readFully()
Read the contents of a snapshot.
If this snapshot was not opened via open(GoogleApiClient, SnapshotMetadata), or if the contents have already been committed via commitAndClose(GoogleApiClient, Snapshot, SnapshotMetadataChange) this method will throw an exception.
Returns
The bytes of the snapshot contents.
Throws
IOException if reading the snapshot failed.
Are you sure that the snapshot has been opened and committed correctly?
I would like some help regarding Java - Android MultiThreading
While learning to develop my app in a multi-threading way in order to take advantage of the ever-growing multi-core devices market share (most devices are quad core now, some even octo-core), I ran in a situation where my threads are either being calling twice or running twice.
I just don't why and how.
[EDIT 3]
Alright, I narrowed down the issue : I called the AsyncTask from the onResume() method. Although my app did not lost focus (which would mean a call to onPause() then back to onResume() upon return of focus in which case my threads would be run twice) during the tests, I solved the issue by moving away the call to FetchFriendsList to another place.
So far so good, but since in my tests the app did not loose focus or perhaps it did but I could not witness it (!), I think there is another reason behind so I'd say my problem is not entirely solved ... at least for the moment. It does work though. Perhaps I did solve the issue but I do not know how :(
[end of EDIT 3]
I am implementing last Facebook SDK and I am using it to fetch the end-user friends list, which seems to do the work.
Since I am running this operation in an AsyncTask, I am not using request.executeAsync().
Instead I am using request.executeAndWait(). Facebook JavaDoc does state that this method must only be used if I am not in a the Main UI Thread which is my case otherwise I would get a NetworkOnMainThreadException.
Anyway, this is where the weird behavior is happening.
private final ArrayList<GraphUser> userFriendsList = new ArrayList<GraphUser>();
public final void fetchFriendsList() {
if (this.session != null && this.session.isOpened()) {
final Request requestUserFriendsList = Request.newMyFriendsRequest(
this.session, new Request.GraphUserListCallback()
public final void onCompleted(final List<GraphUser> users, final Response response) {
if (users != null && users.size() > 0) {
Log.v("Retrieved Friends List -> ", String.valueOf(users.size()));
userFriendsList.addAll(users);
}
}
}
);
if (this.asyncFlag)
requestUserFriendsList.executeAsync();
else
requestUserFriendsList.executeAndWait();
}
}
In my case, asyncFlag is set to false because I need to do stuff synchronously in that specific order :
Fetch User Friends List (not on the Main (UI) Thread)
Save friends list on device (separate new thread)
Save friends list on a server (separate new thread)
Following this pattern, the line userFriendsList.addAll(users); is called twice.
In the logcat, the Log.vis showed twice as well, and finally looking with the debugger, the content of the user friends list is made of duplicates.
But that's not all ... step 2 and 3 are indeed two separate threads which are both created and spawned within the same method : public final void asyncSaveFacebookFriendsList().
And guess what, this method is even called twice !
just why ?
At the beginning I was calling the method for step 2 and 3 like this :
[...]
userFriendsList.addAll(users);
asyncSaveFacebookFriendsList(); // it was private before
[...]
This is where the issue started as both line were running twice.
So I thought, alright, I'll call it later like this :
[...]
fetchFriendsList();
asyncSaveFacebookFriendsList(); // it is now public
[...]
But the issue remains still.
If I don't call public final void asyncSaveFacebookFriendsList(), then nothing is run twice.
Why does this issue happen ? Is there something I did not get in Java Threads ?
I do not think this is somehow related to the Facebook SDK because following the same pattern (and doing it also at the same time), I have the same issues when fetching and storing the end-user Twitter friends list.
So I do believe I am doing something wrong. Does someone have any idea in what possible case a thread is called twice ?
Note : all threads are started this way : thread.start(). I am not using any ThreadPool nor the ExecutorService.
In case you need more background context :
Content of AsyncTask : (no need to wonder why Void and Long, I remove the irrelevant code related to it)
private final class FetchFriendsLists extends AsyncTask<Long, Integer, Void> {
protected final Void doInBackground(final Long... params) {
if (params[0] != Long.valueOf(-1)) {
[...]
twitterAPI.fetchUserFriendsList();
publishProgress(1, -1);
}
if (params[1] == Long.valueOf(0)) {
[...]
facebookAPI.fetchFriendsList();
publishProgress(-1, 0);
}
return null;
}
protected final void onProgressUpdate(Integer... flags) {
super.onProgressUpdate(flags);
if (flags[0] != -1)
twitterAPI.asyncSaveFacebookFriendsList();
if (flags[1] == 0)
facebookAPI.asyncSaveFacebookFriendsList();
}
}
As you can see, I start step 2 and 3 in onPublishProgress() which runs on the Main UI Thread. Brefore it was in the doInBackground() method : the issue happens in both cases!
[EDIT]
After further test, it would seem any kind of code is in fact running twice.
I created a simple method called test in which in print a counter. The counter incremente twice as well !
Why you use onProgressUpdate?¿?
onProgressUpdate(Progress...), [...]. This method is used to display any form of progress in the
user interface while the background computation is still executing.
For instance, it can be used to animate a progress bar or show logs in
a text field.
This is used not at the finish of the petition, but when progress increased.
Read this:
http://developer.android.com/reference/android/os/AsyncTask.html
You need to use:
protected void onPostExecute(Long result) {
Android keeps on reporting crashes from users which I can't reproduce on my phone.
I can find the lines which seem to be incorrect:
cursor.moveToFirst();
elechs=cursor.getString(2);
elecls=cursor.getString(3);
gass=cursor.getString(4);
waters=cursor.getString(5);
cursor.close();
if (elechs.length()!=0){
elechdb=Double.valueOf(elechs);
}
else {
elechdb=0.0;
}
if (elecls.length()!=0){
elecldb=Double.valueOf(elecls);}
else {
elecldb=0.0;
}
if (gass.length()!=0){
gasdb=Double.valueOf(gass);
}
else {
gasdb=0.0;
}
if (waters.length()!=0){
waterdb=Double.valueOf(waters);
}
else {
waterdb=0.0;
}
elecldb=Double.valueOf(elecls);
gasdb=Double.valueOf(gass);
waterdb=Double.valueOf(waters);
If I look at the code, it doesn't make any sense.
I think I forgot to delete the last three lines. First I check the string. If the string is empty it will store the value as zero.
The incorrect last three lines will also try to make a double if the cell is empty. This cause a lot of crashes. However not on my machine.
I believe that it shouldn't be possible to make a of an empty cell.
Does anyone know why this error doesn't crash my phone?
Your best solution is probably just to remove the problematic lines that shouldn't be there anyway, preferably add actual error handling around calls to Double.valueOf() in case the input is completely malformed (there may be inconsistent behaviour if the cell is empty, but if it says "hello world", everything will crash), and release an update.
Since the users are getting NumberFormatException, you should catch the exception and perform appropriate action when it happens.
if (elechs.length()!=0) {
try {
elechdb=Double.valueOf(elechs);
} catch (NumberFormatException e) {
// Perform error handling
}
}
If the users are getting NullPointerException, you should check if the strings are null before checking for their lengths.
If the data is put in by the user, you should do both of the above to avoid future problems.
After many tries, I decided to ask the question again. In my last question, someone said I should have a look at Jsoup. I wrote some code but it won't work. It's an android app. But it totally crashes. with the error message:
Unfortunately, (appname) has stopped
See the full error message
My code for extracting text from the <div>:
public void ButtonClick(View view) throws IOException {
Document doc = dereference("here is my url");
String text = extractContent(doc);
updateUI(text);
}
private Document dereference(String uri) {
Connection connection = Jsoup.connect(uri);
return connection.get();
}
private String extractContent(Document doc) {
Elements divs = doc.select("div.onlinestatus");
return divs.text();
}
private void updateUI(String text) {
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(text);
}
the input from the url:
<html><!-- [...] --><body>
<div class='onlinestatus'>Server ist online! <br /></div>
</body></html>
Can someone spot the mistake?
Edit: when I perform all these operations in a separate thread, I get a different error. Error log and code can be found here.
This is not a Jsoup question after all.
If you look up the error from your error log (first line) where it reads
NetworkOnMainThreadException
Googling for "android NetworkOnMainThreadException" yiedls a page from the android developer reference, which states
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This would explain your previous attempts at moving code into a separate thread, which seemed to produce different results.
Have a look at the page suggested in the android developer reference, on Designing for Responsiveness. That should give you an answer.
The next thing that can fail, is that you need to do all UI changes in the thread that created the UI. The CalledFromWrongThreadException you got here tells you exactly what went wrong. Looking up that error will lead you to a question+answer similar to this one.
If you have problems with that, I suggest you ask a new question, if your problem is not already covered on StackOverflow (but I believe it is!)
I've created an AsyncTask that loads messaging history from a database and then shows it on the device screen:
private void loadHistoryFromDB(Date lastUpdateDate)
{
final class DBAsyncTask extends AsyncTask<Void, Void, List<XMPPMessage>>
{
#Override
protected List<XMPPMessage> doInBackground(Void... arg0)
{
List<XMPPMessage> messages = null;
try
{
messages = PersistenceManager.getXMPPMessagesFromDB(userInfo, 0, messagingActivity);
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (LetsDatabaseException e)
{
e.printStackTrace();
}
return messages;
}
It seems to work fine, but after being executed, it leaves 2 running threads and I can't finish the activity because of that. How can I fix it?
As long as your tasks are executing properly (exits from onPostExecute), this shouldn't be something you have to worry about. Once executed, AsyncTask thread(s) will stick around for possible reuse in the form of a thread pool or single thread, depending on platform version. This is normal behaviour - they will eventually be cleaned-up/reused.
First off, make sure you are calling super.doInBackGround() at the top of your overridden method call.
If that isn't it, it's likely because you are maintaining the connecting to the database.
That is, you still have a lock established on the database.
See if you can explicitly unlock the database, that may fix your problem.
You could put it in the onPostExecute() method.
This problem is most likely due to confusion surrounding the cancel method of AsyncTask.
You need to break down your background task into loopable segments, then Before each loop iteration starts doing your task,you need to check if the task is cancelled and if it is you need to break the loop. There doesn't seem to be any other way to stop an AsyncTask from executing.
I've posted a detailed guide to this problem with code examples here:
http://tpbapp.com/android-development/android-asynctask-stop-running-cancel-method/