Uploading image to Google Drive using GWT-Google Picker - gwt

I am trying to upload an image to Google Drive using Google Picker user interface. So far i have been unsuccessful.
This is the code that i am using :
private void onCreatePicker(ViewId viewId) {
final Picker picker = PickerBuilder.create()
.setTitle("Subir imagen a Google Drive")
.addView(viewId)
.addView(DocsUploadView())
.setLocale("es")
.setOAuthToken(token_oauth2)
.setDeveloperKey(DEVELOPER_KEY)
.setCallback(buildPickerCallback(viewId))
.build();
picker.setVisible(true);
}
private JavaScriptObject DocsUploadView() {
return com.ip.gae.gartla.shared.DocsUploadView.create();
}
I request your help on what could i be missing.
Thank you for your time,
Regards,
UPDATE: It seems that my application scope was wrong. In order to generate the correct oAuth2Token, you must declare the scope which you want to generate the token for:
The following its the method I am using to generate the token:
private void tokenOauth2() {
AuthRequest req = new AuthRequest(AUTH_URL, CLIENT_ID)
.withScopes(GOOGLE_DRIVE_SCOPE); // Can specify multiple scopes here
Auth.get().login(req, new Callback<String, Throwable>() {
#Override
public void onSuccess(String token) {
token_oauth2 = token;
}
#Override
public void onFailure(Throwable caught) {
// The authentication process failed for some reason, see caught.getMessage()
}
});
}
And here it is the GOOGLE_DRIVE_SCOPE variable that i am using:
String GOOGLE_DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
So, for now this is working for me. I have attached the solution so if someone finds it out interesting enough. :-)

Related

Why is onChanged() not called when observing LiveData

This question is a follow up to this problem here: How to make retrofit API call using ViewModel and LiveData
The mistakes 1 and 2 highlighted in that post's response have been fixed. For mistake 3, I haven't yet moved the API call to a repository, but I will once the code start working properly.
So I'm trying to make an API call using Retrofit, using MVVM with LiveData and ViewModel. The API call (which currently is in the ViewModel), is working properly, but the changes is not being picked up by the Observer in the Activity.
I've setup my ViewModel observer as follow:
public class PopularGamesActivity extends AppCompatActivity {
private static final String igdbBaseUrl = "https://api-endpoint.igdb.com/";
private static final String FIELDS = "id,name,genres,cover,popularity";
private static final String ORDER = "popularity:desc";
private static final int LIMIT = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popular_games);
PopularGamesViewModel popViewModel = ViewModelProviders.of(this).get(PopularGamesViewModel.class);
popViewModel.getGameList().observe(this, new Observer<List<Game>>() {
#Override
public void onChanged(#Nullable List<Game> gameList) {
String firstName = gameList.get(0).getName();
Timber.d(firstName);
}
And my ViewModel code is as follow:
public class PopularGamesViewModel extends AndroidViewModel {
private static final String igdbBaseUrl = "https://api-endpoint.igdb.com/";
private static final String FIELDS = "id,name,genres,cover,popularity";
private static final String ORDER = "popularity:desc";
private static final int LIMIT = 30;
public PopularGamesViewModel(#NonNull Application application) {
super(application);
}
public LiveData<List<Game>> getGameList() {
final MutableLiveData<List<Game>> gameList = new MutableLiveData<>();
// Create the retrofit builder
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(igdbBaseUrl)
.addConverterFactory(GsonConverterFactory.create());
// Build retrofit
Retrofit retrofit = builder.build();
// Create the retrofit client
RetrofitClient client = retrofit.create(RetrofitClient.class);
Call<List<Game>> call = client.getGame(FIELDS,
ORDER,
LIMIT);
call.enqueue(new Callback<List<Game>>() {
#Override
public void onResponse(Call<List<Game>> call, Response<List<Game>> response) {
Timber.d("api call sucesss");
if (response.body() != null) {
Timber.d("First game: " + response.body().get(0).getName());
gameList.setValue(response.body());
}
}
#Override
public void onFailure(Call<List<Game>> call, Throwable t) {
Timber.d("api call failed");
}
});
return gameList;
}
}
When I run the code, the onResponse in the ViewModel class will output the correct response from the API call, so the call is working properly. But the onChanged() in the PopularGamesActivity class will never get called. Can someone shed some light on what I'm doing wrong? Thank you!
Ok, so this turned out to be a weird android studio bug. I was initially running the code on my real nexus 4 device, and the onChange never gets called. However, after running it on an emulated device, it started working immediately. And now, it's working on my real device too.
I don't know the actual reason behind it, but if anyone in the future run into a problem where onChange won't get called, try switching device/emulators.
Cheers.
I debug the code on a device and have the same problem.
M'n solution was simply activate the device screen.
The screensaver was the problem..

UBER with SSO using uber rides-android-sdk

I'm trying to get data from ALL_TRIPS Scope. I'm running into a few issues.
1) once I add the Scope.All_Trips to the .setScopes I get redirected verse being able to login to obtain the Token, therefore I get the necessary data from the get CurrentRide() method.
configuration = new SessionConfiguration.Builder()
.setClientId(CLIENT_ID)
.setRedirectUri(REDIRECT_URI)
.setScopes(Arrays.asList(Scope.HISTORY, Scope.PROFILE, Scope.RIDE_WIDGETS, Scope.ALL_TRIPS))
.setEnvironment(SessionConfiguration.Environment.SANDBOX)
.build();
validateConfiguration(configuration);
Error: Webpage not available The webpage at
Market://details?hl-en&id=com.ubercab&referrer=mat_cli%3
And it goes on and one.
Once i remove the All_TRIPS SCOPE I get the ability to Sign in.
Any help would be great so that I can move forward with getting the details like driver, vehicle, RideID.
private void LoadAllTrips(){
Session session = loginManager.getSession();
RidesService AllTrips = UberRidesApi.with(session).build().createService();
AllTrips.getCurrentRide().enqueue(new Callback<Ride>() {
#Override
public void onResponse(Call<Ride> call, Response<Ride> response) {
if (response.isSuccessful())
{
Toast.makeText(LoginSampleActivity.this, response.body().getRideId(), Toast.LENGTH_LONG).show();
}
else
{
ApiError error = ErrorParser.parseError(response);
Toast.makeText(LoginSampleActivity.this, error.getClientErrors().get(0).getTitle(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Ride> call, Throwable t) {
}
});
}

Parse query always returns an empty list

I have the following problem:
I have two Android apps: In one app I add data to Mongo DB via Parse and in the other app I want to retrieve the information added from the first app.
The problem is that in the second app everytime I try to query the DB, I get an empty list. I`ve checked with the API KEY, with the keys from the Mongo DB, and everything seems ok in my app.
Here is the code for the second app to retrieve information in a RecyclerView
public class ParseDb extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId(API_KEY)
.server("http://injuriesandsuspensions.herokuapp.com/parse/")
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
public class MainActivity extends Activity {
private List<AboutTeams> aboutTeamsList = new ArrayList<AboutTeams>();
private RecyclerView recyclerView;
private GamesAdapter gamesAdapter;
public void retrieveGamesFromDatabase(){
ParseQuery<ParseObject> query = ParseQuery.getQuery("InjuriesAndSuspensions");
query.whereEqualTo("score", "none");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> gamesList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + gamesList.size() + " scores");
for(int i = 0; i < gamesList.size(); i++){
AboutTeams aboutTeams = new AboutTeams();
aboutTeams.setId(String.valueOf(gamesList.get(i).getObjectId()));
aboutTeams.setScore(String.valueOf(gamesList.get(i).get("score")));
aboutTeams.setHomeTeam(String.valueOf(gamesList.get(i).get("homeTeam")));
aboutTeams.setHomeTeamMissing(String.valueOf(gamesList.get(i).get("homeTeamMissingPlayers")));
aboutTeams.setAwayTeam(String.valueOf(gamesList.get(i).get("awayTeam")));
aboutTeams.setAwayTeamMissing(String.valueOf(gamesList.get(i).get("awayTeamMissingPlayers")));
aboutTeams.setDate(String.valueOf(gamesList.get(i).get("gameDate")));
Log.d("About Teams " , aboutTeams.toString());
aboutTeamsList.add(aboutTeams);
gamesAdapter.notifyDataSetChanged();
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_listview);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
gamesAdapter = new GamesAdapter(aboutTeamsList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(gamesAdapter);
retrieveGamesFromDatabase();
}
Please help as I`ve been struggling with this thing for almost 3 days.
When I was adding info to the Collection DB,the ParseObject I was using didn`t have this line added where I was initializing Parse in my application:
defaultACL.setPublicReadAccess(true);
Complete code on how to initialize Parse:
public class AddToDB extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId(API_KEY)
.server(SERVER_URL)
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
**defaultACL.setPublicReadAccess(true);**
ParseACL.setDefaultACL(defaultACL, true);
}
}

Facebook profile picture request i.e. "http://graph.facebook.com/me/picture"

When I do a request for a profile picture, mine in this case I receive some kind of encoded string in my HttpResponseHandler. The code below is the request for my profile picture.
private static AsyncHttpClient client = new AsyncHttpClient();
client.get("http://graph.facebook.com/1206433/picture", fbPictureHandler);
The code below is my handler to retrieve a response. I get the response as a string, but I am not sure what to do with this response object. I have tried converting to a byte array and writing to "file.jpg" this hasnt worked. My main question is what do I do with this response object?
private static AsyncHttpResponseHandler fbPictureHandler = new AsyncHttpResponseHandler ()
{
#Override
public void onStart() {
Log.d(TAG,"started picture handler");
}
#Override
public void onSuccess(String response) {
//Not sure what to do here, have been unable to do anything with this Byte //array
byte[] imageBackground = response.getBytes();
}
#Override
public void onFailure(Throwable error) {
Log.d(TAG, "unable to retrieve picture");
error.printStackTrace();
}
#Override
public void onFinish() {
Log.d(TAG,"Finished picture handler");
}
};
This is the PrintString of the response object
11-29 19:42:12.640: D/Yatter Facebook(3551): ÿØÿà��JFIF������������ÿþ��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 95
ANy help is greatly appreciated and hopefully this can help others.
Thank you,
Use the following request instead of the one that you are issuing
http://graph.facebook.com/1206433?fields=picture
This will return a JSON string to you in the following format which contains the original path to the profile image.
{
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/260615_1206433_140418666_q.jpg"
}
Parse this string to get the path of "picture" and use it in your code to get the picture.
Here is a sample request example
NOTE : http://profile.ak.fbcdn.net/hprofile-ak-snc4/260615_1206433_140418666_q.jpg is obtained by parsing the JSON string in the first step.
WebRequest request = WebRequest.Create("http://profile.ak.fbcdn.net/hprofile-ak-snc4/260615_1206433_140418666_q.jpg");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
pictureBox1.Image = Image.FromStream(stream);
This will load the image to a picture box in a windows form application.
If you need anymore help let me know.
you can use ?redirect=false follow '/picture' for get direct link
http://graph.facebook.com/+facebookid+/picture?redirect=false
and response contain url static link (json format)
{"data":{
"url":"https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-frc1\/t1.0-1\/c126.33.409.409\/s50x50\/551571_4079894629426_190963543_n.jpg","is_silhouette":false}
}

not able to set focus on TextBox in a GWT app

This should not be causing me so much pain but it is. It is a very weird problem. In a GWT application, I have two .java files, login.java and application.java.
In login.java, I'm creating a user login page where if the username and password is verified the user is logged into the application and application.java takes from here.
Now in application. java's onModuleLoad() this is how i'm starting with a login page.
public void onModuleLoad() {
Login login = new Login();
login.textBoxUsername.setFocus(true);
RootLayoutPanel.get().add(login);}
This works great, except for the tiny problem of not being able to set focus on the username TextBox when the page loads. I have tried evrything I can think of. But the focus just doesn't get set on the TextBox. If anyone can suggest a solution, please do. Your help is greatly appreciated.
Solution: (In case it helps anyone facing the same issue)
final Login login = new Login();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute () {
login.textBoxUsername.setFocus(true);
}
});
RootLayoutPanel.get().add(login);
Try using Scheduler.scheduleDeferred():
public void onModuleLoad() {
Login login = new Login();
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
public void execute () {
login.textBoxUsername.setFocus(true);
}
});
RootLayoutPanel.get().add(login);
}
Update: answer updated to use Scheduler.get().scheduleDeferred() instead of DeferredCommand, which is deprecated.
Why using DefferedCommand, I think it's better to use someWidget.getElement().focus() which is a native Javascript. I'm using it everywhere, I've not seen any problem.
If your Widget extends Composite, you can:
#Override
protected void onAttach() {
super.onAttach();
textBoxUsername.setFocus(true);
}
It would be so easy for GWT to store a 'wantsFocus' in the internal state, and call focus after the widget is attached. We are still waiting after many years for that feature however...
Still, even after the attach handler is called, setFocus does not always work.
So in the meantime, our GwtUtil library has used the following code. It is a combination of several other solutions, and has been wrapped in a utility function:
static public void setFocus(final FocusWidget focusWidget) {
if (focusWidget.isAttached()) {
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
#Override
public void execute() {
focusWidget.setFocus(true);
}
});
} else {
focusWidget.addAttachHandler(new AttachEvent.Handler() {
#Override
public void onAttachOrDetach(AttachEvent event) {
if (event.isAttached()) {
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
#Override
public void execute() {
focusWidget.setFocus(true);
}
});
}
}
});
}
}
And call it like this:
setFocus(myTextBox);
It makes sense to use a utility function; If and when GWT finally makes setFocus work, you won't have to change your source code in multiple places.