Passing a bitmap/uri to Box Android API v2 - android

EDIT:
I wrote a function passing the Authenticated Box Client and Bitmap Bytestream. Was also informated the root directory on Box has an ID of 0. But I'm still unable to upload.
What I need to do is create a directory, if present don't and upload the file in that directory.
private void doUpload(final BoxAndroidClient client, final ByteArrayInputStream bs) {
if(client.isAuthenticated())
{
System.out.println("Trying to upload: In upload function");
AsyncTask<Null, Integer, Null> task = new AsyncTask<Null, Integer, Null>() {
#Override
protected void onPostExecute(Null result) {
Toast.makeText(PagerActivity.this, "done uploading", Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
Toast.makeText(PagerActivity.this, "start uploading", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
#Override
protected Null doInBackground(Null... params) {
try {
BoxDefaultRequestObject folreqObj = new BoxDefaultRequestObject();
BoxFolder newFol = new BoxFolder();
String parentId = newFol.getId();
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject("0", "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
/*
if(client.getFoldersManager().getFolder(parentId, folreqObj).getName()!=null)
{
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(parentId, "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
}
else
{
BoxFolderRequestObject upreqObj = BoxFolderRequestObject.createFolderRequestObject("BestPhotoNow", parentId);
client.getFoldersManager().createFolder(upreqObj);
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(parentId, "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
}*/
} catch (BoxRestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoxJSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoxServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthFatalFailureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
};
task.execute();
}
}
So, I have a wallpaper app that fetches some images from a server. I'm trying to integrate box to be able to upload the picture in the current view (viewpager) to Box via Box Android API v2.
https://github.com/box/box-android-sdk-v2
I have been successful to authenticate the user via oauth. But, I'm really stuck at trying to upload the bitmap or uri direct to their upload call without having to launch a folder picker activity. This is what I have.
On click of a button for upload:
case R.id.boxcloudbutton:
imageLoader.loadImage(url, new SimpleImageLoadingListener(){
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
Intent intent = OAuthActivity.createOAuthActivityIntent(getApplicationContext(), "vfoj4o6nxqblahh454wem", "J9TQWyFSblahV2C", false, "http://localhost");
intent.putExtra("boximageUri", imageUri);
System.out.println("BoxUri: "+imageUri);
startActivityForResult(intent, BOX_RESULT);
super.onLoadingComplete(imageUri, view, loadedImage);
}
});
break;
I'm trying to pass either the bitmap or uri
and in the OnActivityResult
case BOX_RESULT:
if (resultCode == Activity.RESULT_CANCELED) {
// Get the error message for why authentication failed.
String failMessage = data.getStringExtra(OAuthActivity.ERROR_MESSAGE);
// Implement your own logic to handle the error.
// handleFail(failMessage);
} else {
// You will get an authenticated oath token object back upon success.
BoxAndroidOAuthData oauth = data.getParcelableExtra(OAuthActivity.BOX_CLIENT_OAUTH);
// If you don't want to supply a customized hub or parser, use null to fall back to defaults.
BoxAndroidClient client = new BoxAndroidClient( "vfoj4oxxxxxxxxxxtordlh454wem",
"J9TjxxxxxxxmRwux2V2C", null, null, null);
client.authenticate(oauth);
System.out.println("Data for Box: "+data.getExtras().getString("boximageUri"));
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(0, "name", file);
BoxFile bFile = client.getFilesManager().uploadFile(requestObj);
}
break;
Here, I successfully get authenticated, but I do not recieve the uri or the bitmap in the Intent data that I passed.
More, if anyone has any idea of how I can pass bitmap to a file for a file upload for Box api v2, I would really appreciate some assistance!
Thanks,
Arnab

Try shifting around the responsibility....
When you go to the Oauth activity , do just the authentication and return the credentials or Token from that which grants permission for subsequent actions on Box api.
Choose correct api to POST a bitmap... Here you want an api call that allows the ByteArray corresponding to the bitMap to be loaded as a ByteArrayEntity in the body of a http POST action.
This answer sample of how to prepare a local bitmap instance for being wrapped in body of Post as byteArray.

Related

saveInBackground throws exception "unsaved ParseObject"

I'm trying to save an item which has a relation to my image class. I can save the item, and i can save the image seperately, but when I am saving them with the relation if throws this error:
unable to encode an association with an unsaved ParseObject
Here is my code:
myAdvert = new ParseObject("Items");
myAdvert.put("title", "some title");
if (pic1Set) {
Bitmap bitmap = ((BitmapDrawable) pic1.getDrawable())
.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
myPhoto1 = new ParseObject("Images");
filePhoto = new ParseFile("image.png", byteArray);
filePhoto.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
myPhoto1.put("image", filePhoto);
ParseRelation relation = myAdvert.getRelation("pictures");
relation.add(myPhoto1);
myAdvert.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
// TODO Auto-generated method stub
if (e != null) {
--> // THIS IS WHERE THE ERROR IS THROWN!!!!
Log.d("error", e.toString());
} else {
}
}
});
} else {
Log.d("wow, error", e.toString());
Toast.makeText(getApplicationContext(),
"Error saving: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
lets consider this a comment and some extra info rather then an answer -
I'm running to the same exception when trying to login BUT it will happen only after I have some action done offline while the local data store is working
I also have ACL on.
I'm guessing it has something to do with an attempt to save stuff pinned from my offline work in a wrong order or something.
I'm working on debugging mine - good luck to all of us - let me know if you find something.

facebook login error. unable to get user_birthday and user_location

Hi i am using facebook to login to my app. I am unable to get user
birthday and user location from facebook. Below is the method used to get the details from user. I am using activity class for login.
private void loginFacebook() {
// TODO Auto-generated method stub
if (!facebook.isSessionValid()) {
final Session.OpenRequest request = new
Session.OpenRequest(LoginActivity.this);
facebook.authorize(this, new String[] {
"email","user_birthday","user_about_me","user_location"
}, new LoginDialogListener());
} else {
getProfileInformation();
}
}
public void getProfileInformation() {
// TODO Auto-generated method stub
try {
profile = Util.parseJson(facebook.request("me"));
mUserId = profile.getString("id");
Gloabalvariables.setUserID(mUserId);
mUserToken = facebook.getAccessToken();
mUserName = profile.getString("name");
mUserEmail = profile.getString("email");
JSONObject c=new JSONObject(profile.getString("location"));
mUserhomeTown=c.getString("name");
new insertintoServer().execute();
//getOnlineFreindList();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + mUserName "\nEmail+"+ mUserEmail, Toast.LENGTH_LONG).show();
}
});
} catch (FacebookError e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here the problem is i can able to get user_birthday and user_location from the user only for the account which i created app id. For other account i am unable to get those details. i am struggle for two days. But i dint find what i did wrong in the code.
Go to Facebook Developer Console set permissions:
Facebook Graph API Explorer
There:
Application
Get Access Token: Here select your fieds which you want.
Search For Field
Submit
Save Session

I want to retrieve the usersinfo of the current user in Box API v2 for Android

Please help me in getting the user details for the current user in the BoxApi v2 for android
The code which I am using the user details is as follows:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
BoxAndroidClient client = null;
if (Activity.RESULT_OK != AUTH_REQUEST) {
Toast.makeText(this, "fail", Toast.LENGTH_LONG).show();
} else {
BoxAndroidOAuthData oauth = data
.getParcelableExtra(OAuthActivity.BOX_CLIENT_OAUTH);
BoxAndroidOAuthData moath = data
.getParcelableExtra(OAuthActivity.USER_SERVICE);
client = new BoxAndroidClient(HelloWorldApplication.CLIENT_ID,
HelloWorldApplication.CLIENT_SECRET, null, null);
client.authenticate(oauth);
accestoken = oauth.getAccessToken().toString();
System.out.println("AUTHDATA" + oauth.getAccessToken().toString());// client.getUsersManager().getCurrentUser(requestObj).toString()
// + oauth.getAccessToken().toString());
BoxUser user = new BoxUser();
System.out.println("ID" + user.getId());
if (client == null) {
Toast.makeText(this, "fail", Toast.LENGTH_LONG).show();
} else {
((HelloWorldApplication) getApplication()).setClient(client);
Toast.makeText(this, "authenticated", Toast.LENGTH_LONG).show();
}
}
BoxDefaultRequestObject requestObject = null;
List<BoxUser> userList = null;
try {
userList = client.getUsersManager().getAllEnterpriseUser(
requestObject, null);
} catch (BoxRestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoxServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthFatalFailureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (BoxUser usr : userList) {
System.out.println("Addr: " + usr.getAddress());
System.out.println("Name : " + usr.getName());
System.out.println("Login : " + usr.getLogin());
}
}
I am getting the exception as networkonmainthreadexception...
Can anybody please help me?
Getting current user info in the raw api is done with a call to GET /users/me
Not sure what that looks like in the Java, but probably something more like :
user = client.getUsersManager().getCurrentUser
Make sure your access token is up to date. Also, looking at your code, why have you set
BoxDefaultRequestObject requestObject = null;
Instead do:
BoxDefaultRequestObject requestObject = new BoxDefaultRequestObject()
Otherwise the box library will get a null pointer exception. It gets the JSON parser from the request object.
Let me know if this works.

Authenticate Android App

I am new to android and I am building an app that I want to authenticate using the local users google account. Unfortunately I have gotten myself in a bit of a bind looking at Auth 2.0 and logging in via the google services.
What is the recommended route to authenticate (and hopefully not require typing a login name)? I tried many of the samples that I saw but much of it seems deprecated.
Any example code would be very helpful as well.
I was using this tutorial but it is a bit outdated and I believe that it is much simplier now.
http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app
Thanks,
Craig
Here is how I solved it. Don't know if it is the recommended approach but it works...
in OnCreate of my entry activity (main) I put...
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
AccountManagerFuture<Bundle> futur;
futur = accountManager.getAuthToken(accounts[0],AUTH_TOKEN_TYPE_USERINFO_PROFILE, null, null,
new OnTokenAcquired(), new Handler(new OnError()));
In that same activity I created...
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
// Get the result of the operation from the AccountManagerFuture.
Bundle bundle;
try {
bundle = result.getResult();
// The token is a named value in the bundle. The name of the
// value
// is stored in the constant AccountManager.KEY_AUTHTOKEN.
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
//If token isn't null then let them in and also make sure Crunchy accounts are created
if(token!=null){
ProcessToken pt = new ProcessToken(token);
pt.execute("");
}
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 0);
return;
}
}catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I also created an asyncTask to process the token (because I do a bit more logic to setup account and set a cookie). It looks like this (much of my processing/cookie logic is not completed yet)
package com.craig.activities.login;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
public class ProcessToken extends AsyncTask<String,Integer,Long>{
private static final String AUTH_ACCESS_TOKEN_URL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
private static final String DEBUG_TAG = "OnTokenAcquired.class";
private static String token="";
public ProcessToken(String tokenValue){
token=tokenValue;
}
#Override
protected Long doInBackground(String... params) {
try {
URL url = new URL(AUTH_ACCESS_TOKEN_URL+token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int serverCode= con.getResponseCode();
if(serverCode==200){
Log.i(DEBUG_TAG, "code 200!!!");
//PUT MY LOGIC IN HERE....
}
else{
Log.i(DEBUG_TAG, "Oops, We had an error on authentication");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Not sure if this is the best but it seems to be working for me....

Facebook wall post from multiple Activities

I have been trying to make wall post from multiple pages but when i try to make post from other pages except original facebook page, it is giving me an exception of java.lang.NullPointerException
The method i am calling and created in a Facebook page.
public void setConnection() {
mContext = this;
mFacebook = new Facebook(getResources().getString(R.string.FACEBOOK_ID_TEST));
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
public boolean isSession() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
String access_token = sharedPrefs.getString("access_token", "x");
Long expires = sharedPrefs.getLong("access_expires", -1);
Log.d(TAG, access_token);
if (access_token != null && expires != -1) {
mFacebook.setAccessToken(access_token);
mFacebook.setAccessExpires(expires);
}
return mFacebook.isSessionValid();
}
public void getID()
{
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
try {
mFacebook.request("me/friends", bundle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error in FaceBook Friends List","Exception = "+e.getMessage());
e.printStackTrace();
}
if (isSession()) {
Log.d(TAG, "sessionValid");
try {
mFacebook.request("me/friends", bundle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error in FaceBook Friends List","Exception = "+e.getMessage());
e.printStackTrace();
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
}
}
I am able to get the wall post dialog box but its showing "An error occurred. Please try again later".
Please help me out.
Thanks in advance.
I think the best way for you to achieve this would be to make an abstract class which extends the super class Activity, use this to hold all your facebook functions.
Then when you want to have an activity which has the facebook functionality then you would just extend this abstract class. If your not sure what I mean then take a look at the tutorial here, it goes through how to setup a basic Facebook Activity class. Hope this helps.

Categories

Resources