batch adding events to google calender - android

Hi I'm trying to add events to a calender with the google-api-java-client and calender API service for a android app. I used the calendersample project created by Yaniv Inbar as a template which works great. When inserting 1 event to the selected calender works perfectly but when i try to batch add events to the calendar get an Illegal state exception.
in the example you could batch add calenders like this.
whole class can be found here AsyncBatchInsertCalendars.java
#Override
protected void doInBackground() throws IOException {
BatchRequest batch = client.batch();
for (Calendar calendar : calendars) {
client.calendars().insert(calendar).setFields(CalendarInfo.FIELDS)
.queue(batch, new JsonBatchCallback<Calendar>() {
public void onSuccess(Calendar calendar, GoogleHeaders headers) {
model.add(calendar);
}
#Override
public void onFailure(GoogleJsonError err, GoogleHeaders headers)
throws IOException {
Utils.logAndShowError(activity, CalendarSampleActivity.TAG, err.getMessage());
}
});
}
batch.execute();
}
I rewrote the class so that it would be events instead of calenders. if you look at the whole class AsyncBatchInsertEvent.java you'll see that in the doInBackground methode I also loop through a arraylist creating a list of events. which should than be added to the batch to be inserted on the given calendar.
#Override
protected void doInBackground() throws IOException {
BatchRequest batch = client.batch();
for (Event event : events) {
client.events().insert(calender.id, event).queue(batch,
new JsonBatchCallback<Event>() {
public void onSuccess(Event event, GoogleHeaders headers) {
//TODO show succes message.
}
#Override
public void onFailure(GoogleJsonError err, GoogleHeaders headers)
throws IOException {
Utils.logAndShowError(activity, EventActivity.TAG, err.getMessage());
}
});
}
batch.execute();
}
If I use this then get a an exception and the app crashes
W/dalvikvm(21030): threadid=20: thread exiting with
uncaught exception (group=0x40c19930)
E/AndroidRuntime(21030): FATAL EXCEPTION: AsyncTask #2
E/AndroidRuntime(21030): java.lang.RuntimeException: An error occured
while executing doInBackground()
The full stacktrace of the error can be found here at pastebin log.txt. Does anyone know how to fix this or did I implement the code incorrectly? the whole code can be found here at pastbin AsyncBatchInsertEvent.java

Stupid me, the arraylist events was empty cause i checked a string == string instead of string.equels(string).

Related

LibGDX http request not working

I want to send a String message to database when user presses a specific button in the LibGDX game I am designing for android. How do I go about doing that? Following is the code I tried. But it does not work.
Net.HttpRequest httpRequest = new Net.HttpRequest();
httpRequest.setMethod("POST");
httpRequest.setUrl("URL is here");
httpRequest.setContent("INSERT INTO `game_table` (`Button`) VALUES ('Button 1 Pressed')");
Net.HttpResponseListener httpResponseListener = new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
Gdx.app.log("Log httpResponse", httpResponse.getResultAsString());
}
#Override
public void failed(Throwable t) {
}
#Override
public void cancelled() {
}
};
Gdx.net.sendHttpRequest(httpRequest,httpResponseListener);
Log does not provide anything in android monitor. I also tried using AsyncTask and without AsyncTask to implement this code. But neither works.
Am I missing something? If so could you give me small code snippet that will work?
You don't need to use an AsyncTask, libGDX' HTTPRequest is async out of the box.
You did not log anything if the request fails or is cancelled so probably that's the case.

Android Studio Hola CDN onAttach method not working for ExoPlayer

I have integrated Hola CDN in my android app & when I am trying to attach my ExoPlayer after connection established with Hola CDN by doing this-
if(api.is_connected())
api.attach(player.get_player(), userAgent, new TransferListener() {
#Override
public void onTransferStart() {
System.out.print("start");
}
#Override
public void onBytesTransferred(int i) {
System.out.print("start byte");
}
#Override
public void onTransferEnd() {
System.out.print("start end");
}
}, videoUrl);
,It gives this error -
java.lang.IllegalArgumentException at
com.google.android.exoplayer.util.Assertions.checkNotEmpty(Assertions.java:122)
As per my understanding & references. Getting java.lang.IllegalArgumentException means passing undesired param. In your case, Assertions.checkNotEmpty()method needs NON EMPTY String. But, getting NULL String due to something [that you need to trace out] & that's the reason your are getting above exception.
Giving you the below description,
checkNotEmpty(String string) Throws IllegalArgumentException if string
is null or zero length.
on
1]https://google.github.io/ExoPlayer/doc/reference/com/google/android/exoplayer2/util/Assertions.html
2]https://google.github.io/ExoPlayer/doc/reference/com/google/android/exoplayer2/util/Assertions.html#checkNotEmpty-java.lang.String-
If you fix this then rest of the things might work as you expect.

Retrofit custom error handler + sync & asyc requests

I have a custom error handler that checks RetrofitError it gets passed and rethrows it as custom exceptions
private static ErrorHandler getErrorHandler() {
return new ErrorHandler() {
#Override
public Throwable handleError(RetrofitError cause) {
switch (cause.getKind()) {
case NETWORK: return new NetworkException(cause);
case HTTP: return new ApiException(cause);
default: return cause;
}
}
};
}
If this is my endpoint
#GET(USERS_GET_URL)
User getUsers() throws NetworkException, ApiException;
while executing synchronous request I try...catch and handle each custom exception as I want. When it is done asynchronously using
#GET(USERS_GET_URL)
void getUsers(Callback<User> cb) throws NetworkException, ApiException;
the handled exception gets rethrown as RetrofitError. The following snippet of code is from CallbackRunnable class of Retrofit which executes the request
try {
final ResponseWrapper wrapper = obtainResponse();
callbackExecutor.execute(new Runnable() {
#Override public void run() {
callback.success((T) wrapper.responseBody, wrapper.response);
}
});
} catch (RetrofitError e) {
Throwable cause = errorHandler.handleError(e);
final RetrofitError handled = cause == e ? e : unexpectedError(e.getUrl(), cause);
callbackExecutor.execute(new Runnable() {
#Override public void run() {
callback.failure(handled);
}
});
}
As it can be seen, my custom exceptions are getting rethrown as RetrofitError which makes me loose valuable information. Is there any way I can bypass custom error handling for just the async requests?
In your ErrorHandler you pathing original RetrofitError as cause, so as result in your Callback#failure(RetrofitError error) to get actual information you need to write next code: error.getCause().getCause(). This error will contain response that server send with all the data.
But error handler was created for sync request and after some time square team decided to close this gap this way. For more info you can read: https://gist.github.com/benvium/66bf24e0de80d609dac0
As for me, I don't recommend to use ErrorHander for async way, because I don't find any good solution to handle different types of error. It was much easier to get data right from initial RetrofitError.

Android not waiting for DB response before finishing statement

I have an interesting problem that I've never run into in programming before. I have an onClickListener that does a lot of username and password checks (makes sure the username is proper length, not taken, etc). I'm using MobDB, and I was using a conditional statement that would return a row if the username already existed. The problem is that the Listener skips the DB and goes to the final check that, if everything works, posts a new username and password to my DB. How can I make it wait for a response from the DB before skipping to the last check?
Here is the relevant code:
usernamecheck3 = true;
MobDB.getInstance().execute(APP_KEY, null, rd, null, false, new MobDBResponseListener() {
#Override public void mobDBSuccessResponse() {
usernamecheck3 = false;
Log.e("mobdbSuccess:", "success");
}
#Override public void mobDBResponse(Vector<HashMap<String, Object[]>> row) {
}
#Override public void mobDBResponse(String jsonObj) {
/*Log.e("mobdbSuccess:", "jsonObj");
Log.e("mobdbSuccess:", jsonObj);
JSONObject mainObject;
try {
mainObject = new JSONObject(jsonObj);
// need to parse the json object.
} catch (JSONException e1) {
e1.printStackTrace();
} */
}
#Override public void mobDBFileResponse(String fileName, byte[] fileData) {
//get file name with extension and file byte array
}
#Override public void mobDBErrorResponse(Integer errValue, String errMsg) {
usernamecheck3 = false;
Log.e("doesnt", "work");
}
});
if(usernamecheck3 == false){
Toast.makeText(getApplicationContext(), "Username is taken, please choose another", Toast.LENGTH_SHORT).show();
}
Basically the check always returns true, and then logcat will say mobdbSuccess: success, which should have set the Bool to false.
Thanks.
MobDBResponseListener is executing on a different thread. What happens here is that the processing is split, while a thread is doing the query, the main thread on which you added the listener, skips right ahead to the validation. Your best bet is to place the validation inside the MobDBResponseListener, on the mobDBResponse method.
Try to debug your code and calls, the Listener may be using an async task. If so, you may do anything you please from the response method, as it will be executing in the main thread again. Otherwise, you should look at solutions that handle threaded execution like Handlers

Robolectric.getSentHttpRequest(0) throws IndexOutOfBoundsException

I'm trying to test retrofit with robolectric. But I always get an IndexOutOfBoundsException when I call Robolectric.getSentHttpRequest(0). Can anyone help me?
here is my code:
#Before
public void setup() {
Robolectric.setDefaultHttpResponse(200, "OK");
commonRequest = RequestFactory.getRestAdapter().create(CommonRequest.class);
}
#Test
public void testGet_shouldApplyCorrectHeaders() throws Exception {
commonRequest.register("Token", "{}", null);
HttpRequest sentHttpRequest = Robolectric.getSentHttpRequest(0);
assertThat(sentHttpRequest.getHeaders("Authorization")[0].getValue(), equalTo("Token"));
}
Thank you very much.
It seems that you're missing the send request part. That's why you keep getting IndexOutOfBoundsException. You should send the request first take a look in the first example (testGet_FormsCorrectRequest_noBasicAuth) here

Categories

Resources